Full Code of kobe-koto/EdgeSub for AI

main f4c00115a68b cached
87 files
435.9 KB
106.3k tokens
642 symbols
1 requests
Download .txt
Showing preview only (465K chars total). Download the full file or copy to clipboard to get everything.
Repository: kobe-koto/EdgeSub
Branch: main
Commit: f4c00115a68b
Files: 87
Total size: 435.9 KB

Directory structure:
gitextract_a6ww6u21/

├── .gitattributes
├── .gitignore
├── LICENSE
├── astro.config.ts
├── bun.lockb
├── functions/
│   ├── _middleware.js
│   ├── internal/
│   │   ├── Converter/
│   │   │   ├── getClashMetaConfig.js
│   │   │   └── getSingBoxConfig.ts
│   │   ├── Dumpers/
│   │   │   ├── clash-meta.ts
│   │   │   ├── share-link.js
│   │   │   └── sing-box.js
│   │   ├── Parsers/
│   │   │   ├── clash-meta.js
│   │   │   ├── share-link.js
│   │   │   └── sing-box.js
│   │   ├── RuleProviderReader/
│   │   │   ├── Readers/
│   │   │   │   └── ini.js
│   │   │   └── main.js
│   │   ├── configs.ts
│   │   ├── data/
│   │   │   ├── rule/
│   │   │   │   ├── MetaToSingLogicalRule.ts
│   │   │   │   └── MetaToSingMapping.ts
│   │   │   └── ruleset/
│   │   │       └── transformGeoRef.ts
│   │   ├── getParsedSubData.ts
│   │   ├── types/
│   │   │   └── ClashMetaConfig.ts
│   │   └── utils/
│   │       ├── TrulyAssign.js
│   │       ├── fetchCached.ts
│   │       ├── parseContentDisposition.ts
│   │       └── removeUndefinedFields.ts
│   ├── ruleset/
│   │   ├── preprocessor/
│   │   │   └── sing-box.ts
│   │   └── proxy.ts
│   ├── short/
│   │   ├── admin-password/
│   │   │   ├── set.ts
│   │   │   └── status.ts
│   │   ├── delete/
│   │   │   └── [id].ts
│   │   ├── get/
│   │   │   └── [id].ts
│   │   ├── list.ts
│   │   ├── put.ts
│   │   ├── token-reset/
│   │   │   └── [id].ts
│   │   └── utils/
│   │       └── defaultHeader.ts
│   └── sub/
│       ├── base64.js
│       ├── clash-meta.js
│       ├── debug.js
│       ├── share-link.js
│       └── sing-box.js
├── package.json
├── public/
│   ├── basic-config/
│   │   ├── mihomo.yaml
│   │   └── sing-box.jsonc
│   └── minimal_remote_rules.ini
├── readme.md
├── src/
│   ├── components/
│   │   ├── NavBar.astro
│   │   ├── backendIndicator.astro
│   │   ├── data-input.astro
│   │   ├── index/
│   │   │   └── SubURLGenerator.astro
│   │   ├── k-dropdown.astro
│   │   ├── layouts/
│   │   │   └── SEOComponent.astro
│   │   └── shorter/
│   │       ├── k-shorter.astro
│   │       ├── short-destroyer.astro
│   │       ├── short-editor.astro
│   │       ├── short-token-reset.astro
│   │       ├── shorter-list.astro
│   │       └── shorter-password.astro
│   ├── config/
│   │   ├── AvalibleOptoutFormat.ts
│   │   └── RuleProviders.ts
│   ├── env.d.ts
│   ├── layouts/
│   │   └── base.astro
│   ├── pages/
│   │   ├── index.astro
│   │   └── shorter/
│   │       ├── admin.astro
│   │       ├── create.astro
│   │       ├── destory.astro
│   │       ├── edit.astro
│   │       ├── list.astro
│   │       └── reset-token.astro
│   ├── scripts/
│   │   ├── components/
│   │   │   ├── data-input.ts
│   │   │   ├── k-dropdown.ts
│   │   │   ├── k-suburl-generator.ts
│   │   │   └── shorter/
│   │   │       ├── k-shorter.ts
│   │   │       ├── short-destroyer.ts
│   │   │       ├── short-editor.ts
│   │   │       ├── short-token-reset.ts
│   │   │       ├── shorter-list.ts
│   │   │       └── shorter-password.ts
│   │   └── utils/
│   │       ├── copy.ts
│   │       ├── filterObject.ts
│   │       └── getDefaultBackend.ts
│   └── styles/
│       ├── app.scss
│       ├── import.css
│       ├── index.scss
│       └── main.scss
├── tsconfig.json
└── types/
    └── worker-configuration.d.ts

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitattributes
================================================
# Auto detect text files and perform LF normalization
* text=auto


================================================
FILE: .gitignore
================================================
# build output
dist/
_worker.bundle

# generated types
.astro/
.wrangler/

# dependencies
node_modules/

# logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*

# IDE files
.idea/
.vscode/

# environment variables
.env
.env.production

# macOS-specific files
.DS_Store

# others
*.bak
*.kate-swap
wrangler.toml


================================================
FILE: LICENSE
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU Affero General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time.  Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.


================================================
FILE: astro.config.ts
================================================
import { defineConfig } from "astro/config";

// astro integrations
import compress from "astro-compress";
import icon from "astro-icon";

// vite plugins
import tailwindcss from "@tailwindcss/vite";

export default defineConfig({
    prefetch: true,
    integrations: [
        compress(),
        icon(),
    ],
    vite: {
        css: {
            preprocessorOptions: {
                scss: {
                    api: "modern-compiler"
                }
            }
        },
        plugins: [
            tailwindcss(),
        ],
        // log dropping not enabled by default cuz this project will never be production ready lol
        // esbuild: {
        //     drop: ["console", "debugger"],
        // },
    },
});


================================================
FILE: functions/_middleware.js
================================================
async function RequestInfo (context) {
    const Path = (new URL(context.request.url)).pathname;
    console.info("[Main] Processing request...")
    console.info(`[Main] Request type: ${Path}`)

    return await context.next();
}

async function PerformanceCounting (context) {
    const __startTime = performance.now();

    const response = await context.next();
    
    console.info(`[PerformanceCounting] we've done this glory, totally wasting ${performance.now() - __startTime}ms.`)

    return response;
}

export const onRequest = [RequestInfo, PerformanceCounting];

================================================
FILE: functions/internal/Converter/getClashMetaConfig.js
================================================
import { TrulyAssign } from "../utils/TrulyAssign";
import { parseYAML } from "confbox";
import ClashMetaDumper from "../Dumpers/clash-meta.js";

const BasicConfig = {
    isUDP: true,
    isSSUoT: false,
    isInsecure: true,
    RuleProvider: "https://raw.githubusercontent.com/kobe-koto/EdgeSub/main/public/minimal_remote_rules.ini",
    RuleProvidersProxy: false,
    BaseConfig: "http://localhost:4321/basic-config/mihomo.yaml",
    // BaseConfig: "https://raw.githubusercontent.com/kobe-koto/EdgeSub/main/public/basic-config/mihomo.yaml",
    isForcedRefresh: false
}


import { RuleProviderReader } from "../RuleProviderReader/main.js";

export async function getClashMetaConfig (
    Proxies, 
    EdgeSubDB, 
    PassedConfig = {},
) {
    const Config = TrulyAssign(BasicConfig, PassedConfig);

    console.log(`[getClashMetaConfig] fetching base config from remote (${Config.BaseConfig})`)
    const ClashConfig = parseYAML(await fetch(Config.BaseConfig).then(res => res.text()));
    console.log("[getClashMetaConfig] fetched base config", ClashConfig)

    let RuleProvider = await (new RuleProviderReader(Config.RuleProvider)).Process(EdgeSubDB, Config.isForcedRefresh)

    let Dumper = new ClashMetaDumper(Config.isUDP, Config.isSSUoT, Config.isInsecure)
    
    // validate proxies
    Proxies = Proxies.map(i => {
        if (Dumper.__validate(i)) {
            i.Hostname = i.Hostname.replace(/(^\[|\]$)/g, "");
            return i;
        }
    }).filter(i => !!i);
    // append proxies
    ClashConfig.proxies = Proxies.map(i => Dumper[i.__Type](i));

    

    // Append proxy groups.
    ClashConfig["proxy-groups"] = []
    for (let i of RuleProvider.ProxyGroup) {

        // get Matched Proxies
        let MatchedProxies = [];
        for (let t of i.RegExps) {
            MatchedProxies = [ ...MatchedProxies, ...Proxies.filter( loc => loc.__Remark.match(new RegExp(t)) ) ]
        }
        // unique proxy
        MatchedProxies = Array.from(new Set(MatchedProxies));



        // generate proxies list 
        let GroupProxies = [];
        for (let t of i.GroupSelectors) {
            GroupProxies.push(t.replace(/^\[\]/, ""))
        }
        for (let t of MatchedProxies) {
            GroupProxies.push(t.__Remark)
        }
        if (MatchedProxies.length + i.GroupSelectors.length === 0) {
            // add fallback selector if no selector can be added
            GroupProxies.push("DIRECT")
            GroupProxies.push("REJECT")
        }

        //generate proxy group
        let ProxyGroup = {}
        ProxyGroup.name = i.name;
        ProxyGroup.type = i.type;
        if (i.type === "url-test" || i.type === "load-balance" || i.type === "fallback") {
            ProxyGroup.url = i.TestConfig.TestURL;
            ProxyGroup.interval = i.TestConfig.Interval;
        }
        if (i.type === "url-test") {
            ProxyGroup.tolerance = i.TestConfig.Tolerance;
        }
        ProxyGroup.proxies = GroupProxies;

        // append proxy group to config
        ClashConfig["proxy-groups"].push(ProxyGroup)
    }

    // append rule providers
    ClashConfig["rule-providers"] = {};
    let RuleProvidersMapping = {}; // { URL: ID }[]
    for (let i in RuleProvider.RuleProviders) {
        for (let t in RuleProvider.RuleProviders[i]) {
            const RuleProviderPayload = RuleProvider.RuleProviders[i][t];
            const RuleProviderID = `${i}__${t}`;
            RuleProvidersMapping[RuleProviderPayload] = RuleProviderID;
            let RuleProviderURL;
            if (Config.RuleProvidersProxy) {
                let RuleProviderURLObject = new URL(Config.RuleProvidersProxy);
                RuleProviderURLObject.pathname = "/ruleset/proxy"
                RuleProviderURLObject.search = ""
                RuleProviderURLObject.searchParams.append("target", RuleProviderPayload)
                RuleProviderURL = RuleProviderURLObject.toString()
            } else {
                RuleProviderURL = RuleProviderPayload;
            }
            ClashConfig["rule-providers"][RuleProviderID] = {
                type: "http",
                behavior: "classical",
                url: RuleProviderURL,
                format: (RuleProviderPayload.endsWith(".yaml") || RuleProviderPayload.endsWith(".yml")) ? "yaml" : "text",
                interval: 21600
            }
        }
    }

    // Append rule sets;
    ClashConfig.rules = []
    for (let i of RuleProvider.Rules) {
        
        const rulesetBreakdown = i.split(",")
        const id = rulesetBreakdown[0];
        let payload = rulesetBreakdown.slice(1).join(",");
        if (payload.startsWith("http://") || payload.startsWith("https://")) {
            payload = `RULE-SET,${RuleProvidersMapping[payload]}`;
        }
        ClashConfig.rules.push(`${payload},${id}`)
    }

    return ClashConfig;
}


================================================
FILE: functions/internal/Converter/getSingBoxConfig.ts
================================================
import { TrulyAssign } from "../utils/TrulyAssign";
import SingBoxDumper from "../Dumpers/sing-box.js";
import { MetaToSingRuleMapping } from "../data/rule/MetaToSingMapping.ts";
import { MetaToSingLogicalRule } from "../data/rule/MetaToSingLogicalRule.ts";
import { transformGeoRef } from "../data/ruleset/transformGeoRef.ts";
import { parseJSON5 } from "confbox";

const BasicConfig = {
    isUDP: true,
    isSSUoT: true,
    isInsecure: true,
    RuleProvider: "https://raw.githubusercontent.com/kobe-koto/EdgeSub/main/public/minimal_remote_rules.ini",
    RuleProvidersProxy: true, // this is required
    BaseConfig: "https://raw.githubusercontent.com/kobe-koto/EdgeSub/main/public/basic-config/sing-box.jsonc",
    isForcedRefresh: false
}


import { RuleProviderReader } from "../RuleProviderReader/main.js";
import mod from "astro/zod";

export async function getSingBoxConfig (
    Proxies, 
    EdgeSubDB, 
    PassedConfig = {},
) {
    const Config = TrulyAssign(BasicConfig, PassedConfig);
    if (!Config.RuleProvidersProxy) {
        throw new Error("RuleProvidersProxy is required for SingBox config generation.");
    }

    console.log(`[getSingBoxConfig] fetching base config from remote (${Config.BaseConfig})`)
    const SingBoxConfig = parseJSON5(await fetch(Config.BaseConfig).then(res => res.text())) as any;
    console.log("[getSingBoxConfig] fetched base config", SingBoxConfig)

    // Process OutBounds
    let Dumper = new SingBoxDumper(Config.isUDP, Config.isSSUoT, Config.isInsecure);
    // validate proxies
    Proxies = Proxies.map(i => {
        if (Dumper.__validate(i)) {
            return i;
        }
    }).filter(i => !!i);
    // append proxies
    SingBoxConfig.outbounds = SingBoxConfig.outbounds || [];
    SingBoxConfig.outbounds = [
        ...SingBoxConfig.outbounds, 
        ...Proxies.map(i => Dumper[i.__Type](i))
    ]
    // check for essential outbounds
    if (!SingBoxConfig.outbounds.find(i => i.tag === "DIRECT")) {
        SingBoxConfig.outbounds.push({
            type: "direct",
            tag: "DIRECT"
        })
    }
    if (!SingBoxConfig.outbounds.find(i => i.tag === "REJECT")) {
        SingBoxConfig.outbounds.push({
            type: "block",
            tag: "REJECT"
        })
    }

    // proxy clash external ui archive
    if (SingBoxConfig.experimental.clash_api.external_ui_download_url) {
        let ClashWebUIURLObject = new URL(Config.RuleProvidersProxy);
            ClashWebUIURLObject.pathname = "/ruleset/proxy";
            ClashWebUIURLObject.search = "";
            ClashWebUIURLObject.searchParams.append("target", SingBoxConfig.experimental.clash_api.external_ui_download_url);
        SingBoxConfig.experimental.clash_api.external_ui_download_url = ClashWebUIURLObject.toString();
    }


    // RULES!;
    let RuleProvider = await (new RuleProviderReader(Config.RuleProvider)).Process(EdgeSubDB, Config.isForcedRefresh)
    console.log(RuleProvider)

    // Append proxy groups.
    // SingBoxConfig.outbounds = []
    // GLOBAL selector
    SingBoxConfig.outbounds.push({
        tag: "GLOBAL",
        type: "selector",
        outbounds: [ "DIRECT", "REJECT", ...Proxies.map(i => i.__Remark)]
    })
    // Respect RuleProvider
    for (let i of RuleProvider.ProxyGroup) {

        // get Matched Proxies
        let MatchedProxies = [];
        for (let t of i.RegExps) {
            MatchedProxies = [ ...MatchedProxies, ...Proxies.filter( loc => loc.__Remark.match(new RegExp(t)) ) ]
        }
        // unique proxy
        MatchedProxies = Array.from(new Set(MatchedProxies));


        // generate proxies list 
        let GroupProxies = [];
        for (let t of i.GroupSelectors) {
            GroupProxies.push(t.replace(/^\[\]/, ""))
        }
        for (let t of MatchedProxies) {
            GroupProxies.push(t.__Remark)
        }
        if (MatchedProxies.length + i.GroupSelectors.length === 0) {
            // add fallback selector if no selector can be added
            GroupProxies.push("DIRECT")
            GroupProxies.push("REJECT")
        }

        //generate proxy group
        let ProxyGroup: {
            type: string,
            tag: string,
            outbounds: string[],
            url?: string | URL, // for url-test onlly
            interval?: string, // for url-test onlly
            tolerance?: string, // for url-test onlly
        } = {
            tag: i.name,
            type: "", // placeholder... change it later
            outbounds: GroupProxies
        }


        if (i.type === "select") {
            ProxyGroup.type = "selector"
        } else if (i.type === "url-test" || i.type === "load-balance" || i.type === "fallback") {
            ProxyGroup.type = "urltest"

            ProxyGroup.url = i.TestConfig.TestURL;
            ProxyGroup.interval = `${i.TestConfig.Interval}s`;

            if (i.type === "url-test") {
                ProxyGroup.tolerance = i.TestConfig.Tolerance;
            }
            if (i.type === "load-balance" || i.type === "fallback") {
                console.log(`[getSingBoxConfig] ${i.name} fallback to urltest`)
            }
        }

        // append proxy group to config
        SingBoxConfig.outbounds.push(ProxyGroup)
    }

    // Append rule-sets
    // SingBoxConfig.route.rule_set = [];
    let RuleProvidersMapping = {}; // { URL: ID }[]
    for (let i in RuleProvider.RuleProviders) {
        for (let t in RuleProvider.RuleProviders[i]) {
            const RuleProviderPayload = RuleProvider.RuleProviders[i][t];
            const RuleProviderID = `${i}__${t}`;
            RuleProvidersMapping[RuleProviderPayload] = RuleProviderID;

            // construct RuleProviderURL
            let RuleProviderURLObject = new URL(Config.RuleProvidersProxy);
                RuleProviderURLObject.pathname = "/ruleset/preprocessor/sing-box"
                RuleProviderURLObject.search = ""
                RuleProviderURLObject.searchParams.append("target", RuleProviderPayload)
            const RuleProviderURL = RuleProviderURLObject.toString()
            SingBoxConfig.route.rule_set.push({
                type: "remote",
                tag: RuleProviderID,
                format: "source",
                url: RuleProviderURL,
                download_detour: "DIRECT"
            })
        }
    }

    // Append rules
    // SingBoxConfig.route.rules = []
    let FinalOutboundID;
    for (let i of RuleProvider.Rules) {
        const rulesetBreakdown = i.split(",").map(i => i.trim())
        const outboundID = rulesetBreakdown[0];
        // parse in simple rules <OUTBOUND>,<TYPE>,<PAYLOAD>
        const type = MetaToSingRuleMapping[rulesetBreakdown[1]] as string;
        const payload = rulesetBreakdown.slice(2).join(",") as string;
        
        // parse in rule-set route rules
        const RuleSetPayload = rulesetBreakdown.slice(1).join(",");
        if (RuleSetPayload.startsWith("http://") || RuleSetPayload.startsWith("https://")) {
            SingBoxConfig.route.rules.push({
                rule_set: RuleProvidersMapping[RuleSetPayload],
                action: "route",
                outbound: outboundID
            });
            continue;
        }

        // handle Match Type Rule (Final Ooutbound)
        if (rulesetBreakdown[1] === "MATCH") {
            FinalOutboundID = outboundID;
            continue
        }

        // handle GEOIP and GEOSITE
        if (type === "geoip" || type === "geosite") {
            const { headlessRule, headlessRuleSet } = transformGeoRef(type, payload, Config.RuleProvidersProxy);

            SingBoxConfig.route.rules.push({
                ...headlessRule,
                action: "route",
                outbound: outboundID
            });

            // if we cant find rule set with same tag (ie append before), 
            if (headlessRuleSet && !(SingBoxConfig.route.rule_set.find(i => i.tag === headlessRuleSet.tag))) { 
                // append rule-set
                SingBoxConfig.route.rule_set.push({
                    ...headlessRuleSet,
                    download_detour: "DIRECT"
                })
            }
            continue;
        }

        // handle the types that payload need to be number
        if (type === "source_port" || type === "port") {
            let numPayload = Number(payload);
            if (isNaN(numPayload)) {
                console.warn(`[getSingBoxConfig] invalid port number: ${payload}, skiping rule ${i}`);
                continue;
            }
            SingBoxConfig.route.rules.push({
                [type]: numPayload,
                action: "route",
                outbound: outboundID
            });
            continue;
        }

        // handle AND | OR Logic rules
        if (type === "and" || type === "or") {
            let { headlessRule, headlessRuleSet } = MetaToSingLogicalRule(type, payload, Config.RuleProvidersProxy);
            headlessRuleSet = headlessRuleSet.filter(i => !!i && !SingBoxConfig.route.rule_set.find(t => t.tag === i.tag));

            SingBoxConfig.route.rule_set.push(...headlessRuleSet);
            SingBoxConfig.route.rules.push({
                ...headlessRule,
                action: "route",
                outbound: outboundID
            });
            continue;
        }

        // any other route rules else should works... not sure 
        SingBoxConfig.route.rules.push({
            [type]: payload,
            action: "route",
            outbound: outboundID
        });
    }
    // Append Final Outbound
    SingBoxConfig.route.final = FinalOutboundID;

    return SingBoxConfig;
}


================================================
FILE: functions/internal/Dumpers/clash-meta.ts
================================================
import type { RealityConfig, TransportGRPC, TransportH2, TransportHTTP, TransportWS } from "../types/ClashMetaConfig";

export default class Dumper {
    config = {
        UDP: true,
        SSUoT: true,
        SkipCertVerify: true,
        ClientFingerprint: "chrome"
    }
    constructor (
        UDP = true,
        SSUoT = true,
        SkipCertVerify = true,
        ClientFingerprint = "chrome"
    ) {
        this.config.UDP = UDP;
        this.config.SSUoT = SSUoT;
        this.config.SkipCertVerify = SkipCertVerify;
        this.config.ClientFingerprint = ClientFingerprint;

        return this;
    }

    // __appendCommonField () {}

    __validate (ProxyObject) {
        if (!(ProxyObject.__Type in this)) {
            console.warn(`[Dumper: Clash Meta] [WARN] ${ProxyObject.__Type} is not supported to dump, ignoring...`)
            return false;
        }
        return true;
    }

    http (HTTP) {
        return {
            name: HTTP.__Remark,
            type: HTTP.__Type,
            server: HTTP.Hostname,
            port: HTTP.Port,
            username: HTTP.Auth.username,
            password: HTTP.Auth.password,
            "skip-cert-verify": this.config.SkipCertVerify
        }
    }
    socks5 (SOCKS5) {
        return {
            name: SOCKS5.__Remark,
            type: SOCKS5.__Type,
            server: SOCKS5.Hostname,
            port: SOCKS5.Port,
            username: SOCKS5.Auth.username,
            password: SOCKS5.Auth.password,
            "skip-cert-verify": this.config.SkipCertVerify,
            udp: this.config.UDP
        }
    }

    hysteria (hyObject) {
        return {
            name: hyObject.__Remark,
            type: hyObject.__Type,
            server: hyObject.Hostname,
            port: hyObject.Port,
            ports: hyObject.Query.mport,
            "auth_str": hyObject.Query.auth,
            "auth-str": hyObject.Query.auth,
            alpn: hyObject.Query.alpn ? [ hyObject.Query.alpn ] : undefined,
            up: hyObject.Query.upmbps,
            down: hyObject.Query.downmbps,
            sni: hyObject.Query.peer,
            "skip-cert-verify": this.config.SkipCertVerify,
            protocol: this.config.UDP ? "UDP" : "wechat-video",
        }
    }
    hysteria2 (hy2Object) {
        return {
            name: hy2Object.__Remark,
            type: hy2Object.__Type,
            server: hy2Object.Hostname,
            port: hy2Object.Port,
            ports: hy2Object.Query.mport,
            password: hy2Object.Auth,
            sni: hy2Object.Query.sni,
            obfs: hy2Object.Query.obfs,
            "obfs-password": hy2Object.Query["obfs-password"],
            "client-fingerprint": this.config.ClientFingerprint,
            "skip-cert-verify": this.config.SkipCertVerify,
            udp: this.config.UDP,
        }
    }
    hy2 = this.hysteria2;

    tuic (TUIC) {
        return {
            name: TUIC.__Remark,
            type: TUIC.__Type,
            server: TUIC.Hostname,
            port: TUIC.Port,
            uuid: TUIC.Auth.uuid,
            password: TUIC.Auth.password,
            alpn: TUIC.Query.alpn ? [ TUIC.Query.alpn ] : undefined,
            "disable-sni": !!parseInt(TUIC.Query.disable_sni),
            "udp-relay-mode": TUIC.Query.udp_relay_mode,
            "congestion-controller": TUIC.Query.congestion_control,
            "skip-cert-verify": this.config.SkipCertVerify,
            sni: TUIC.Query.sni,
            // max-udp-relay-packet-size: 1500,
            // fast-open: true,
            // max-open-streams: 20,
        }
    }

    vless (VLESS) {
        return {
            name: VLESS.__Remark,
            type: VLESS.__Type,
            server: VLESS.Hostname,
            port: VLESS.Port,
            uuid: VLESS.Auth,
            flow: VLESS.Query.flow,
            "packet-encoding": VLESS.Query.packetEncoding,
            tls: !!VLESS.Query.sni,
            servername: VLESS.Query.sni,
            alpn: VLESS.Query.alpn ? [ VLESS.Query.alpn ] : undefined,
            "client-fingerprint": VLESS.Query.fp,
            network: VLESS.Query.type,

            "reality-opts": __genRealityConfig(VLESS),

            // transport layer config
            "ws-opts": __genTransportWS(VLESS),
            "grpc-opts": __genTransportGRPC(VLESS),
            "h2-opts": __genTransportH2(VLESS),
            "http-opts": __genTransportHTTP(VLESS),

            udp: this.config.UDP,
            "skip-cert-verify": this.config.SkipCertVerify,
        }
    }
    vmess (VMESS) {
        return {
            name: VMESS.__Remark,
            type: VMESS.__Type,
            server: VMESS.Hostname,
            port: VMESS.Port,    
            uuid: VMESS.Auth,
            alterId: VMESS.Query.aid,
            cipher: VMESS.Query.scy ? VMESS.Query.scy : "auto",
            network: VMESS.Query.net,

            protocol: VMESS.Query.type,
            
            "client-fingerprint": VMESS.Query.fp,

            alpn: ["h2", "http/1.1"],

            // tls
            tls: VMESS.Query.tls === "tls",
            servername: VMESS.Query.sni,
            // "reality-opts": {
            //     "public-key": "xxxx",
            //     "short-id": "xxxx",
            // },

            // transport layer config
            "ws-opts": __genTransportWS(VMESS),
            "grpc-opts": __genTransportGRPC(VMESS),
            "h2-opts": __genTransportH2(VMESS),
            "http-opts": __genTransportHTTP(VMESS),

            "skip-cert-verify": this.config.SkipCertVerify,
            udp: this.config.UDP,

            // packet-encoding
            // global-padding
            // authenticated-length
        }
    }
    vmess__shadowsocks_type (VMESS) {
        return {
            name: VMESS.__Remark,
            type: "vmess",
            server: VMESS.Hostname,
            port: VMESS.Port,    
            uuid: VMESS.Auth,
            alterId: parseInt(VMESS.Query.alterId),
            cipher: "auto",
            network: VMESS.Query.obfs,
            

            // tls
            tls: VMESS.Query.tls === "1",
            servername: VMESS.Query.peer,

            // transport layer config
            "ws-opts": __genTransportWS(VMESS),
            "grpc-opts": __genTransportGRPC(VMESS),
            "http-opts": __genTransportHTTP(VMESS),
            "h2-opts": __genTransportH2(VMESS),

            "skip-cert-verify": this.config.SkipCertVerify,
            udp: this.config.UDP,

            // packet-encoding
            // global-padding
            // authenticated-length
        }
    }

    ss (SS) {
        return {
            name: SS.__Remark,
            type: "ss",
            server: SS.Hostname,
            port: SS.Port,
            cipher: SS.Auth.cipher,
            password: SS.Auth.password,
  
            udp: this.config.UDP,
            "udp-over-tcp": this.config.SSUoT,
            "udp-over-tcp-version": this.config.SSUoT ? 2 : undefined,
        }
    }
    trojan (TROJAN) {
        return {
            name: TROJAN.__Remark,
            type: "trojan",
            server: TROJAN.Hostname,
            port: TROJAN.Port,
            password: TROJAN.Auth,

            network: TROJAN.Query.type ? TROJAN.Query.type : "tcp",
            sni: TROJAN.Query.sni,
            alpn: ["h2", "http/1.1"],

            "reality-opts": __genRealityConfig(TROJAN),
            
            // transport layer config
            "ws-opts": __genTransportWS(TROJAN),
            "grpc-opts": __genTransportGRPC(TROJAN),
            "http-opts": __genTransportHTTP(TROJAN),

            "client-fingerprint": TROJAN.Query.fp,

            udp: this.config.UDP,
            "skip-cert-verify": this.config.SkipCertVerify,
        }
    }
}


function __genRealityConfig (Obj) : RealityConfig | undefined {
    return Obj.Query.security === "reality" ? {
        "public-key": Obj.Query.pbk ? Obj.Query.pbk : undefined,
        "short-id": Obj.Query.sid ? Obj.Query.sid : undefined
    } : undefined
}


function __genTransportWS (Obj) : TransportWS | undefined {
    const PassedTransportType = Obj.Query.obfs || Obj.Query.net || Obj.Query.type;

    if (PassedTransportType !== "ws") {
        return undefined;
    }

    const host = Obj.Query.host || Obj.Query.obfsParam;
    const PathObj = new URL(`path:${Obj.Query.path}`)
    const ParsedMaxEarlyData = parseInt(Obj.Query.ed || PathObj.searchParams.get("ed"));
    
    const MaxEarlyData = isNaN(ParsedMaxEarlyData) ? undefined : ParsedMaxEarlyData;
    const EarlyDataHeaderName = Obj.Query.eh || (MaxEarlyData ? "Sec-WebSocket-Protocol" : undefined)

    return {
        path: PathObj.pathname,
        headers: host ? { host } : undefined,
        "max-early-data": MaxEarlyData,
        "early-data-header-name": EarlyDataHeaderName,
        //"v2ray-http-upgrade"?: unknown,
        //"v2ray-http-upgrade-fast-open"?: unknown,
    }
}
function __genTransportGRPC (Obj) : TransportGRPC | undefined {
    const PassedTransportType = Obj.Query.obfs || Obj.Query.net || Obj.Query.type;
    return PassedTransportType === "grpc" ? {
        "grpc-service-name": Obj.Query.serviceName || Obj.Query.path
    } : undefined;
}

function __genTransportHTTP (Obj) : TransportHTTP | undefined {
    const PassedTransportType = Obj.Query.obfs || Obj.Query.net || Obj.Query.type;
    const host = Obj.Query.host || Obj.Query.obfsParam;
    return PassedTransportType === "http" ? {
        method: Obj.Query.method,
        path: Obj.Query.path ? [ Obj.Query.path ] : undefined,
        headers: host ? { host } : undefined,
    } : undefined;
}
function __genTransportH2 (Obj) : TransportH2 | undefined {
    const PassedTransportType = Obj.Query.obfs || Obj.Query.net || Obj.Query.type;
    return PassedTransportType === "h2" ? {
        method: Obj.Query.method,
        path: Obj.Query.path,
    } : undefined;
}


================================================
FILE: functions/internal/Dumpers/share-link.js
================================================
export class ShareLinkDumper {
    constructor () {
        return true;
    }

    __validate (ProxyObject) {
        if (!(ProxyObject.__Type in this)) {
            console.warn(`[Dumper: Share Link] [WARN] ${ProxyObject.__Type} is not supported to dump, ignoring...`)
            return false
        }
        return true;
    }

    http (HTTP) {
        return `http://${HTTP.Auth.username}:${HTTP.Auth.password}@${HTTP.Hostname}:${HTTP.Port}/#${encodeURIComponent(HTTP.__Remark)}`;
    }
    socks5 (SOCKS5) {
        return `socks5://${SOCKS5.Auth.username}:${SOCKS5.Auth.password}@${SOCKS5.Hostname}:${SOCKS5.Port}/#${encodeURIComponent(SOCKS5.__Remark)}`;
    }

    hysteria (Obj) {
        return `hysteria://${Obj.Hostname}:${Obj.Port}/${URLQueryWrapper(Obj.Query)}#${encodeURIComponent(Obj.__Remark)}`
    }
    hysteria2 (Obj) {
        return `hysteria2://${Obj.Auth}@${Obj.Hostname}:${Obj.Port}/?${URLQueryWrapper(Obj.Query)}#${encodeURIComponent(Obj.__Remark)}`
    }
    hy2 = this.hysteria2;

    tuic (Obj) {
        return `tuic://${Obj.Auth.uuid}:${Obj.Auth.password}@${Obj.Hostname}:${Obj.Port}/?${URLQueryWrapper(Obj.Query)}#${encodeURIComponent(Obj.__Remark)}`
    }

    vless (Obj) {
        return `vless://${Obj.Auth}@${Obj.Hostname}:${Obj.Port}/?${URLQueryWrapper(Obj.Query)}#${encodeURIComponent(Obj.__Remark)}`
    }
    vmess (Obj) {
        let VMESSObj = {
            ps: unescape(encodeURIComponent(Obj.__Remark)) ,
            add: Obj.Hostname,
            port: Obj.Port,
            id: Obj.Auth,
            ...Obj.Query,
        }

        return `vmess://${btoa(JSON.stringify(VMESSObj))}`
    }
    vmess__shadowsocks_type (Obj) {
        let VMESSObj = {
            ps: unescape(encodeURIComponent(Obj.__Remark)) ,
            add: Obj.Hostname,
            port: Obj.Port,
            id: Obj.Auth,
            //...Obj.Query,
            aid: Obj.Query.alterId,
            scy: "auto",
            net: Obj.Query.obfs,
            tls: Obj.Query.tls === "1" ? "tls" : undefined,
            sni: Obj.Query.peer,
            host: Obj.Query.obfsParam,
            path: Obj.Query.path
        }
        return `vmess://${btoa(JSON.stringify(VMESSObj))}`
    }

    ss (Obj) {
        return `ss://${encodeURIComponent(btoa(`${Obj.Auth.cipher}:${Obj.Auth.password}`))}@${Obj.Hostname}:${Obj.Port}/#${encodeURIComponent(Obj.__Remark)}`
    }
    trojan (Obj) {
        return `trojan://${Obj.Auth}@${Obj.Hostname}:${Obj.Port}/?${URLQueryWrapper(Obj.Query)}#${encodeURIComponent(Obj.__Remark)}`
    }
}

function URLQueryWrapper (Obj) {
    let Childs = [];
    for (let i in Obj) {
        let value = Obj[i];
        if (value) {
            Childs.push(`${i}=${encodeURIComponent(Obj[i])}`)
        }
    }
    return Childs.join("&");
}


================================================
FILE: functions/internal/Dumpers/sing-box.js
================================================
export default class Dumper {
    config = {}
    constructor (
        UDP = true,
        SSUoT = false,
        SkipCertVerify = true
    ) {
        this.config.UDP = UDP;
        this.config.SSUoT = SSUoT;
        this.config.SkipCertVerify = SkipCertVerify;

        return true;
    }

    // __appendCommonField () {}

    __validate (ProxyObject) {
        if (!(ProxyObject.__Type in this)) {
            console.warn(`[Dumper: Sing Box] [WARN] ${ProxyObject.__Type} is not supported to dump, ignoring...`)
            return false;
        }
        if (ProxyObject.__Type === "vmess__shadowsocks_type" && ProxyObject.Query.obfs === "none") {
            console.warn(`[Dumper: Sing Box] [WARN] ${ProxyObject.__Type} TCP-Transport is not supported by sing-box, ignoring...`)
            return false;
        }
        return true;
    }

    http (HTTP) {
        return {
            tag: HTTP.__Remark,
            type: "http",
          
            server: HTTP.Hostname,
            server_port: HTTP.Port,
            username: HTTP.Auth.username,
            password: HTTP.Auth.password,
            path: "/",
            headers: {},
            tls: {
                insecure: this.config.SkipCertVerify
            },
        }
    }
    socks5 (SOCKS5) {
        return {
            tag: SOCKS5.__Remark,
            type: "socks",
            server: SOCKS5.Hostname,
            server_port: SOCKS5.Port,
            version: "5",
            username: SOCKS5.Auth.username,
            password: SOCKS5.Auth.password,
            //udp_over_tcp: this.config.UDP ? "udp" : "tcp"
        }
    }

    hysteria (hyObject) {
        return {
            type: "hysteria",
            tag: hyObject.__Remark,
          
            server: hyObject.Hostname,
            server_port: hyObject.Port,

            server_ports: hyObject.Query.mport ? hyObject.Query.mport.replace(/\-/g, ":").split(",") : undefined,
            up_mbps: parseInt(hyObject.Query.upmbps) || 250,
            down_mbps: parseInt(hyObject.Query.downmbps) || 500,
            obfs: hyObject.Query.obfsParam,
            auth_str: hyObject.Query.auth,
            
            tls: {
                enabled: true,
                server_name: hyObject.Query.peer,
                insecure: this.config.SkipCertVerify
            },
        }
    }
    hysteria2 (hy2Object) {
        return {
            type: "hysteria2",
            tag: hy2Object.__Remark,
          
            server: hy2Object.Hostname,
            server_port: hy2Object.Port,

            server_ports: hy2Object.Query.mport ? hy2Object.Query.mport.replace(/\-/g, ":").split(",") : undefined,
            up_mbps: parseInt(hy2Object.Query.upmbps) || 250,
            down_mbps: parseInt(hy2Object.Query.downmbps) || 500,
            obfs: (hy2Object.Query.obfs && hy2Object.Query["obfs-password"] ) ? {
                type: hy2Object.Query.obfs,
                password: hy2Object.Query["obfs-password"],
            } : undefined,
            password: hy2Object.Auth,
            
            tls: {
                enabled: true,
                server_name: hy2Object.Query.sni,
                insecure: this.config.SkipCertVerify,
                alpn: [
                  "h3"
                ]
            },
        }
    }
    hy2 = this.hysteria2;

    tuic (TUIC) {
        return {
            type: "tuic",
            tag: TUIC.__Remark,
          
            server: TUIC.Hostname,
            server_port: TUIC.Port,
            uuid: TUIC.Auth.uuid,
            password: TUIC.Auth.password,

            udp_relay_mode: TUIC.Query.udp_relay_mode,

            congestion_control: TUIC.Query.congestion_control,

            heartbeat: "10s",
            tls: {
                enabled: true,
                disable_sni: !!parseInt(TUIC.Query.disable_sni),
                alpn: TUIC.Query.alpn ? [ TUIC.Query.alpn ] : undefined,
                insecure: this.config.SkipCertVerify,
                server_name: TUIC.Query.sni,
            }
        }
    }

    vless (VLESS) {
        return {
            type: "vless",
            tag: VLESS.__Remark,
          
            server: VLESS.Hostname,
            server_port: VLESS.Port,
            uuid: VLESS.Auth,
            flow: VLESS.Query.flow,
            packet_encoding: VLESS.Query.packetEncoding,
            tls: !!VLESS.Query.sni ? {
                enabled: true,
                server_name: VLESS.Query.sni,
                insecure: this.config.SkipCertVerify,
                alpn: VLESS.Query.alpn ? [ VLESS.Query.alpn ] : undefined,

                utls: {
                    enabled: !!VLESS.Query.fp,
                    fingerprint: VLESS.Query.fp
                },
                reality: __genRealityConfig(VLESS),
            } : undefined,
            //"multiplex: {},
            transport: __genTransportConfig(VLESS)

        }
    }
    vmess__shadowsocks_type (VMess) {

        let URITransportType = URIObject.Query.obfs;
        const PathObject = new URL(`path:${URIObject.Query.path}`);

        return {
            type: "vmess",
            tag: VMess.__Remark,
            server: VMess.Hostname,
            server_port: VMess.Port,
            uuid: VMess.Auth,
            security: "auto",
            alter_id: parseInt(VMess.Query.alterId),

            tls: VMess.Query.sni === "1" ? {
                enabled: true,
                server_name: VMess.Query.peer,
                insecure: this.config.SkipCertVerify,
            } : undefined,
            //"multiplex: {},
            transport: {
                type: URITransportType,

                // http
                headers: { 
                    Host: 
                        (URITransportType !== "quic" && URITransportType !== "grpc")
                        ? URIObject.Query.obfsParam
                        : undefined,
                },
                path: URITransportType !== "grpc" ? PathObject.path : undefined,

                // max early data
                early_data_header_name: PathObject.searchParams.has("ed") ? "Sec-WebSocket-Protocol" : undefined,
                max_early_data: PathObject.searchParams.has("ed") ? parseInt(PathObject.searchParams.get("ed")) : undefined,

                // grpc
                service_name: URITransportType === "grpc" ? ( URIObject.Query.path ) : undefined,
            }
        }
    }
    vmess (VMESS) {
        return {
            type: "vmess",
            tag: VMESS.__Remark,
          
            server: VMESS.Hostname,
            server_port: VMESS.Port,
            uuid: VMESS.Auth,
            security: VMESS.Query.scy ? VMESS.Query.scy : "auto",
            alter_id: VMESS.Query.aid,
            // global_padding: false, //??
            // authenticated_length: true, //??
            tls: (VMESS.Query.tls === "tls") ? {
                enabled: true,
                server_name: VMESS.Query.sni,
                insecure: this.config.SkipCertVerify,
                alpn: ["h2", "http/1.1"],
                utls: {
                    enabled: !!VMESS.Query.fp,
                    fingerprint: VMESS.Query.fp
                },
                reality: __genRealityConfig(VMESS),
            } : undefined,
            transport: __genTransportConfig(VMESS)
        }
    }

    ss (SS) {
        return {
            type: "shadowsocks",
            tag: SS.__Remark,
          
            server: SS.Hostname,
            server_port: SS.Port,
            method: SS.Auth.cipher,
            password: SS.Auth.password,
            udp_over_tcp: this.config.SSUoT ? {
                enabled: true,
                version: 2
            } : false,
        }
    }
    trojan (TROJAN) {
        return {

            type: "trojan",
            tag: TROJAN.__Remark,
          
            server: TROJAN.Hostname,
            server_port: TROJAN.Port,
            password: TROJAN.Auth,
            network: TROJAN.Query.type ? TROJAN.Query.type : "tcp",
            tls: !!TROJAN.Query.sni ? {
                enabled: true,
                server_name: TROJAN.Query.sni,
                alpn: ["h2", "http/1.1"],
                insecure: this.config.SkipCertVerify,
                utls: {
                    enabled: !!TROJAN.Query.fp,
                    fingerprint: TROJAN.Query.fp
                },
                reality: __genRealityConfig(TROJAN),
            } : undefined,
            transport: __genTransportConfig(TROJAN)

        }
    }
}
function __genRealityConfig (URIObject) {
    return (URIObject.Query.security === "reality") ? {
        enabled: true,
        public_key: URIObject.Query.pbk || undefined,
        short_id: URIObject.Query.sid || undefined
    } : undefined;
}
function __genTransportConfig (URIObject) {
    const URITransportType = URIObject.Query.net || URIObject.Query.type;

    const PathObject = new URL(`path:${URIObject.Query.path}`);
    return (
        URITransportType === "http" ||
        URITransportType === "ws" ||
        URITransportType === "grpc" ||
        URITransportType === "quic" ||
        URITransportType === "httpupgrade"
    ) ? {
        type: URITransportType,

        // http
        headers: { 
            Host: 
                (URITransportType !== "quic")
                 ? URIObject.Query.host
                 : undefined,
        },
        path: PathObject.pathname || "",
        method: URIObject.Query.method,

        // max early data
        early_data_header_name: PathObject.searchParams.has("ed") ? "Sec-WebSocket-Protocol" : undefined,
        max_early_data: PathObject.searchParams.has("ed") ? parseInt(PathObject.searchParams.get("ed")) : undefined,

        // grpc
        service_name: URITransportType === "grpc" ? ( URIObject.Query.serviceName || URIObject.Query.path ) : undefined,
    } : undefined;
}

================================================
FILE: functions/internal/Parsers/clash-meta.js
================================================
export class ClashMetaParser {
    constructor () {}

    __validate (ProxyObject) {
        if (!(ProxyObject.type in this)) {
            console.warn(`[Parser: Clash Meta] [WARN] ${ProxyObject.__Type} is not supported to parse, ignoring...`)
            return false;
        }
        return true;
    }

    http (Obj) {
        return {
            __Type: "http",
            __Remark: Obj.name,
            Hostname: Obj.server,
            Port: Obj.port,
            Auth: {
                username: Obj.username,
                password: Obj.password
            }
        }
    }
    socks5 (Obj) {
        return {
            __Type: "socks5",
            __Remark: Obj.name,
            Hostname: Obj.server,
            Port: Obj.port,
            Auth: {
                username: Obj.username,
                password: Obj.password
            }
        }
    }
    
    hysteria (Obj) {
        return {
            __Type: "hysteria",
            __Remark: Obj.name,
            Hostname: Obj.server,
            Port: Obj.port,
            Query: {
                auth: (Obj["auth_str"] || Obj["auth-str"]),
                alpn: Obj.alpn ? Obj.alpn.join(",") : undefined,
                upmbps: Obj.up,
                downmbps: Obj.down,
                peer: Obj.sni,
                mport: Obj.ports,
            }
        }
    }
    hysteria2 (Obj) {
        return {
            __Type: "hysteria2",
            __Remark: Obj.name,
            Hostname: Obj.server,
            Port: Obj.port,
            Auth: Obj.auth || Obj.password,
            Query: {
                objs: Obj.obfs,
                "obfs-password": Obj["obfs-password"],
                insecure: Obj["skip-cert-verify"] ? 1 : 0,
                mport: Obj.ports,
            }
        }
    }
    hy2 = this.hysteria2;

    tuic (Obj) {
        return {
            __Type: "tuic",
            __Remark: Obj.name,
            Hostname: Obj.server,
            Port: Obj.port,
            Auth: { uuid: Obj.uuid, password: Obj.password },
            Query: {
                alpn: Obj.alpn ? Obj.alpn.join(",") : undefined,
                disable_sni: Obj["disable-sni"],
                udp_relay_mode: Obj["udp-relay-mode"],
                congestion_control: Obj["congestion-controller"],
                sni: Obj.sni,
            }
        }
    }


    vless (Obj) {
        return {
            __Type: "vless",
            __Remark: Obj.name,
            Hostname: Obj.server,
            Port: Obj.port,
            Auth: Obj.uuid,
            Query: {
                flow: Obj.flow,
                packetEncoding: Obj["packet-encoding"],
                sni: Obj.servername,
                alpn: Obj.alpn ? Obj.alpn.join(",") : undefined,
                fp: Obj["client-fingerprint"],
                type: Obj.network,


                // reality
                security: !!Obj["reality-opts"] ? "reality": undefined,
                pbk: (Obj["reality-opts"] || {})["public-key"],
                sid: (Obj["reality-opts"] || {})["short-id"],

                
                // transport layer config
                
                // - ws
                ed: Obj["max-early-data"],
                eh: Obj["early-data-header-name"],

                // - grpc
                serviceName: Obj["grpc-service-name"],

                // - http
                method: Obj.method,

                // - http & ws & h2
                path: Obj["ws-path"] || Obj.path,
                host: Obj.host || (Obj["ws-headers"] || Obj.headers || {}).Host,
            }
        }
    }
    vmess (Obj) {
        return {
            __Type: "vmess",
            __Remark: Obj.name,
            Hostname: Obj.server,
            Port: Obj.port,
            Auth: Obj.uuid,
            Query: {
                aid: Obj.alterId,
                cipher: Obj.cipher,
                net: Obj.network,
                type: Obj.protocol,
                fp: Obj["client-fingerprint"],
                alpn: Obj.alpn ? Obj.alpn.join(",") : undefined,
                tls: Obj.tls ? "tls" : undefined,
                sni: Obj.servername,

                // transport layer config
                // - http & ws & h2 
                host: (Obj["ws-headers"] || Obj.headers || {}).Host,
                // - http & ws & h2 & grpc
                path: 
                    Obj["ws-path"] || 
                    ( Obj["ws-opts"] || Obj["h2-opts"] || {} ).path || 
                    ( (Obj["http-opts"] || {}).path || [] )[0] || 
                    Obj["grpc-service-name"] ||
                    undefined,

            }
        }
    }

    ss (Obj) {
        return {
            __Type: "ss",
            __Remark: Obj.name,
            Hostname: Obj.server,
            Port: Obj.port,
            Auth: { cipher: Obj.cipher, password: Obj.password },
        }
    }

    trojan (Obj) {
        return {
            __Type: "trojan",
            __Remark: Obj.name,
            Hostname: Obj.server,
            Port: Obj.port,
            Auth: Obj.password,
            Query: {
                type: Obj.network,
                sni: Obj.sni,

                // reality
                security: !!Obj["reality-opts"] ? "reality" : undefined,
                pbk: Obj["public-key"],
                sid: Obj["short-id"],


                // transport layer config
                
                // - ws
                ed: Obj["max-early-data"],
                eh: Obj["early-data-header-name"],

                // - grpc
                serviceName: Obj["grpc-service-name"],

                // - http
                method: Obj.method,

                // - http & ws
                path: Obj["ws-path"] || Obj.path,
                host: (Obj["ws-headers"] || Obj.headers || {}).Host,
            }
        }
    }
}

function __searchParamsMapper (searchParams) {
    let Query = {}
    for (const [key, value] of searchParams) {
        Query[key] = value
    }
    return Query;
}


================================================
FILE: functions/internal/Parsers/share-link.js
================================================
export class ShareLinkParser {
    constructor () {}

    __validate (URI) {
        if (!(URI.split(":")[0] in this)) {
            console.warn(`[Parser: Share Link] [WARN] ${URI.__Type} is not supported to parse, ignoring...`)
            return false;
        }
        return true;
    }

    http (URI) {
        let URIObject = new URL (URI);
        return {
            __Type: "http",
            __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, "")) || URIObject.host,
            Hostname: URIObject.hostname,
            Port: parseInt(URIObject.port),
            Auth: {
                username: URIObject.username,
                password: URIObject.password
            }
        }
    }
    socks5 (URI) {
        let URIObject = new URL (URI);
        return {
            __Type: "socks5",
            __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, "")) || URIObject.host,
            Hostname: URIObject.hostname,
            Port: parseInt(URIObject.port),
            Auth: {
                username: URIObject.username,
                password: URIObject.password
            }
        }
    }
    
    hysteria (HYURL) {
        const URIObject = new URL (HYURL);

        const HY = {
            __Type: "hysteria",
            __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, "")) || URIObject.host,
            Hostname: URIObject.hostname,
            Port: parseInt(URIObject.port),
            Query: __searchParamsMapper(URIObject.searchParams)
        }
        return HY;
    }
    hysteria2 (HY2URL) {
        const URIObject = new URL (HY2URL);

        const HY2 = {
            __Type: "hysteria2",
            __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, "")) || URIObject.host,
            Auth: decodeURIComponent(URIObject.password || URIObject.username),
            Hostname: URIObject.hostname,
            Port: parseInt(URIObject.port),
            Query: __searchParamsMapper(URIObject.searchParams)
        }
        return HY2;
    }
    hy2 = this.hysteria2;

    tuic (TUICURI) {
        let URIObject = new URL(TUICURI);

        const TUIC = {
            __Type: "tuic",
            __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, "")) || URIObject.host,
            Auth: { uuid: URIObject.username, password: URIObject.password},
            Hostname: URIObject.hostname,
            Port: parseInt(URIObject.port),
            Query: __searchParamsMapper(URIObject.searchParams)
        }
        return TUIC;
    }


    vless (URI) {
        let URIObject = new URL (URI);
        let VLESS = {
            __Type: "vless",
            __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, "")) || URIObject.host,
            Hostname: URIObject.hostname,
            Port: parseInt(URIObject.port),
            Auth: URIObject.username,
            Query: __searchParamsMapper(URIObject.searchParams)
        }
        return VLESS;
    }
    vmess (URI) {
        let URIObject = new URL(URI);
        let VMessRawData = atob(URIObject.host);
        try {
            let VMessRawObject = JSON.parse(VMessRawData);

            let Remark;
            try {
                Remark = decodeURIComponent(escape(VMessRawObject.ps))
            } catch (e) {
                Remark = VMessRawObject.ps
            }
            let VMess =  {
                __Type: "vmess",
                __Remark: Remark || `${VMessRawObject.add}:${VMessRawObject.port}`,
                Hostname: VMessRawObject.add,
                Port: parseInt(VMessRawObject.port),
                Auth: VMessRawObject.id,
            }
            delete VMessRawObject.ps
            delete VMessRawObject.add
            delete VMessRawObject.port
            delete VMessRawObject.id

            // am i doing right...
            delete VMessRawObject.v // assume its version 2

            // delete all the empty fields
            for (let i in VMessRawObject) {
                if (
                    VMessRawObject[i] === "" || 
                    VMessRawObject[i] === null || 
                    VMessRawObject[i] === undefined
                ) {
                    delete VMessRawObject[i]
                }
            }

            VMessRawObject.aid = parseInt(VMessRawObject.aid)

            VMess.Query = VMessRawObject;

            return VMess;
        } catch (err) {
            let StandardURIObj = new URL(`vmess://${VMessRawData}${URIObject.pathname}${URIObject.search}`)
            let VMess =  {
                //__Type: "vmess",
                __Type: "vmess__shadowsocks_type",
                __Remark: StandardURIObj.searchParams.get("remarks") || StandardURIObj.host,
                Hostname: StandardURIObj.hostname,
                Port: parseInt(StandardURIObj.port),
                Auth: StandardURIObj.password,
                Query: __searchParamsMapper(URIObject.searchParams)
            }
            delete VMess.Query.remarks
            if (VMess.Query.obfs === "websocket") { VMess.Query.obfs = "ws" }
            return VMess
        }
    }

    ss (URI) {
        let StandardURI = (URI => {
            let URIObject = new URL(URI);
            try {
                // base64-encoded cipher:uuid@host:port
                return `ss://${encodeURIComponent(atob(decodeURIComponent(URIObject.host))).replace(/\%3A/gi,":").replace(/\%40/gi,"@")}${URIObject.search}${URIObject.hash}`;
            } catch (e) {}
            try {
                // base64-encoded cipher:uuid
                return `ss://${encodeURIComponent(atob(decodeURIComponent(URIObject.username))).replace(/\%3A/i,":")}@${URIObject.host}${URIObject.search}${URIObject.hash}`;
            } catch (e) {}
            // plain
            return URI;
        })(URI)
        
        let URIObject = new URL(StandardURI);
        

        return {
            __Type: "ss",
            __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, "")) || URIObject.host,
            Auth: { cipher: decodeURIComponent(URIObject.username), password: decodeURIComponent(URIObject.password) },
            Hostname: URIObject.hostname,
            Port: parseInt(URIObject.port)
        }

    }

    trojan (URI) {
        let URIObject = new URL(URI);

        const TROJAN = {
            __Type: "trojan",
            __Remark: decodeURIComponent(URIObject.hash.replace(/^#/, "")) || URIObject.host,
            Auth: URIObject.username,
            Hostname: URIObject.hostname,
            Port: parseInt(URIObject.port),
            Query: __searchParamsMapper(URIObject.searchParams)
        }
        return TROJAN;
    }
}

function __searchParamsMapper (searchParams) {
    let Query = {}
    for (const [key, value] of searchParams) {
        Query[key] = value
    }
    return Query;
}

================================================
FILE: functions/internal/Parsers/sing-box.js
================================================
export class SingBoxParser {
    constructor () {}

    __validate (ProxyObject) {
        if (!(ProxyObject.type in this)) {
            console.warn(`[Parser: Sing-Box] [WARN] ${ProxyObject.__Type} is not supported to parse, ignoring...`)
            return false;
        }
        if (ProxyObject.type === "socks" && ProxyObject.version != 5) {
            console.warn(`[Parser: Sing-Box] [WARN] Only Socks version 5 is supported to parse, ignoring...`)
            return false;
        }
        return true;
    }

    http (Obj) {
        return {
            __Type: "http",
            __Remark: Obj.tag,
            Hostname: Obj.server,
            Port: Obj.server_port,
            Auth: {
                username: Obj.username,
                password: Obj.password
            }
        }
    }
    socks (Obj) {
        return {
            __Type: "socks5",
            __Remark: Obj.tag,
            Hostname: Obj.server,
            Port: Obj.server_port,
            Auth: {
                username: Obj.username,
                password: Obj.password
            }
        }
    }
    
    hysteria (Obj) {
        return {
            __Type: "hysteria",
            __Remark: Obj.tag,
            Hostname: Obj.server,
            Port: Obj.server_port,
            Query: {
                auth: (Obj["auth_str"] || Obj["auth"]),
                alpn: Obj.tls && Obj.tls.alpn ? Obj.tls.alpn.join(",") : undefined,
                upmbps: Obj.up || Obj.up_mbps,
                downmbps: Obj.down || Obj.down_mbps,
                peer: Obj.tls && Obj.tls.server_name,
                mport: Obj.server_ports ? Obj.server_ports.map(i=>i.replace(/\:/gi, "-")).join(",") : undefined,
            }
        }
    }
    hysteria2 (Obj) {
        return {
            __Type: "hysteria2",
            __Remark: Obj.tag,
            Hostname: Obj.server,
            Port: Obj.server_port,
            Auth: Obj.password,
            Query: {
                upmbps: Obj.up_mbps,
                downmbps: Obj.down_mbps,
                objs: Obj.obfs ? Obj.obfs.type : undefined,
                "obfs-password": Obj.obfs ? Obj.obfs.password : undefined,
                insecure: Obj.tls && Obj.tls.insecure ? 1 : 0,
                mport: Obj.server_ports ? Obj.server_ports.map(i=>i.replace(/\:/gi, "-")).join(",") : undefined,
            }
        }
    }

    tuic (Obj) {
        return {
            __Type: "tuic",
            __Remark: Obj.tag,
            Hostname: Obj.server,
            Port: Obj.server_port,
            Auth: { uuid: Obj.uuid, password: Obj.password },
            Query: {
                alpn: Obj.alpn ? Obj.alpn.join(",") : undefined,
                disable_sni: Obj.tls.disable_sni,
                udp_relay_mode: Obj.udp_relay_mode,
                congestion_control: Obj.congestion_control,
                sni: Obj.tls && Obj.tls.server_name,
            }
        }
    }


    vless (Obj) {
        return {
            __Type: "vless",
            __Remark: Obj.tag,
            Hostname: Obj.server,
            Port: Obj.server_port,
            Auth: Obj.uuid,
            Query: {
                flow: Obj.flow,
                packetEncoding: Obj.packet_encoding,
                sni: Obj.tls && Obj.tls.server_name,
                alpn: Obj.tls && Obj.tls.alpn ? Obj.tls.alpn.join(",") : undefined,
                fp: Obj.tls && Obj.tls.utls && Obj.tls.utls.enabled === true ? Obj.tls.utls.fingerprint: undefined,
                type: Obj.network,

                // reality
                security: Obj.tls && Obj.tls.reality && Obj.tls.reality.enabled ? "reality" : undefined,
                pbk: Obj.tls && Obj.tls.reality && Obj.tls.reality.enabled ? Obj.tls.reality["public_key"] : undefined,
                sid: Obj.tls && Obj.tls.reality && Obj.tls.reality.enabled ? Obj.tls.reality["short_id"] : undefined,

                // transport layer config
                // - ws
                ed: Obj.transport && Obj.transport["max_early_data"],
                eh: Obj.transport && Obj.transport["early_data_header_name"],
                // - grpc
                serviceName: Obj.transport && Obj.transport["service_name"],
                // - http
                method: Obj.method,
                // - http & ws
                path: Obj.transport && Obj.transport.path,
                host: (Obj.transport && Obj.transport.headers || {}).Host,
            }
        }
    }
    vmess (Obj) {
        return {
            __Type: "vmess",
            __Remark: Obj.tag,
            Hostname: Obj.server,
            Port: Obj.server_port,
            Auth: Obj.uuid,
            Query: {
                aid: Obj.alter_id,
                cipher: Obj.security,
                net: Obj.network,
                type: Obj.protocol,
                fp: Obj.tls && Obj.tls.utls ? Obj.tls.utls.fingerprint : undefined,
                alpn: Obj.alpn ? Obj.alpn.join(",") : undefined,
                tls: Obj.tls && Obj.tls.enabled ? "tls" : undefined,
                sni: Obj.server_name,

                // transport layer config
                // - http & ws & h2 
                host: (Obj.headers || {}).Host,
                // - http & ws & h2 & grpc
                path: Obj.path || undefined
            }
        }
    }

    shadowsocks (Obj) {
        return {
            __Type: "ss",
            __Remark: Obj.tag,
            Hostname: Obj.server,
            Port: Obj.server_port,
            Auth: { cipher: Obj.method, password: Obj.password },
        }
    }

    trojan (Obj) {
        return {
            __Type: "trojan",
            __Remark: Obj.tag,
            Hostname: Obj.server,
            Port: Obj.server_port,
            Auth: Obj.password,
            Query: {
                type: Obj.network,
                sni: Obj.tls && Obj.tls.server_name,

                // reality
                security: Obj.tls && Obj.tls.reality && Obj.tls.reality.enabled ? "reality" : undefined,
                pbk: Obj.tls && Obj.tls.reality && Obj.tls.reality.enabled ? Obj.tls.reality["public_key"] : undefined,
                sid: Obj.tls && Obj.tls.reality && Obj.tls.reality.enabled ? Obj.tls.reality["short_id"] : undefined,


                // transport layer config
                // - ws
                ed: Obj.transport && Obj.transport["max_early_data"],
                eh: Obj.transport && Obj.transport["early_data_header_name"],
                // - grpc
                serviceName: Obj.transport && Obj.transport["service_name"],
                // - http
                method: Obj.method,
                // - http & ws
                path: Obj.transport && Obj.transport["path"] || Obj.path,
                host: (Obj.transport && Obj.transport["headers"] || Obj.headers || {}).Host,
            }
        }
    }
}


================================================
FILE: functions/internal/RuleProviderReader/Readers/ini.js
================================================
import { parseINI } from "confbox";

import { fetchCached } from "../../utils/fetchCached.js";

export async function ini (RuleProviderURL, CacheDB, isForcedRefresh) {

    let Config = {
        RuleProviders: [],
        Rules: [],
        ProxyGroup: []
    };

    // get raw remote config.
    let RuleProvider = 
        await fetchCached(RuleProviderURL, "RuleProvider", CacheDB, isForcedRefresh)
        .then(
            res => 
                res.replaceAll("ruleset=", "ruleset[]=")
                   .replaceAll("custom_proxy_group=", "custom_proxy_group[]=")
        )
        .then(res => parseINI(res));


    // process rules
    for (let i of RuleProvider.custom.ruleset) {
        const rulesetBreakdown = i.split(",").map(i=>i.trim())
        const id = rulesetBreakdown[0];
        const payload = rulesetBreakdown.slice(1).join(",");

        // append rule providers
        if (payload.startsWith("https://") || payload.startsWith("http://")) {
            if (!Config.RuleProviders[id]) {
                Config.RuleProviders[id] = [];
            }
            Config.RuleProviders[id].push(payload)
        }

        // append route rules
        const postProcessedContent = 
            `${id},${payload
                .replace(/^\[\]FINAL/i, "MATCH")
                .replace(/^\[\]/g, "")
            }`
        Config.Rules.push(postProcessedContent)
    }

    // process proxy groups
    for (let i of RuleProvider.custom.custom_proxy_group) {
        // "特殊筛选条件" (starts with "!!") are not supported. #todo
        const ConfigArr = i.split("`").map(i => i.trim()).filter(t => !t.startsWith("!!"));
        const Args = ConfigArr.slice(2).filter(t => !t.startsWith("[]"));
        const type = ConfigArr[1];

        let ProxyGroupConfig = {
            name: ConfigArr[0],
            type: type,
            RegExps: Args,
            GroupSelectors: ConfigArr.slice(2).filter(t => t.startsWith("[]")),
        }
            
        if (type === "url-test" || type === "fallback" || type === "load-balance") {
            let TestURLIndex = Args.findIndex(loc => (loc.startsWith("https://") || loc.startsWith("http://")))
            let TestArgs = [Args.slice(TestURLIndex)[0], ...Args.slice(TestURLIndex)[1].split(",").map(i => i.trim())];
            ProxyGroupConfig.TestConfig = {
                TestURL: TestArgs[0],
                Interval: parseInt(TestArgs[1]),
                Timeout: parseInt(TestArgs[2]),
                Tolerance: parseInt(TestArgs[3]),
            }
        }

        Config.ProxyGroup.push(ProxyGroupConfig)
    }

    return Config;

}

================================================
FILE: functions/internal/RuleProviderReader/main.js
================================================
import { ini } from "./Readers/ini.js"

export class RuleProviderReader {
    RuleProvider = {};
    Reader = {
        ini,
    }
    constructor (RuleProviderURL) {
        this.RuleProvider.URL = RuleProviderURL;
        const pathname = new URL(RuleProviderURL).pathname;
        this.RuleProvider.Type = pathname.split(".").slice(-1)[0].toLowerCase();

        console.info(`[Remote Config Reader] Inputed remote config type: ${this.RuleProvider.Type}`);

        if (this.RuleProvider.Type in this.Reader) {
            return true;
        } else {
            console.warn("[Remote Config Reader] [WARN] Inputed remote config type cannot be detected, assume as .ini.");
            this.RuleProvider.Type = "ini"
            return true;
        }
    }

    Process = async function (EdgeSubDB, isForcedRefresh) {
        let __startTime = performance.now();
        console.info(`[Remote Config Reader] started`);
        const response = this.Reader[this.RuleProvider.Type](this.RuleProvider.URL, EdgeSubDB, isForcedRefresh);
        //let RawConfig = await fetchRuleProvider(RuleProviderURL, isForcedRefresh);
        console.info(`[Remote Config Reader] done, wasting ${performance.now() - __startTime}ms`);
        return response
    }

}


================================================
FILE: functions/internal/configs.ts
================================================
export const DefaultRequestHeaders = {
    "Accept": "*/*",
    "User-Agent": "EdgeSub-git/0.0.0 (Prefer ClashMeta / Mihomo Format)",
}

================================================
FILE: functions/internal/data/rule/MetaToSingLogicalRule.ts
================================================
import { MetaToSingRuleMapping } from "./MetaToSingMapping";
import { transformGeoRef } from "../ruleset/transformGeoRef";
import type { headlessRuleSet } from "../ruleset/transformGeoRef";

/**
 * Parse Mihomo Logical rules, AND | OR
 * example:
 *  - AND,  ((DOMAIN,baidu.com),(NETWORK,UDP))
 *  - OR,   ((NETWORK,UDP),(DOMAIN,baidu.com))
 * Nesting supported!
 * example:
 *  - AND,  ( (DOMAIN,baidu.com), (OR, ( (NETWORK,UDP), (PORT,443) ) ) )
 * @param type Sing rule type 
 * @returns Sing Headless rule
 */
export function MetaToSingLogicalRule (type: string, payload: string, EdgeSubInstanceBaseURL): { headlessRule: any, headlessRuleSet: headlessRuleSet[] } {
    // console.log(payload)
    const payloads = payload.replace(/(^\(|\)$)/g, "");
    // console.log(payloads)
    const ruleSets: headlessRuleSet[] = [];
    const rules = parseParenthesizedItems(payloads).map(i => {
        const itemBreakdown = i.split(",");
        const itemType = MetaToSingRuleMapping[itemBreakdown[0]];
        const itemPayload = itemBreakdown[1];
        // handle GEOIP and GEOSITE
        if (itemType === "geoip" || itemType === "geosite") {
            const { headlessRule, headlessRuleSet } = transformGeoRef(itemType, itemPayload, EdgeSubInstanceBaseURL);
            // if we cant find rule set with same tag (ie append before), 
            if (headlessRuleSet && !(ruleSets.find(i => i.tag === headlessRuleSet.tag))) { 
                ruleSets.push(headlessRuleSet);
            }
            return headlessRule;
        }
        if (itemType === "and" || itemType === "or") {
            let { 
                headlessRule: RecrusivlyHeadlessRule, 
                headlessRuleSet: RecrusivlyHeadlessRuleSet 
            } = MetaToSingLogicalRule(itemType, itemBreakdown.slice(1).join(","), EdgeSubInstanceBaseURL);

            RecrusivlyHeadlessRuleSet = RecrusivlyHeadlessRuleSet.filter(i => !!i && !ruleSets.find(t => t.tag === i.tag));
            ruleSets.push(...RecrusivlyHeadlessRuleSet);

            return RecrusivlyHeadlessRule;
        }
        return {
            [itemType]: itemPayload,
        }
    });
    
    return {
        headlessRule: {
            type: "logical",
            mode: type,
            rules: rules
        },
        headlessRuleSet: ruleSets
    }
}


/**
 * Parses a string containing comma-separated, parenthesized items into an array of strings.
 * This version correctly handles nested parentheses by manually balancing them,
 * which is a task simple regular expressions cannot reliably perform.
 *
 * @param inputString The string to parse, e.g., "(A,(B)),(C)".
 * @returns An array containing the inner content of each top-level parenthesized item.
 * For example, ["A,(B)", "C"].
 * Returns an empty array if there are no matches.
 */
function parseParenthesizedItems(inputString: string): string[] {
    const result: string[] = [];
    let parenCount = 0;
    let itemStart = -1;

    for (let i = 0; i < inputString.length; i++) {
        const char = inputString[i];

        if (char === '(') {
        if (parenCount === 0) {
            // This is the start of a top-level item.
            // Mark the position right after the opening parenthesis.
            itemStart = i + 1;
        }
        parenCount++;
        } else if (char === ')') {
        parenCount--;
        if (parenCount === 0 && itemStart !== -1) {
            // We've found the closing parenthesis of a top-level item.
            // Extract the content from itemStart to the current position.
            result.push(inputString.substring(itemStart, i));
            itemStart = -1; // Reset for the next item.
        }
        }
    }

    // A final check: if parenCount is not 0, the input string had mismatched parentheses.
    // You might want to throw an error here, but for now we'll return what we found.
    if (parenCount !== 0) {
        console.error("Warning: Mismatched parentheses in input string.");
    }

    return result;
}

================================================
FILE: functions/internal/data/rule/MetaToSingMapping.ts
================================================
// mihomo src rule syntax
// <TYPE>, <PAYLOAD>, <OUTBOUND>, <Additional Parameters>
// note: headless rule doesnt need to care bout outbound
//       additional parameters is not handled by sing-box/route/rule:
//       - "no-resolve"'s sing-box/dns/rule's work. 
//       - "src" is a crazy thing i don't even know why it exists (
export const MetaToSingRuleMapping = {
    "DOMAIN": "domain",
    "DOMAIN-SUFFIX": "domain_suffix",
    "DOMAIN-KEYWORD": "domain_keyword",
    "DOMAIN-REGEX": "domain_regex",

    "GEOSITE": "geosite",
    "GEOIP": "geoip",

    "IP-CIDR": "ip_cidr",
    "IP-CIDR6": "ip_cidr", // IP-CIDR6 is a alias for IP-CIDR in mihomo route rule
    "SRC-IP-CIDR": "source_ip_cidr",
    "SRC-PORT": "source_port",

    "DST-PORT": "port",

    "PROCESS-PATH": "process_path",
    "PROCESS-PATH-REGEX": "process_path_regex",
    "PROCESS-NAME": "process_name",

    "NETWORK": "network",

    "UID": "user_id",

    "IN_NAME": "inbound",

    "Sing_PROTOCOL": "protocol",


    "AND": "and",
    "OR": "or",
    // "NOT": "invert", // #TBD: invert rules
}

// mihomo source route rule w/o matching or no need to convert

// IP-SUFFIX IP-ASN // destination IP rules
// SRC-GEOIP SRC-IP-ASN SRC-IP-SUFFIX // source IP rules
// IN-PORT IN-TYPE IN-USER IN-NAME // inbound rules
// PROCESS-NAME-REGEX
// UID
// DSCP

// RULE-SET
// SUB-RULE
// MATCH


================================================
FILE: functions/internal/data/ruleset/transformGeoRef.ts
================================================
export type headlessRuleSet = {
    type: "remote",
    tag: string,
    url: string,
    format: "binary" | "source",
}


export function transformGeoRef (
    type: string, 
    payload: string, 
    EdgeSubInstanceBaseURL
): { 
    headlessRule: any, 
    headlessRuleSet: headlessRuleSet | null
} {
    const RuleSetTag = `${type}-${payload.toLowerCase()}`;

    if (RuleSetTag === "geoip-lan") {
        return {
            headlessRule: {
                ip_is_private: true,
        
            },
            headlessRuleSet: null
        }
    }

    // let edge-sub preprocess the rule-set
    // construct url
        let RuleSetURLObject = new URL(EdgeSubInstanceBaseURL);
            RuleSetURLObject.pathname = "/ruleset/proxy";
            RuleSetURLObject.search = "";
            RuleSetURLObject.searchParams.append("target", `https://raw.githubusercontent.com/SagerNet/sing-geoip/rule-set/${RuleSetTag}.srs`);
    const RuleSetURL = RuleSetURLObject.toString();

    return {
        headlessRule: {
            rule_set: RuleSetTag,
        },
        headlessRuleSet: {
            type: "remote",
            tag: RuleSetTag,
            format: "binary",
            url: RuleSetURL,
        }
    }
}

================================================
FILE: functions/internal/getParsedSubData.ts
================================================
import type { ClashMetaConfig } from "./types/ClashMetaConfig";

import { DefaultRequestHeaders } from "./configs";

import { ShareLinkParser } from "./Parsers/share-link";
import { ClashMetaParser } from "./Parsers/clash-meta";
import { SingBoxParser } from "./Parsers/sing-box";

import { parseYAML } from "confbox";
import { TrulyAssign } from "./utils/TrulyAssign";
import { parseContentDisposition } from "./utils/parseContentDisposition";

type SubURL = string; // start with `short:`, `http(s)://`, or sth like `[proxy protocol]://`
type SubURLs = string; // contains SubURL a lot
type SubURLArr = SubURL[]; // usually it is some SubURLs squeeze into a Array.
type ParsedSubscription = {
    data: any[];
    SubscriptionUserInfo?: SubscriptionUserInfo;
};
type SubscriptionUserInfo = {
    traffic?: string; // e.g. 'upload=<bytes>; download=<bytes>; total=<bytes>; expire=<timestamp>', from `subscription-userinfo` header
    name?: string; // e.g. 'Nexitally', from `content-disposition` header filename field.
}

/**
 * 
 * @returns {Array}
 */
export default async function getParsedSubData (
    SubURLs: SubURLs, 
    EdgeSubDB, 
    isShowHost = false as boolean,
    CustomHTTPHeaders = {} as Headers,
    ExcludeRegExpPattern = "" 
) {
    let __startTime = performance.now();
    console.info("[Fetch Sub Data] Job started")
    console.info(`[Fetch Sub Data] isShowHost: ${isShowHost.toString()}`)

    const RequestHeaders = TrulyAssign(DefaultRequestHeaders, CustomHTTPHeaders);

    let SubURLArr = SubURLs.replaceAll("\r", "\n").split("\n").filter((i) => !!i).map(i => encodeURIComponent(i.trim())).map(i => decodeURIComponent(i)) as SubURLArr;
    let Proxies = [],
        SubscriptionUserInfos: SubscriptionUserInfo[] = [];
    for (let i in SubURLArr) {
        console.info(`[Fetch Sub Data] Fetching ${parseInt(i) + 1}/${SubURLArr.length}`)
        const ParsedSubscription = await ParseSubData(SubURLArr[i], EdgeSubDB, RequestHeaders);
        Proxies = [...Proxies, ...ParsedSubscription.data];
        if (ParsedSubscription.SubscriptionUserInfo) {
            SubscriptionUserInfos.push(ParsedSubscription.SubscriptionUserInfo);
        }
    }

    if (isShowHost === true) {
        Proxies = Proxies.map(i => {
            i.__Remark = `${i.__Remark} - ${i.Hostname}:${i.Port}`
            return i;
        })
    }

    if (!!ExcludeRegExpPattern) {
        const ExcludeRegExp = new RegExp(ExcludeRegExpPattern, "g")
        console.log("[Fetch Sub Data] filtering out outbounds matched with", ExcludeRegExp)
        Proxies = Proxies.filter(i => !i.__Remark.match(ExcludeRegExp))
    }

    console.info(`[Fetch Sub Data] Job done, wasting ${performance.now() - __startTime}ms.`)
    return {Proxies, SubscriptionUserInfos};
}
async function ParseSubData (SubURL: SubURL, EdgeSubDB, RequestHeaders) : Promise<ParsedSubscription> {

    // pre define SubscriptionUserInfo
    let SubscriptionUserInfo: SubscriptionUserInfo;

    // handle `short` here
    if (SubURL.match(/^short:/i)) {
        let ShortData: SubURLs = await EdgeSubDB.get(SubURL).then(res => JSON.parse(res).subdata);
        console.info(`[Fetch Sub Data] starting sub task for ${SubURL}`)
        let ParsedShortData = (await getParsedSubData(ShortData, EdgeSubDB, RequestHeaders)).Proxies;
        console.info(`[Fetch Sub Data] sub task for ${SubURL} done`)
        return { data: ParsedShortData };
    }

    let SubData;
    // handle bundle share link (not starts with `http(s|)://` )
    if (!SubURL.match(/^http(s|):\/\//i)) {
        SubData = {
            type: "share-link",
            data: SubURL
        }
    } else {
        SubData = await fetch(SubURL, { headers: RequestHeaders })
            .then(async res => { 
                console.info(`[Fetch Sub Data] Response status code ${res.status}`);
                return {
                    data: await res.text(),
                    headers: res.headers
                }
            })
            .then(res => {
                // fill out SubscriptionUserInfo
                SubscriptionUserInfo = {
                    traffic: res.headers.has("Subscription-UserInfo") ? res.headers.get("Subscription-UserInfo") : null,
                    name: res.headers.has("Content-Disposition") ? parseContentDisposition(res.headers.get("Content-Disposition")) : null
                };
                // try decode as yaml, for clash-meta config
                try {
                    let YAMLData = parseYAML(res.data) as ClashMetaConfig;
                    if (YAMLData.proxies) {
                        return {
                            type: "clash-meta",
                            data: YAMLData
                        }
                    }
                } catch (e) {
                    console.warn(`[Fetch Sub Data] Err when try parse as yaml: ${e}, skipping...`)
                }
                // try decode as json, for sing-box config
                try {
                    let SingBoxConfig = JSON.parse(res.data);
                    if (SingBoxConfig.outbounds) {
                        return {
                            type: "sing-box",
                            data: SingBoxConfig
                        }
                    }
                } catch (e) {
                    console.warn(`[Fetch Sub Data] Err when try parse as JSON (sing-box): ${e}, skipping...`)
                }

                // try decode as base64 endoded share-links
                try {
                    let decodedData = atob(res.data.trim());
                    if (!decodedData.match(/\:\/\//gi)) {
                        throw "seems like base64 decoded data malformed"
                    }
                    return {
                        type: "share-link",
                        data: decodedData
                    }
                } catch (e) {
                    console.warn(`[Fetch Sub Data] try parse as base64: ${e}, skipping...`)
                }

                // final return as share-link
                return {
                    type: "share-link",
                    data: res.data
                }
            })
    }

    let ParsedSubData = [];
    if (SubData.type === "share-link") {
        let links = SubData.data.replaceAll("\r", "\n").split("\n").filter(loc => !!loc);
        let Parser = new ShareLinkParser();
        for (let i of links) {
            let protocol = i.split(":")[0];
            try {
                if (Parser.__validate(i)) {
                    ParsedSubData.push(Parser[protocol](i))
                }
            } catch (e) {
                console.warn(`[Fetch Sub Data] this share-url doesn't seem right, ignoring... ('${i}')`)
                console.warn(e)
            }
        }
    } else if (SubData.type === "clash-meta") {
        let { proxies } = SubData.data;
        let Parser = new ClashMetaParser();
        for (let i of proxies) {
            if (Parser.__validate(i)) {
                ParsedSubData.push(Parser[i.type](i))
            }
        }
    } else if (SubData.type === "sing-box") {
        let { outbounds } = SubData.data;
        let Parser = new SingBoxParser();
        for (let i of outbounds) {
            if (Parser.__validate(i)) {
                ParsedSubData.push(Parser[i.type](i))
            }
        }
    }
    
    return {
        data: ParsedSubData,
        SubscriptionUserInfo,
    };
}

================================================
FILE: functions/internal/types/ClashMetaConfig.ts
================================================
// reference: https://wiki.metacubex.one/

type ClashMetaProxyGroup = {
    name: string;
    type: string; // head to https://wiki.metacubex.one/config/proxy-groups/
    url?: string | URL;
    interval?: number;
    tolerance?: number;
    proxies: string[]
}

export type ClashMetaConfig = {
    port: number;
    "socks-port": number;
    "allow-lan": boolean;
    mode: "Rule" | "Global" | "Direct";
    "log-level": "silent" | "error" | "warning" | "info" | "debug";
    "external-controller": string; // start with ":"
    ipv6: boolean; // default true
    dns: {
        enabled: boolean; // default true
        nameserver: string[];
        fallback: string[];
    };
    proxies: []
    "proxy-groups": ClashMetaProxyGroup[];
    rules: string[] // head to https://wiki.metacubex.one/config/rules/
}




// for transport layers
export type TransportHTTP = {
    method: string;
    path: string[];
    headers?: {
        host?: string
    };
}
export type TransportH2 = {
    method: string;
    path: string;
}
export type TransportGRPC = {
    "grpc-service-name": string;
}
export type TransportWS = {
    path?: string;
    headers?: {
        host?: string
    };
    "max-early-data"?: number;
    "early-data-header-name"?: "Sec-WebSocket-Protocol" | string;
    "v2ray-http-upgrade"?: unknown;
    "v2ray-http-upgrade-fast-open"?: unknown;
}

// for reality
export type RealityConfig = {
    "public-key"?: string;
    "short-id"?: string;
}

================================================
FILE: functions/internal/utils/TrulyAssign.js
================================================
/**
 * Assign source to target, note that its only for the first frame. 
 * You will not get the target modified, instead, the target you need is in the returns.
 * @param {Object} target 
 * @param {Object} source 
 * @returns {Object} Assigned Target
 */
export function TrulyAssign (target, source) {
    let DeepCopiedTarget = JSON.parse(JSON.stringify(target))
    for (let key in source) {
        if (key in source && source[key] !== "__DEFAULT") {
            DeepCopiedTarget[key] = source[key];
        }
    }
    return DeepCopiedTarget;
}


================================================
FILE: functions/internal/utils/fetchCached.ts
================================================
export async function fetchCached (URL: URL, Prefix = "Cached", CacheDB: KVNamespace, isForcedRefresh = false) {
    // const CacheKey = `RuleProvider_${URL}`;
    const CacheKey = `${Prefix}_${URL}`;
    const CacheTTL =  6 * 60 * 60; // 6hrs for default

    // check if data was cached
    let CachedData: string | null;
    if (!CacheDB) {
        CachedData = null;
        console.info(`[fetchCached] - CacheDB is not configured, fetching.`)
    } else {
        if (isForcedRefresh) {
            CachedData = null;
        } else {
            CachedData = await CacheDB.get(CacheKey)
        }
    }

    // return cached data when it exist
    if (CachedData) {
        return CachedData;
    }

    console.info(`[fetchCached] - "${CacheKey}" is not cached, fetching.`)
    // only when CachedData == falsy
    let data = await fetch (URL)
        .then(res => {
            if (res.status === 200 || res.status === 304) {
                return res
            } else {
                throw "Failed to fetch."
            }
        })
        .then(res => res.text())
        .catch(() => null);
    // save it into CacheDB when success, and, whatever, when CacheDB exist.
    if (data !== null && CacheDB) {
        await CacheDB.put(CacheKey, data.toString(), { expirationTtl: CacheTTL })
    }
    // just return
    return data;
}


================================================
FILE: functions/internal/utils/parseContentDisposition.ts
================================================
export function parseContentDisposition(RawContentDispositionHeader: string): string {
    if (!RawContentDispositionHeader || !RawContentDispositionHeader.toLowerCase().startsWith('attachment')) {
        console.warn('Invalid Content-Disposition header');
        return null;
    }

    // Match filename*= (RFC 5987)
    const filenameStarMatch = RawContentDispositionHeader.match(/filename\*\s*=\s*([^'"]*)''([^;]+)/i);
    if (filenameStarMatch) {
        try {
            const encoding = filenameStarMatch[1].toLowerCase();
            const filenameEncoded = filenameStarMatch[2];
            return decodeURIComponent(filenameEncoded);
        } catch (err) {
            return null;
        }
    }

    // Match filename= (quoted or unquoted)
    const filenameMatch = RawContentDispositionHeader.match(/filename\s*=\s*("?)([^";]+)\1/i);
    if (filenameMatch) {
        return filenameMatch[2];
    }

    return null; // No fucking filename found
}


================================================
FILE: functions/internal/utils/removeUndefinedFields.ts
================================================
export function removeUndefinedFields (obj: object) : object {
    for (const key in obj) {
        if (typeof obj[key] === 'object' && obj[key] !== null) {
            removeUndefinedFields(obj[key]);
        }
        if (obj[key] === undefined) {
            delete obj[key];
        }
    }
    return obj;
}


================================================
FILE: functions/ruleset/preprocessor/sing-box.ts
================================================
import { fetchCached } from "../../internal/utils/fetchCached.js";
import { MetaToSingRuleMapping } from "functions/internal/data/rule/MetaToSingMapping.js";

export async function onRequest (context) {
    const { request } = context;
    const URLObject = new URL(request.url);

    const targetURL = URLObject.searchParams.get("target") as unknown as URL;
    const isForcedRefresh = URLObject.searchParams.get("forced_refresh") === "true" ? true : false;

    if (!targetURL) {
        return new Response("400 Bad Request. 'targetURL' required.", {
            status: 200,
            headers: {
                "Content-Type": "text/plain; charset=utf-8"
            }
        })
    }


    let RawData = await fetchCached(targetURL, "RuleSet", context.env.EdgeSubDB, isForcedRefresh);

    let RulesList = RawData.split("\n").map(i => i.trim()).filter(i => i.length > 0 && !i.startsWith("#")).map(i => i.split(",").map(j => j.trim()));

    // merge up rules
    let rules = {}; // ref: https://sing-box.sagernet.org/configuration/rule-set/headless-rule/
    for (let i of RulesList) {
        const type = MetaToSingRuleMapping[i[0]],
              payload = i[1];
        if (!type) {
            continue
        }
        if (!(type in rules)) {
            rules[type] = [];
        }
        rules[type].push(payload);
    }


    return new Response(JSON.stringify({ "version": 1, rules: [ rules ] }), {
        status: 200,
        headers: {
            "Content-Type": "application/json; charset=utf-8",
            "Content-Length": RawData.length
        }
    })
}


================================================
FILE: functions/ruleset/proxy.ts
================================================
import { fetchCached } from "../internal/utils/fetchCached.js";

export async function onRequest (context) {
    const { request } = context;
    const URLObject = new URL(request.url);

    const targetURL = URLObject.searchParams.get("target") as unknown as URL;

    if (!targetURL) {
        return new Response("400 Bad Request. 'targetURL' required.", {
            status: 200,
            headers: {
                "Content-Type": "text/plain; charset=utf-8"
            }
        })
    }

    let RawData = await fetch(targetURL);
    return new Response(RawData.body, {
        status: 200,
        headers: RawData.headers
    })
}


================================================
FILE: functions/short/admin-password/set.ts
================================================
import { getDefaultHeader, getOptionsHeader } from "../utils/defaultHeader";
import { sha256 } from "js-sha256";

export async function onRequestPost (context) {
    const { request } = context;
    const url = new URL(request.url);
    const defaultHeader = getDefaultHeader(url);

    const EdgeSubDB = context.env.EdgeSubDB;
    const { 
        oldPassword, // will be false is client thinks the password is not set
        newPassword // new password, not hashed
    } = await request.json()
    const hashedOldPassword = sha256(oldPassword)
    const hashedNewPassword = sha256(newPassword)

    // security check?
    if (url.hostname === "localhost") {
        console.info("[setPassword - security check] in development, ignoring...")
    } else {
        if (url.protocol === "http:") {
            console.warn("[setPassword - security check] requested via http, upgrading to https")
            if (url.protocol === "http:") {
                url.protocol = "https:"
                return Response.redirect(url.toString(), 301)
            }
        }
    }

    if (!newPassword) {
        return new Response (
            JSON.stringify({
                msg: "new password cant be empty",
                passwordUpdated: false
            }), {
                status: 400,
                headers: defaultHeader
            }
        )
    }


    let oldPasswordInDB = await EdgeSubDB.get("admin-password");
    if (
        !oldPasswordInDB || // should be true when there isn't any old password
        hashedOldPassword == oldPasswordInDB // should be true when there is an password in db and matched
    ) {
        await EdgeSubDB.put("admin-password", hashedNewPassword);
    } else {
        return new Response (
            JSON.stringify({
                msg: "the provided old password does not match with the old password in database.",
                passwordUpdated: false
            }), {
                status: 422,
                headers: defaultHeader
            }
        )
    }


    return new Response (
        JSON.stringify({
            msg: "OK",
            passwordUpdated: true
        }), {
            status: 200,
            headers: defaultHeader
        }
    )

}
export async function onRequestOptions (context) {
    const url = new URL(context.request.url);
    return new Response("OK", {
        status: 200,
        headers: getOptionsHeader(url)
    });
}


================================================
FILE: functions/short/admin-password/status.ts
================================================
import { getDefaultHeader, getOptionsHeader } from "../utils/defaultHeader";

export async function onRequest (context) {
    const { request } = context;
    const defaultHeader = getDefaultHeader(new URL(request.url));

    const EdgeSubDB = context.env.EdgeSubDB;

    let hashedPassword = await EdgeSubDB.get("admin-password");
    return new Response (
        JSON.stringify({
            msg: "OK",
            isPasswordSet: !!hashedPassword
        }), {
            status: 200,
            headers: defaultHeader
        }
    )
}

================================================
FILE: functions/short/delete/[id].ts
================================================
import { getDefaultHeader, getOptionsHeader } from "../utils/defaultHeader";

export async function onRequestDelete (context) {
    const { id } = context.params;
    const EdgeSubDB = context.env.EdgeSubDB;
    const defaultHeader = getDefaultHeader(new URL(context.request.url));

    let { token } = await context.request.json();

    if (!token) {
        return new Response(
            JSON.stringify({
                msg: "400 Bad Request. token missing or empty."
            }), {
                status: 400,
                headers: defaultHeader
            }
        )
    }


    let storedData = await EdgeSubDB.get(`short:${id}`);
    if (storedData) {
        // when data exists
        let storedJSON = JSON.parse(storedData);
        let storedToken = storedJSON.token ?? storedJSON.password;
        if (storedToken !== token) { 
            // when token doesnt matchs
            return new Response(
                JSON.stringify({
                    msg: "401 Unauthorized. Incorrect short token."
                }), {
                    status: 401,
                    headers: defaultHeader
                }
            )
        }
    } else {
        return new Response(
            JSON.stringify({
                msg: "404 Not Found. requested short not exist.",
            }), {
                status: 404,
                headers: defaultHeader
            }
        )
    }

    // when all the things seems right, eg: data not exist or token matches.
    await EdgeSubDB.delete(`short:${id}`)
    return new Response(
        JSON.stringify({
            msg: `200 OK. short:${id} has been deleted.`,
        }), {
            status: 200,
            headers: defaultHeader
        }
    )
}
export async function onRequestOptions (context) {
    return new Response("OK", {
        status: 200,
        headers: getOptionsHeader(new URL(context.request.url), [ "DELETE" ])
    });
}






================================================
FILE: functions/short/get/[id].ts
================================================
import { getDefaultHeader } from "../utils/defaultHeader";

export async function onRequest (context) {
    const { id } = context.params;
    const EdgeSubDB = context.env.EdgeSubDB;
    const defaultHeader = getDefaultHeader(new URL(context.request.url));

    let storedData = await EdgeSubDB.get(`short:${id}`);
    if (storedData) {
        let { subdata } = JSON.parse(storedData);
        return new Response(
            JSON.stringify({
                msg: "OK",
                subdata,
            }), {
                status: 200,
                headers: defaultHeader
            }
        )
    } else {
        return new Response(
            JSON.stringify({
                msg: "Not Found"
            }), {
                status: 404,
                headers: defaultHeader
            }
        )
    }
}

================================================
FILE: functions/short/list.ts
================================================
import { getDefaultHeader, getOptionsHeader } from "./utils/defaultHeader";
import { sha256 } from "js-sha256";

export async function onRequestPost (context) {
    const { request } = context;
    const defaultHeader = getDefaultHeader(new URL(request.url));

    const EdgeSubDB = context.env.EdgeSubDB;

    const { password } = await request.json()
    const hashedPassword = sha256(password)
    const hashedPasswordInDB = await EdgeSubDB.get("admin-password");

    // check for password
    if (hashedPassword !== hashedPasswordInDB) {
        return new Response (
            JSON.stringify({
                msg: "the provided old password does not match with the old password in database",
                success: false,
                shortIDs: []
            }), {
                status: 401,
                headers: defaultHeader
            }
        )
    }

    // const shortIDs = 
    //     ((await EdgeSubDB.list({ prefix: "short:" })).keys || [])
    //         .map(i => { 
    //             return { 
    //                 name: i.name, 
    //                 timestamp: EdgeSubDB.get(i.name).then(res => JSON.parse(res).timestamp) // its needed to be
    //             }
    //         });
    const shortIDs = await EdgeSubDB.list({ prefix: "short:" })
        .then(async listResult => {
            const keys = listResult.keys || [];
            const shortIDs = [];
            for (let i of keys) {
                let ShortItem = await EdgeSubDB.get(i.name)
                    .then(res => JSON.parse(res).timestamp)
                    .then(timestamp => ({ name: i.name, timestamp }));
                shortIDs.push(ShortItem)
            }
            return shortIDs
        })
        .catch(error => {
            throw "Error fetching short IDs:" + error
        });

    return new Response (
        JSON.stringify({
            msg: "OK",
            success: true,
            shortIDs
        }), {
            status: 200,
            headers: defaultHeader
        }
    )

}
export async function onRequestOptions (context) {
    const url = new URL(context.request.url);
    return new Response("OK", {
        status: 200,
        headers: getOptionsHeader(url)
    });
}


================================================
FILE: functions/short/put.ts
================================================
import { getDefaultHeader, getOptionsHeader } from "./utils/defaultHeader";

export async function onRequestPost (context) {
    const { request } = context;
    const defaultHeader = getDefaultHeader(new URL(request.url));
    const timestamp = Date.now();

    const EdgeSubDB = context.env.EdgeSubDB;
    let { slug, token, subdata } = await request.json();

    if (!slug && !token) {
        slug = await generateToken(8, EdgeSubDB);
        token = await generateToken(16);
    }


    let storedData = await EdgeSubDB.get(`short:${slug}`);
    if (storedData) {
        // when data exists
        let storedJSON = JSON.parse(storedData);
        let storedToken = storedJSON.token ?? storedJSON.password;
        if (storedToken !== token) { 
            // when token doesnt matchs
            return new Response(
                JSON.stringify({
                    msg: "401 Unauthorized. Incorrect short token.",
                    slug,
                }), {
                    status: 401,
                    headers: defaultHeader
                }
            )
        }
    }

    // when all the things seems right, eg: data not exist or token matches.
    await EdgeSubDB.put(`short:${slug}`, JSON.stringify({
        token, subdata, timestamp
    }))
    return new Response(
        JSON.stringify({
            msg: "OK",
            slug,
            token
        }), {
            status: 200,
            headers: defaultHeader
        }
    )
}
export async function onRequestOptions (context) {
    return new Response("OK", {
        status: 200,
        headers: getOptionsHeader(new URL(context.request.url))
    });
}


async function generateToken (length, EdgeSubDB = undefined) {
    const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    let strArr = [];
    for (let i = 0, n = chars.length; i < length; i++) {
        strArr.push(chars[Math.floor(Math.random() * n)])
    }
    let str =  strArr.join("");
    if ( EdgeSubDB && !!(await EdgeSubDB.get(`short:${str}`)) ) {
        return generateToken(length, EdgeSubDB);
    }
    return str;
}


================================================
FILE: functions/short/token-reset/[id].ts
================================================
import { getDefaultHeader, getOptionsHeader } from "../utils/defaultHeader";

export async function onRequestPatch (context) {
    const { id } = context.params;
    const EdgeSubDB = context.env.EdgeSubDB;
    const defaultHeader = getDefaultHeader(new URL(context.request.url));

    let { oldToken, newToken } = await context.request.json();

    if (!oldToken || !newToken) {
        return new Response(
            JSON.stringify({
                msg: "400 Bad Request. oldToken or newToken missing or empty."
            }), {
                status: 400,
                headers: defaultHeader
            }
        )
    }


    let storedData = await EdgeSubDB.get(`short:${id}`);
    let storedJSON = JSON.parse(storedData);
    if (storedData) {
        // when data exists
        let storedToken = storedJSON.token ?? storedJSON.password;
        if (storedToken !== oldToken) { 
            // when oldToken doesnt matchs
            return new Response(
                JSON.stringify({
                    msg: "401 Unauthorized. Incorrect short oldToken."
                }), {
                    status: 401,
                    headers: defaultHeader
                }
            )
        }
    } else {
        return new Response(
            JSON.stringify({
                msg: "404 Not Found. requested short not exist.",
            }), {
                status: 404,
                headers: defaultHeader
            }
        )
    }

    // when all the things seems right, eg: data not exist or token matches.
    storedJSON.token = newToken;
    await EdgeSubDB.put(`short:${id}`, JSON.stringify(storedJSON))
    return new Response(
        JSON.stringify({
            msg: `200 OK. short:${id}'s token has been changed.`,
        }), {
            status: 200,
            headers: defaultHeader
        }
    )
}
export async function onRequestOptions (context) {
    return new Response("OK", {
        status: 200,
        headers: getOptionsHeader(new URL(context.request.url), [ "PATCH" ])
    });
}


================================================
FILE: functions/short/utils/defaultHeader.ts
================================================
export const getDefaultHeader = (url: URL) => { 
    return {
        "Access-Control-Allow-Origin": getAllowedOriginHeader(url),
        "content-type": "application/json, charset=utf-8",
        "Access-Control-Allow-Credentials": "true",
    } as unknown as Headers;
}
export const getOptionsHeader = (url: URL, Methods = [ "POST" ]) => { 
    Methods.push("OPTIONS")
    return {
        //"Access-Control-Allow-Origin":  "localhost:4321")
        "Access-Control-Allow-Origin": getAllowedOriginHeader(url),
        "Access-Control-Allow-Credentials": "true",
        "Access-Control-Allow-Methods": Methods.join(", "),
    } as unknown as Headers;
}

const getAllowedOriginHeader = (url: URL) => url.hostname === "localhost" ? "*" : `${url.protocol}//${url.host}`;

================================================
FILE: functions/sub/base64.js
================================================
import { onRequest as ShareLinkOnRequest } from "./share-link.js";

export async function onRequest (context) {
    return await ShareLinkOnRequest(context, true)
}


================================================
FILE: functions/sub/clash-meta.js
================================================
import { getClashMetaConfig } from "../internal/Converter/getClashMetaConfig.js";
import getParsedSubData from "../internal/getParsedSubData.ts";
import { stringifyYAML } from "confbox";


export async function onRequest (context) {
    const { request } = context;
    const URLObject = new URL(request.url);
    let { Proxies, SubscriptionUserInfos } = await getParsedSubData(
        URLObject.searchParams.get("url"), 
        context.env.EdgeSubDB, 
        URLObject.searchParams.get("show_host") === "true",
        JSON.parse(URLObject.searchParams.get("http_headers")),
        URLObject.searchParams.get("ExcludeRegExpPattern"),
    );
    // a javascript object !!! not YAML !!!
    let ClashMetaConfigObject = await getClashMetaConfig (
        Proxies,
        context.env.EdgeSubDB,
        {
            isUDP: URLObject.searchParams.get("udp") === "true",
            isSSUoT: URLObject.searchParams.get("ss_uot") === "true",
            isInsecure: true,
            RuleProvider: URLObject.searchParams.get("remote_config") || "__DEFAULT",
            RuleProvidersProxy: URLObject.searchParams.get("rule_providers_proxy"),
            BaseConfig: URLObject.searchParams.get("BaseConfig"),
            isForcedRefresh: URLObject.searchParams.get("forced_refresh") === "true",
        }
    )

    // handle forced ws 0-rtt
    if (URLObject.searchParams.get("forced_ws0rtt") === "true") {
        console.info("[Main] ForcedWS0RTT enabled.")
        for (let i of ClashMetaConfigObject.proxies) {
            if (!("ws-opts" in i)) {
                continue;
            }
            i["ws-opts"]["max-early-data"] = 2560
            i["ws-opts"]["early-data-header-name"] = "Sec-WebSocket-Protocol"
        }
    }

    const ResponseBody = stringifyYAML(ClashMetaConfigObject);
    const response = new Response(
        ResponseBody, 
        {
            status: 200,
            headers: {
                "Content-Type": "text/plain; charset=utf-8",
                "Content-Length": ResponseBody.length,
                "Cache-Control": "no-cache, no-store, must-revalidate",
                "Pragma": "no-cache",
                "Expires": "0",
            }
        }
    )

    if (SubscriptionUserInfos.length > 0) {
        let Names = SubscriptionUserInfos.map(i => i.name).filter(i => !!i);
        // two name, then eclipse...
        let NamesLimit = Names.length > 2 ? 2 : Names.length;
        let Filename = `${Names.slice(0, NamesLimit).join(", ")}, and ${SubscriptionUserInfos.length - NamesLimit} more`;
        response.headers.set("Content-Disposition", `attachment; filename*=UTF-8''${encodeURIComponent(Filename)}.yaml`);

        let Traffic = SubscriptionUserInfos.map(i => i.traffic).filter(i => !!i)[0]; // first element of SubscriptionUserInfos
        // if Names.length > 1, then we shouldn't use such per-profile specific traffic values.
        if (Names.length === 1) {
            response.headers.set("Subscription-UserInfo", Traffic);
        }
    }
    
    return response;
}

================================================
FILE: functions/sub/debug.js
================================================
import getParsedSubData from "../internal/getParsedSubData.ts";

export async function onRequest (context) {
    const { request } = context;
    const URLObject = new URL(request.url);
    const { Proxies } = await getParsedSubData(
        URLObject.searchParams.get("url"), 
        context.env.EdgeSubDB, 
        URLObject.searchParams.get("show_host") === "true",
        JSON.parse(URLObject.searchParams.get("http_headers")),
        URLObject.searchParams.get("ExcludeRegExpPattern"),
    );
    const ResponseBody = JSON.stringify(Proxies)
    
    return new Response(ResponseBody, {
        status: 200,
        headers: {
            "Content-Type": "application/json, charset=utf-8",
            "Content-Length": ResponseBody.length,
        }
    })
}

================================================
FILE: functions/sub/share-link.js
================================================
import getParsedSubData from "../internal/getParsedSubData.ts";
import { ShareLinkDumper } from "../internal/Dumpers/share-link.js";

export async function onRequest (context, isBase64 = false) {
    const { request } = context;
    const URLObject = new URL(request.url);
    // do convert
    const { Proxies } = await getParsedSubData(
        URLObject.searchParams.get("url"), 
        context.env.EdgeSubDB, 
        URLObject.searchParams.get("show_host") === "true",
        JSON.parse(URLObject.searchParams.get("http_headers")),
        URLObject.searchParams.get("ExcludeRegExpPattern"),
    );
    let Dumper = new ShareLinkDumper();
    let ShareLinkArray = [];
    for (let i of Proxies) {
        if (Dumper[i.__Type]) {
            ShareLinkArray.push(Dumper[i.__Type](i))
        }
    }
    
    // generate final response
    let ShareLinkResponse = ShareLinkArray.join("\n");
    if (isBase64 === true) {
        ShareLinkResponse = btoa(ShareLinkResponse);
    }

    return new Response(ShareLinkResponse, {
        status: 200,
        headers: {
            "Content-Type": "text/plain, charset=utf-8",
            "Content-Length": ShareLinkResponse.length
        }
    })
}


================================================
FILE: functions/sub/sing-box.js
================================================
import { getSingBoxConfig } from "../internal/Converter/getSingBoxConfig.ts";
import getParsedSubData from "../internal/getParsedSubData.ts";

export async function onRequest (context) {
    const { request } = context;
    const URLObject = new URL(request.url);
    let { Proxies } = await getParsedSubData(
        URLObject.searchParams.get("url"), 
        context.env.EdgeSubDB, 
        URLObject.searchParams.get("show_host") === "true",
        JSON.parse(URLObject.searchParams.get("http_headers")),
        URLObject.searchParams.get("ExcludeRegExpPattern"),
    );

    // a javascript object !!! not YAML !!!
    let SingBoxConfigObject = await getSingBoxConfig (
        Proxies,
        context.env.EdgeSubDB,
        {
            isUDP: URLObject.searchParams.get("udp") === "true",
            isSSUoT: URLObject.searchParams.get("ss_uot") === "true",
            isInsecure: true,
            RuleProvider: URLObject.searchParams.get("remote_config") || "__DEFAULT",
            RuleProvidersProxy: URLObject.searchParams.get("rule_providers_proxy"),
            BaseConfig: URLObject.searchParams.get("BaseConfig"),
            isForcedRefresh: URLObject.searchParams.get("forced_refresh") === "true" ? true : false
        }
    )

    // handle forced ws 0-rtt
    if (URLObject.searchParams.get("forced_ws0rtt") === "true") {
        console.info("[Main] ForcedWS0RTT enabled.")
        for (let i of SingBoxConfigObject.outbounds) {
            if (!("transport" in i)) {
                continue;
            }
            if (i.transport.type !== "ws") {
                continue;
            }
            i.transport.max_early_data = 2560
            i.transport.early_data_header_name = "Sec-WebSocket-Protocol"
        }
    }

    const ResponseBody = JSON.stringify(SingBoxConfigObject)

    return new Response(ResponseBody, {
        status: 200,
        headers: {
            "Content-Type": "application/json; charset=utf-8",
            "Content-Length": ResponseBody.length,
        }
    })
}

================================================
FILE: package.json
================================================
{
  "name": "edge-sub",
  "type": "module",
  "version": "1.0.0",
  "license": "AGPL-3",
  "author": "kobe-koto",
  "homepage": "https://github.com/kobe-koto/EdgeSub",
  "scripts": {
    "build:frontend": "astro build",
    "dev": "concurrently 'wrangler pages dev ./' 'astro dev'",
    "dev:frontend": "astro dev",
    "dev:backend": "wrangler pages dev ./",
    "generate-types": "wrangler types ./types/worker-configuration.d.ts",
    "type-check": "generate-types && tsc"
  },
  "dependencies": {
    "@iconify-json/iconoir": "^1.2.7",
    "@tailwindcss/vite": "^4.1.10",
    "astro": "5.4.1",
    "astro-compress": "^2.3.6",
    "astro-icon": "^1.1.5",
    "astro-seo": "^0.8.4",
    "confbox": "^0.2.2",
    "daisyui": "^5.0.43",
    "generate-password": "^1.7.1",
    "js-sha256": "^0.11.0",
    "sass": "^1.85.1",
    "tailwindcss": "^4.1.10"
  },
  "devDependencies": {
    "concurrently": "^9.2.0"
  },
  "trustedDependencies": [
    "@parcel/watcher",
    "@tailwindcss/oxide",
    "esbuild",
    "sharp"
  ]
}

================================================
FILE: public/basic-config/mihomo.yaml
================================================
auto-detect-interface: true
log-level: "info"

port: 7890
mixed-port: 7891

mode: "Rule"
external-controller: ":9090"


dns:
  enable: true
  ipv6: true
  listen: 0.0.0.0:1053
  cache-algorithm: arc
  respect-rules: false
  enhanced-mode: fake-ip
  fake-ip-range: 198.18.0.1/16
  fake-ip-filter-mode: blacklist
  fake-ip-filter:
    - '*'
    - '.lan'
    - lancache.steamcontent.com
  default-nameserver:
    - 119.29.29.29
    - 223.5.5.5
  nameserver:
    - https://doh.pub/dns-query
    - https://dns.alidns.com/dns-query
  direct-nameserver:
    - https://doh.pub/dns-query
    - https://dns.alidns.com/dns-query
  fallback:
    - https://dns.google/dns-query
    - https://cloudflare-dns.com/dns-query
  fallback-filter:
    geoip: true
    geoip-code: CN
    ipcidr:
      - 240.0.0.0/4
      - 0.0.0.0/24
      - 127.0.0.1/24


================================================
FILE: public/basic-config/sing-box.jsonc
================================================
{
    "log": {
        "disabled": false,
        "level": "info"
    },
    "dns": {
        "servers": [
            {
                "tag": "hosts",
                "type": "hosts"
            },
            {
                "tag": "google",
                "type": "tls",
                "server": "8.8.8.8"
            },
            {
                "tag": "local",
                "type": "udp",
                "server": "223.5.5.5"
            },
            {
                "tag": "remote",
                "type": "fakeip",
                "inet4_range": "198.18.0.0/15",
                "inet6_range": "fc00::/18"
            }
        ],
        "rules": [
            {
                "ip_accept_any": true,
                "action": "route",
                "server": "hosts"
            },
            {
                "query_type": [
                "A",
                "AAAA"
                ],
                "server": "remote"
            }
        ],
        "independent_cache": true
    },

    "inbounds": [
        {
            "type": "mixed",
            "tag": "mixed-in",
            "listen": "127.0.0.1",
            "listen_port": 7890
        },
        {
            "type": "tun",
            "tag": "tun-in",
            "address": [
                "172.19.0.1/30",
                "fdfe:dcba:9876::1/126"
            ],
            "auto_route": true
        }
    ],
    "experimental": {
        "clash_api": {
            "external_controller": "127.0.0.1:9090",
            "external_ui": "ui",
            "secret": "",
            "external_ui_download_url": "https://github.com/MetaCubeX/metacubexd/archive/refs/heads/gh-pages.zip",
            "external_ui_download_detour": "DIRECT",
            "default_mode": "rule"
        },
        "cache_file": {
            "enabled": true,
            "store_fakeip": false
        }
    },
    "outbounds": [
        {
            "type": "direct",
            "tag": "DIRECT"
        }, {
            "type": "block",
            "tag": "REJECT"
        }
    ],
    "route": {
        "rules": [
            {
                "action": "sniff"
            }, {
                "protocol": "dns",
                "action": "hijack-dns"
            }, {
                "ip_is_private": true,
                "outbound": "direct"
            }, {
                "clash_mode": "direct",
                "outbound": "DIRECT"
            }, {
                "clash_mode": "global",
                "outbound": "GLOBAL"
            }
        ],
        "rule_set": [],
        "geosite": {
            "download_detour": "DIRECT"
        },
        "geoip": {
            "download_detour": "DIRECT"
        },
        "default_domain_resolver": "local",
        "auto_detect_interface": true
    }
}


================================================
FILE: public/minimal_remote_rules.ini
================================================
;https://raw.githubusercontent.com/kobe-koto/EdgeSub/main/public/minimal_remote_rules.ini

[custom]
ruleset=Proxies,[]DOMAIN-SUFFIX,googleapis.cn
ruleset=CN-Directed,[]GEOIP,CN
ruleset=CN-Directed,[]GEOSITE,CN
ruleset=Proxies,[]MATCH

custom_proxy_group=Proxies`select`[]DIRECT`[]REJECT`.*
custom_proxy_group=CN-Directed`select`[]DIRECT`[]REJECT`[]Proxies


================================================
FILE: readme.md
================================================
# Edge Sub

在 CloudFlare 的全球網絡上轉換您的代理訂閱.

請為我點一個 ⭐ Star!

## 使用方式

- ### UI
  
  在 Cloudflare Pages 部署後打開,並按提示操作。

- ### Debug

  > **⚠️ Warning**
  > 
  > 該格式隨時可能發生變更, 僅供測試用途

  Endpoint: `/sub/debug`

  需要以下參數:

  - `url`: 輸入的訂閱的遠程位址

## 部署

- ### 在 Cloudflare Pages 上部署

  0. Fork 本項目
  1. 打開 dash.cloudflare.com
  2. 轉到側邊欄上的 **Workers & Pages** (Overview) 部分
  3. 按下 **Create** 按鈕
  4. 切換到 **Pages** 欄
  5. 按 **Connect to Git**
  6. 選擇你剛 Fork 下來的 EdgeSub 項目
  7. 在 **Build settings > Framework preset** 中選擇 Astro
  8. 編輯 **Build settings > Build command** 為 `pnpm build:frontend`
  9. 按下 **Save and Deploy**
  10. 部署完成後,你可能需要添加自訂網域,請前往 **項目 > Custom domains** 添加
  
  #### ✡️ 可選 - 為遠端規則添加緩存以加快處理速度:
  
  **需要注意的是,開發時會以假設緩存 KV 存在來開發,無緩存 KV 環境將作為低優先級來開發。**
  
  **因此,不添加緩存 KV 是不被推薦的行為。**
  
  1. 轉到 **Workers & Pages > KV**
  2. 按 **Create a namespacce**,**輸入任意名字**,然後按 **Add**
  3. 回到項目
  4. 轉到 **Settings > Functions >  KV namespace bindings**
  5. 按 **Add binding**
  6. 在 **Variable name** 填寫 `EdgeSubDB`,**KV namespace** 選擇你剛建立的 KV 空間
  7. 點按 **Save**
  8. 轉到**項目 > Deployments**
  9. 在 **All deployments** 中找到最近的一個 Deployment,然後點**右側三個點 > Retry Deployment**
  10. 完成


## 相容性表格

- 節點類型

  | 類型         | 支援 | 已經測試 | Notes                                 |
  | ------------ | ---- | -------- | ------------------------------------- |
  | HTTP         | 🗿  | 🚫        | 由於與 **遠端訂閱** 不相容, 請勿直接傳入 HTTP Proxy |
  | Socks 5      | ✅    | 🚫        |                                       |
  | Hysteria 1   | ✅    | ✅        |                                       |
  | Hysteria 2   | ✅    | ✅        |                                       |
  | TUIC v5      | ✅    | ✅        |                                       |
  | Vmess        | ✅    | ☑️        | 未經完全測試                          |
  | Vless        | ✅    | ☑️        | 未經完全測試                          |
  | Shadowsocks  | ✅    | ✅        |  |
  | Trojan       | ✅    | ✅        |                                    |
  | WireGuard    | 🚫    | -        | 似乎沒有通用的 ShareLink 格式         |
  | ShadowsocksR | 🚫    | -        | 暫無計劃實現                          |
  | SSH          | 🚫    | -        | 暫無計劃實現                          |

- 訂閱類型

  | 類型                    | 輸入 | 輸出 | 輸出 Endpoint     |
  | ----------------------- | ---- | ---- | ----------------- |
  | 內部除錯用格式          | 🚫    | ✅    | `/sub/debug`      |
  | ShareLink 集合          | ✅    | ✅    | `/sub/share-link` |
  | ShareLink 集合 (Base64) | ✅    | ✅    | `/sub/base64`     |
  | Clash Meta 配置         | ✅    | ✅    | `/sub/clash-meta` |
  | Sing-Box 配置           | ✅    | ✅    | `/sub/sing-box`   |

  Notes:
  
  - Legacy Clash config support has been dropped at `Commit 13df326`
  
  - **內部除錯用格式**: 
  
    僅供除錯, 將會在未來的任意某個時間點做出破壞性改動或刪除.

## Remote Rules Parsing

**ONLY** support .ini with `ruleset=` `custom_proxy_group=` and comments.

### Special Remote Rules

- `Sing_PROTOCOL` see https://sing-box.sagernet.org/configuration/route/sniff/

## Handling Traffic and Name Information

**Note: This section's behavior description applies specifically to Clash Meta Config.**

This section describes how `traffic` and `name` information is processed from incoming data.

1.  **Data Parsing:**
    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`.
    
    *   A `Subscription` object may contain a `SubscriptionUserInfo` attribute.
    *   A `Proxy` object does not contain `SubscriptionUserInfo`.
    *   The `SubscriptionUserInfo` attribute, if present, contains `traffic` and `name` fields. Both `traffic` and `name` can be empty or absent within `SubscriptionUserInfo`.
    
2.  **Name Processing and Display:**
    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).

    *Note: A `name` might not be explicitly present or might be empty within a `SubscriptionUserInfo` object, even if `SubscriptionUserInfo` itself exists.*

3.  **Traffic Data Handling:**
    Traffic data is processed based on the number of unique "visible" names found:
    
    *   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."
    *   If **more than one** visible `name` is identified, traffic data will be ignored.

## Subscription Requesting

When requesting subscriptions based on user-provided data, the following HTTP headers are used:

1.  **Default HTTP Headers:**
    The application sends a set of default HTTP headers, as defined in `/functions/internal/configs.ts`. These include:
    
    ```json
    {
        "Accept": "*/*",
        "User-Agent": "EdgeSub-git/0.0.0 (Prefer ClashMeta / Mihomo Format)"
    }
    ```
    
2.  **User-Provided HTTP Headers:**
    Users can provide additional HTTP headers. The processing of these headers is as follows:
    
    *   Any non-empty and valid user-provided header that shares a key with a default HTTP header will **overwrite** the corresponding default header.
    *   Any non-conflicting user-provided headers (i.e., those with unique keys not present in the default set) will be **appended** to the request.

## Shorter Feature Security Overview

Shorts data is **stored remotely** is **unencrypted**.

*   Each short is uniquely identified by a **Short ID**.
*   **Short IDs** provide **read-only access** to a specific short.
*   A corresponding **Short Token** grants **write access** to a specific short. These tokens are for access control only and are **not encryption keys**.

The **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.


================================================
FILE: src/components/NavBar.astro
================================================
---
import { Icon } from "astro-icon/components";
---

<div class="navbar bg-base-100 shadow-sm mx-auto max-w-5xl rounded-b-box">
    <div class="flex-1">
        <a class="btn btn-ghost text-xl" href="/">EdgeSub</a>
    </div>
    <div class="flex-none">
        <ul class="menu menu-horizontal px-1">
            <li>
                <details>
                    <summary><Icon name="iconoir:compress-lines" /> Shorter</summary>
                    <ul class="bg-base-100 rounded-t-none p-2">
                        <li><a href="/shorter/create/">
                            <Icon class="inline" name="iconoir:add-circle" />
                            <span>Create</span>
                        </a></li>
                        <li><a href="/shorter/edit/">
                            <Icon class="inline" name="iconoir:edit" />
                            <span>Edit</span>
                        </a></li>
                        <li><a href="/shorter/destory/">
                            <Icon class="inline" name="iconoir:trash" />
                            <span>Delete</span>
                        </a></li>
                        <li><a href="/shorter/reset-token/">
                            <Icon class="inline" name="iconoir:refresh-double" />
                            <span>Reset Token</span>
                        </a></li>
                        <li><a href="/shorter/list/">
                            <Icon class="inline" name="iconoir:list" />
                            <span>List</span>
                        </a></li>
                        <li><a href="/shorter/admin/">
                            <Icon class="inline" name="iconoir:plus" />
                            <span>Admin</span>
                        </a></li>
                    </ul>
                </details>
            </li>

            <li>
                <a
                    title="GitHub Project"
                    href="https://github.com/kobe-koto/EdgeSub"
                    >
                    <Icon name="iconoir:github" /> GitHub
                </a>
            </li>
        </ul>
    </div>
</div>


================================================
FILE: src/components/backendIndicator.astro
================================================
---
import { Icon } from "astro-icon/components";
---

<div role="alert" class="alert bg-base-300 my-4">
    <Icon name="iconoir:info-circle" />
    <span>
        Current backend: 
        <code id="backend">
            <span class="skeleton h-6 w-28 inline-block align-[-0.45rem] ml-1"></span>
        </code>
    </span>
</div>

<script>
    addEventListener("DOMContentLoaded", () => {
        const backendIndicator = document.querySelector("#backend") as HTMLElement;
        backendIndicator.innerText = document.body.dataset.defaultBackend;
    });
</script>


================================================
FILE: src/components/data-input.astro
================================================
---
import type { DropdownItemPrototype } from "@components/k-dropdown.astro";
import KDropdown from "@components/k-dropdown.astro";

interface Props {
    slug: string;
    desc: string;
    detail?: string;
    optional?: boolean;
    type: "input" | "textarea" | "k-dropdown" | "toggle";
    DropdownDefault?: DropdownItemPrototype;
    DropdownItems?: DropdownItemPrototype[];
    SwitchDefault?: boolean;
}

const { 
    slug, 
    desc, 
    detail = "<暂未设定 detail 属性>", 
    type,
    optional = false,
    DropdownDefault, 
    DropdownItems, 
    SwitchDefault = false,
} = Astro.props;
---

<data-input id={slug} data-type={type}>

    <!-- <label class="fieldset-legend">{desc}</label> -->

    { type === "input" && (
        <fieldset class="fieldset">
            <legend class="fieldset-legend">
                {desc}
                { optional && <span class="label">可选</span> }
            </legend>
            <input type="text" class="input" placeholder={detail} />
        </fieldset>
    ) }

    { type === "textarea" && (
        <label class="fieldset-legend">
            {desc}
            { optional && <span class="label">可选</span> }
        </label>
        <textarea class="textarea h-24 w-full p-4" placeholder={detail} />
    ) }

    { type === "k-dropdown" && (
        <label class="fieldset-legend">{desc}</label>
        <KDropdown 
            Default={DropdownDefault} 
            Items={DropdownItems}
        />
    ) }

    { type === "toggle" && (
        <fieldset class="fieldset bg-base-100 border-base-300 rounded-box w-64 border p-4">
            <legend class="fieldset-legend">{desc}</legend>
            <label class="label">
                <input type="checkbox" checked={SwitchDefault ? "checked" : ""} class="toggle" />
                {detail}
            </label>
        </fieldset>
    ) }
    
</data-input>

<script src="@scripts/components/data-input"></script>
<!-- 
<style lang="scss">
    data-input {
        margin: 12px 0;
    }
</style> -->


================================================
FILE: src/components/index/SubURLGenerator.astro
================================================
---
import DataInput from "@components/data-input.astro";
import { Icon } from "astro-icon/components";
import type { DropdownItemPrototype } from "@components/k-dropdown.astro";
import { RuleProviders } from "@config/RuleProviders";
import { Endpoints } from "@config/AvalibleOptoutFormat.js"
---

<k-suburl-generator data-endpoints={JSON.stringify(Endpoints)} class="flex-contents">
    <h1 class="text-2xl font-bold">EdgeSub 订阅转换</h1>
    <div role="alert" class="alert bg-base-300 my-4">
        <Icon name="iconoir:info-circle" />
        <span>
            如果实例并非您自己的,请谨慎使用。<br />
            您输入的所有数据将<b>在请求订阅时进行远程处理</b>。<br />
            与 Shorter 功能相关的数据将<b>以非加密形式远程存储</b>,并且 Short Token 仅用于访问控制,而非加密密码。<br />
            <b>我们建议您按照 GitHub 上的文档进行自行部署。</b>
        </span>
    </div>
    <DataInput
        slug="SubURL"
        desc="订阅链接"
        detail="仅支持 http(s):// 和 short: 开头的订阅链接, 类似于 vless:// 开头的分享链接。以换行分割。"
        type="textarea"
    />
    <DataInput
        slug="Endpoint"
        desc="输出格式"
        type="k-dropdown"
        DropdownDefault={{ key: "Clash Meta (默认)", value: "/sub/clash-meta" }}
        DropdownItems={Endpoints as DropdownItemPrototype[]}
    />

    
    <DataInput
        slug="RuleProvider"
        desc="远程配置 (Rule Providers)"
        type="k-dropdown"
        DropdownDefault={{ key: "最小配置 (默认)", value: "__DEFAULT" }}
        DropdownItems={RuleProviders as DropdownItemPrototype[]}
    />


    <h2 class="text-lg font-bold">高级选项</h2>
    <div class="flex flex-row gap-2 flex-wrap">
        <DataInput
            slug="RuleProvidersProxy"
            desc="让 EdgeSub 缓存和代理 Rule Providers"
            detail="对于 Sing-Box 始终为 true"
            type="toggle"
            SwitchDefault={true}
        />
        <DataInput
            slug="isUDP"
            desc="开启 UDP"
            detail="在配置中开启原生 UDP 支持"
            type="toggle"
            SwitchDefault={true}
        />
        <DataInput
            slug="isSSUoT"
            desc="开启 SS UoT"
            detail="仅对 Shadowsocks 开启 UDP over TCP 支持. 不可与原生 UDP 同时开启."
            type="toggle"
            SwitchDefault={false}
        />
        <DataInput
            slug="isShowHost"
            desc="在节点名称后添加 Host 字段"
            detail="不知道的别开"
            type="toggle"
            SwitchDefault={false}
        />
        <DataInput
            slug="ForcedWS0RTT"
            desc="强制打开 WS 0-RTT"
            detail="强制打开 WebSocket 0-RTT 支持, 可能会导致部分节点无法连接."
            type="toggle"
            SwitchDefault={false}
        />
        <DataInput
            slug="Backend"
            desc="后端地址"
            detail="默认为当前站点"
            type="input"
            optional={true}
        />
        <DataInput
            slug="RuleProviderUserspec"
            desc="自订远程配置 (将覆写已选择的远程配置)"
            detail="仅不完善地支持 ini 格式"
            type="input"
            optional={true}
        />
        <DataInput
            slug="BaseConfig"
            desc="Custom Base Config URL"
            detail="JSON(C|5) for Sing-Box, YAML for Mihomo"
            type="textarea"
            optional={true}
        />
    </div>



    <DataInput
        slug="ExcludeRegExpPattern"
        desc="Custom RegExp Pattern to Exclude"
        detail="Any outbound name matched with this RegExp Pattern will be ignored. This pattern is case-sensitive, and global mode only"
        type="textarea"
        optional={true}
    />

    <DataInput
        slug="HTTPHeaders"
        desc="HTTP Headers"
        detail="请求远端订阅位址时使用的 HTTP Headers, 请务必使用 JSON 格式书写."
        type="textarea"
    />
    
    <div class="divider"></div>

    <div class="mockup-code w-full">
        <pre data-prefix="~"><code>https://OpenWrt.lan/luci/123" OR ""==" </code></pre>
    </div>

    <div class="flex gap-4">
        <button class="btn" id="generate"><Icon name="iconoir:refresh-circle" />  Generate</button>
        <button class="btn" id="copy"><Icon name="iconoir:copy" />  Copy</button>
    </div>

</k-suburl-generator>

<script src="@scripts/components/k-suburl-generator.ts"></script>

<style lang="scss">
    .botton-con {
        display: flex;
        gap: 8px;
    }
</style>

================================================
FILE: src/components/k-dropdown.astro
================================================
---
import { Icon } from "astro-icon/components";

export type DropdownItemPrototype = { key: string; value: string };

interface Props {
    Items: DropdownItemPrototype[];
    Default?: DropdownItemPrototype;
}
const {
    Items,
    Default = {
        key: "还未选择",
        value: "__NULL__",
    },
} = Astro.props;
---

<k-dropdown class="dropdown" data-selected-value={Default.value}>
    <div tabindex="0" role="button" class="btn m-1">
        <span>{Default.key}</span>
        <Icon name="iconoir:arrow-down-tag" />
    </div>

    <ul
        tabindex="0"
        class="dropdown-content menu bg-base-100 rounded-box z-1 w-52 p-2 shadow-sm"
    >
        {
            Items.map((i) => {
                return (
                    <li>
                        <a data-value={i.value}>{i.key}</a>
                    </li>
                );
            })
        }
    </ul>
</k-dropdown>

<script src="@scripts/components/k-dropdown"></script>


================================================
FILE: src/components/layouts/SEOComponent.astro
================================================
---
import { SEO } from "astro-seo";

interface Props {
    Title?: string;
    Desc?: string;
    noindex?: boolean;
}
const { 
    Title = "EdgeSub",
    Desc = "A proxy toolchain config converter, KISS and privacy on.",
    noindex = false 
} = Astro.props;
---

<SEO
    title={Title}
    noindex={noindex}
    nofollow={noindex}
    description={Desc}
    charset="UTF-8"
    extend={{
        link: [
            { rel: "sitemap", href: "/sitemap-index.xml" },
            { rel: "icon", type: "image/png", href: "/favicon.svg" },
        ],
        meta: [
            { name: "viewport", content: "width=device-width" },
            { name: "author", content: "EdgeSub Project" },
        ]
    }}
    openGraph={{
        basic: {
            type: "website",
            title: Title,
            image: "/favicon.svg"
        },
        optional: {
            description: Desc,
            siteName: Title,
        }
    }}
/>



================================================
FILE: src/components/shorter/k-shorter.astro
================================================
---
import DataInput from "@components/data-input.astro";
import { Icon } from "astro-icon/components";
---

<k-shorter class="flex-contents">
    <DataInput
        slug="SubURL"
        desc="订阅链接"
        detail="仅支持 http(s):// 和 short: 开头的订阅链接, 类似于 vless:// 开头的分享链接。以换行分割。"
        type="textarea"
    />

    <div class="flex flex-row gap-2 flex-wrap">
        <DataInput
            slug="short-slug"
            desc="Short ID"
            detail="默认随机"
            type="input"
        />
        <DataInput
            slug="short-token"
            desc="Short Token"
            detail="默认随机"
            type="input"
        />
    </div>

    <div class="mockup-code w-full my-2">
        <pre data-prefix="~"><code>请先提交</code></pre>
    </div>

    <p>可将以上内容作为本程式内专用的 订阅链接</p>

    <div class="flex gap-4">
        <button class="btn" id="shorter">
            <label class="swap swap-rotate">
                <div class="swap-on">
                    <!-- loading -->
                    <span class="loading loading-spinner loading-md"></span>
                </div>
                <div class="swap-off">
                    <!-- not loading -->
                    <Icon name="iconoir:send" class="text-xl inline" />
                </div>
            </label>
            <span>Submit</span>
        </button>

        <button class="btn" id="copy">
            <Icon name="iconoir:copy" />
            <span>Copy</span>
        </button>
    </div>
</k-shorter>

<script src="@scripts/components/shorter/k-shorter"></script>


================================================
FILE: src/components/shorter/short-destroyer.astro
================================================
---
import DataInput from "@components/data-input.astro";
import { Icon } from "astro-icon/components";
---

<short-destroyer class="flex-contents">
    <DataInput slug="slug" desc="Short ID" detail="Short ID" type="input" />
    <DataInput slug="token" desc="token" detail="Short token" type="input" />

    <div class="mockup-code w-full my-2">
        <pre data-prefix="~"><code>请先提交</code></pre>
    </div>

    <button class="btn" id="submit">
        <label class="swap swap-rotate">
            <div class="swap-on">
                <!-- loading -->
                <span class="loading loading-spinner loading-md"></span>
            </div>
            <div class="swap-off">
                <!-- not loading -->
                <Icon name="iconoir:send" class="text-xl inline" />
            </div>
        </label>
        <span>Submit</span>
    </button>
</short-destroyer>

<script src="@scripts/components/shorter/short-destroyer.ts"></script>


================================================
FILE: src/components/shorter/short-editor.astro
================================================
---
import DataInput from "@components/data-input.astro";
import { Icon } from "astro-icon/components";
---

<short-editor class="flex-contents">
    <DataInput
        slug="short-id"
        desc="Short ID"
        detail="Short ID"
        type="input"
    />
    <button class="btn" id="editor-fetch">
        <label class="swap swap-rotate">
            <div class="swap-on">
                <!-- loading -->
                <span class="loading loading-spinner loading-md"></span>
            </div>
            <div class="swap-off">
                <!-- not loading -->
                <Icon name="iconoir:send" class="text-xl inline" />
            </div>
        </label>
        <span>Fetch</span>
    </button>
    <DataInput
        slug="short-data"
        desc="订阅链接"
        detail="请先拉取数据。仅支持 http(s):// 或 short: 开头的订阅链接、类似于 vless:// 开头的分享链接。以换行分割。"
        type="textarea"
    />
    <DataInput
        slug="short-password"
        desc="Short password"
        detail="Short password"
        type="input"
    />

    <div class="mockup-code w-full my-2">
        <pre data-prefix="~"><code>请先提交</code></pre>
    </div>
    <p>可将以上内容作为本程式内专用的 订阅链接</p>

    <button class="btn" id="editor-submit">
        <label class="swap swap-rotate">
            <div class="swap-on">
                <!-- loading -->
                <span class="loading loading-spinner loading-md"></span>
            </div>
            <div class="swap-off">
                <!-- not loading -->
                <Icon name="iconoir:send" class="text-xl inline" />
            </div>
        </label>
        <span>Submit</span>
    </button>

</short-editor>

<script src="@scripts/components/shorter/short-editor.ts"></script>


================================================
FILE: src/components/shorter/short-token-reset.astro
================================================
---
import DataInput from "@components/data-input.astro";
import { Icon } from "astro-icon/components";
---

<short-token-reset class="flex-contents">
    <DataInput
        slug="slug"
        desc="Short ID"
        detail="Short ID"
        type="input"
    />
    <DataInput
        slug="old-token"
        desc="Old Token"
        detail="OLD Short token"
        type="input"
    />
    <DataInput
        slug="new-token"
        desc="New Token"
        detail="NEW Short token"
        type="input"
    />
    
    <div class="mockup-code w-full my-2">
        <pre data-prefix="~"><code>请先提交</code></pre>
    </div>

    <button class="btn" id="submit">
        <label class="swap swap-rotate">
            <div class="swap-on">
                <!-- loading -->
                <span class="loading loading-spinner loading-md"></span>
            </div>
            <div class="swap-off">
                <!-- not loading -->
                <Icon name="iconoir:send" class="text-xl inline" />
            </div>
        </label>
        <span>Submit</span>
    </button>

</short-token-reset>

<script src="@scripts/components/shorter/short-token-reset.ts"></script>


================================================
FILE: src/components/shorter/shorter-list.astro
================================================
---
import DataInput from "@components/data-input.astro";
import { Icon } from "astro-icon/components";
---

<shorter-list class="flex-contents">
    <DataInput
        slug="password"
        desc="Admin password"
        detail="Admin password"
        type="input"
    />

    <button class="btn" id="list-submit">
        <label class="swap swap-rotate">
            <div class="swap-on">
                <!-- loading -->
                <span class="loading loading-spinner loading-md"></span>
            </div>
            <div class="swap-off">
                <!-- not loading -->
                <Icon name="iconoir:send-diagonal" class="text-xl inline" />
            </div>
        </label>
        <span>Fetch</span>
    </button>

    <div id="list-items" class="flex flex-row flex-wrap gap-4 justify-center">
        <list-item class="hidden">
            <div class="card bg-neutral text-neutral-content w-96">
                <div class="card-body items-center text-center">
                    <p>
                        <Icon class="inline" name="iconoir:info-circle" /> Short
                        ID: <code class="item-id">cry_me_a_r1ver</code>
                    </p>
                    <p>
                        <Icon class="inline" name="iconoir:edit" /> Last modified:
                        <span class="item-date">11011111101010010</span>
                    </p>

                    <div class="card-actions justify-end">
                        <button class="btn item-edit">
                            <Icon name="iconoir:edit" /> Edit
                        </button>
                        <button class="btn item-copy">
                            <Icon name="iconoir:copy" /> Copy ID
                        </button>
                    </div>
                </div>
            </div>
        </list-item>
    </div>
</shorter-list>

<script src="@scripts/components/shorter/shorter-list"></script>

================================================
FILE: src/components/shorter/shorter-password.astro
================================================
---
import DataInput from "@components/data-input.astro";
import { Icon } from "astro-icon/components";
---

<shorter-password class="flex-contents">
    <DataInput
        slug="old-password"
        desc="Old admin password"
        detail="Old admin password (leave it empty if 'Password undefined')"
        type="input"
    />
    <DataInput
        slug="new-password"
        desc="New admin password"
        detail="New admin password"
        type="input"
    />

    <div class="mockup-code w-full my-2">
        <pre data-prefix="~"><code>请先提交</code></pre>
    </div>

    <button class="btn" id="password-submit">
        <label class="swap swap-rotate">
            <div class="swap-on">
                <!-- loading -->
                <span class="loading loading-spinner loading-md"></span>
            </div>
            <div class="swap-off">
                <!-- not loading -->
                <Icon name="iconoir:send" class="text-xl inline" />
            </div>
        </label>
        <span>Submit</span>
    </button>

</shorter-password>

<script src="@scripts/components/shorter/shorter-password.ts"></script>


================================================
FILE: src/config/AvalibleOptoutFormat.ts
================================================
import { readdirSync } from "node:fs";
export type EndpointExtendConfigPrototype = "RuleProvider" | "RuleProvidersProxy" | "BaseConfig" | "isUDP" | "isSSUoT" | "RuleProviderUserspec" | "ForcedWS0RTT"

export type EndpointPrototype = {
    key: string;
    value: string;
    ExtendConfig?: EndpointExtendConfigPrototype[]
}

const AvalibleEndpoints: EndpointPrototype[] = [
    {
        key: "Sing Box",
        value: "/sub/sing-box",
        ExtendConfig: ["RuleProvider", "RuleProviderUserspec", "RuleProvidersProxy", "BaseConfig", "isUDP", "isSSUoT", "ForcedWS0RTT"]
    },
    {
        key: "Clash Meta",
        value: "/sub/clash-meta",
        ExtendConfig: ["RuleProvider", "RuleProviderUserspec", "RuleProvidersProxy", "BaseConfig", "isUDP", "isSSUoT", "ForcedWS0RTT"]
    },
    {
        key: "Base 64",
        value: "/sub/base64"
    },
    {
        key: "Share Link 集合",
        value: "/sub/share-link"
    }
]

const AvalibleEndpointsPath = AvalibleEndpoints.map(i => i.value);
const TestingEndpointsPath = readdirSync("./functions/sub/").map(i => `/sub/${i.replace(/\.js$/, "")}`).filter(i => !AvalibleEndpointsPath.includes(i));
let TestingEndpoints: EndpointPrototype[] = [];
for (let i of TestingEndpointsPath) {
    TestingEndpoints.push({
        key: `${i} (Experimental)`,
        value: i
    })
}

export const Endpoints: EndpointPrototype[] = [...AvalibleEndpoints, ...TestingEndpoints]


================================================
FILE: src/config/RuleProviders.ts
================================================
type RuleProvider = {
    key: string;
    value: string | URL;
}

export const RuleProviders: RuleProvider[] = [
    {
        key: "最小配置", 
        value: "__DEFAULT"
    },
    {
        key: "ACL_默认版",
        value: "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online.ini"
    },
    {
        key: "ACL_无测速版",
        value: "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_NoAuto.ini"
    },
    {
        key: "ACL_去广告版",
        value: "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_AdblockPlus.ini"
    },
    {
        key: "ACL_多国家版",
        value: "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_MultiCountry.ini"
    },
    {
        key: "ACL_无Reject版",
        value: "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_NoReject.ini"
    },
    {
        key: "ACL_无测速精简版",
        value: "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_NoAuto.ini"
    },
    {
        key: "ACL_全分组版",
        value: "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full.ini"
    },
    {
        key: "ACL_全分组谷歌版",
        value: "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full_Google.ini"
    },
    {
        key: "ACL_全分组多模式版",
        value: "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full_MultiMode.ini"
    },
    {
        key: "ACL_全分组奈飞版",
        value: "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Full_Netflix.ini"
    },
    {
        key: "ACL_精简版",
        value: "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini.ini"
    },
    {
        key: "ACL_去广告精简版",
        value: "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_AdblockPlus.ini"
    },
    {
        key: "ACL_Fallback精简版",
        value: "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_Fallback.ini"
    },
    {
        key: "ACL_多国家精简版",
        value: "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_MultiCountry.ini"
    },
    {
        key: "ACL_多模式精简版",
        value: "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_MultiMode.ini"
    }
];


================================================
FILE: src/env.d.ts
================================================
/// <reference path="../.astro/types.d.ts" />
/// <reference types="astro/client" />

================================================
FILE: src/layouts/base.astro
================================================
---
import "@styles/import.css";
import SEOComponent from "@components/layouts/SEOComponent.astro";
interface Props {
	noindex?: boolean;
}
const { noindex = false } = Astro.props;
//import "@styles/main.scss";
//import "@styles/index.scss";

import NavBar from "@components/NavBar.astro";
---

<html lang="en" data-theme="Light Mint" class="bg-base-200">
	<head>
		<SEOComponent noindex={noindex} />
	</head>
	<body>
		<NavBar />

		<div class="my-8 mx-auto max-w-5xl px-6">
			<div class="main-card">
				<div class="contents">
					<slot />
				</div>
			</div>
		</div>
	</body>
</html>


<script>
    // update the backend
    import { getDefaultBackend } from "@scripts/utils/getDefaultBackend";
    document.body.dataset.defaultBackend = getDefaultBackend();
</script>


================================================
FILE: src/pages/index.astro
================================================
---
import Base from "@layouts/base.astro";

import SubURLGenerator from "@components/index/SubURLGenerator.astro";
//import KShorter from "@components/index/k-shorter.astro";
---
<Base>
    <SubURLGenerator />
</Base>

================================================
FILE: src/pages/shorter/admin.astro
================================================
---
import Base from "@layouts/base.astro";
import { Icon } from "astro-icon/components";
import BackendIndicator from "@components/backendIndicator.astro";

import ShorterPassword from "@components/shorter/shorter-password.astro";
---

<Base>
    <h1 class="text-2xl font-bold">Administration</h1>
    <p>
        <Icon class="inline" name="iconoir:info-circle" /> Please ensure that you
        have binded a KV correctly to the project.
    </p>

    <BackendIndicator />

    <div role="alert" class="alert my-4 alert-warning">
        <Icon class="inline" name="iconoir:info-circle" />
        <span
            >Warning: The following content is intended only for instance
            owners.</span
        >
    </div>

    <div data-role="passwordStatus" data-status="checking">
        <h2>Admin password status</h2>

        <div role="alert" class="alert my-4 alert-success" data-status="true">
            <Icon class="inline" name="iconoir:check-circle" />
            <span>Admin password defined</span>
        </div>

        <div role="alert" class="alert my-4 alert-error" data-status="false">
            <Icon class="inline" name="iconoir:warning-triangle" />
            <span>Admin password undefined</span>
        </div>

        <div role="alert" class="alert my-4 alert-success" data-status="fail">
            <Icon class="inline" name="iconoir:xmark-circle" />
            <span>Check failed, open console to get more information.</span>
        </div>

        <div
            role="alert"
            class="alert my-4 alert-success"
            data-status="checking"
        >
            <span class="loading loading-spinner loading-md"></span>
            <span>Checking....</span>
        </div>
    </div>
    <div role="alert" class="alert my-4 bg-base-300" data-status="checking">
        <Icon name="iconoir:question-mark-circle" />
        <span
            >If you forget your admin password, you have to delete the key
            "admin-password" in the KV database and set a new one.</span
        >
    </div>
    <h2 class="text-xl font-bold">Set / Change Admin Password</h2>
    <ShorterPassword />
</Base>

<style lang="scss">
    div[data-role="passwordStatus"] {
        > * {
            display: none;
        }
        &[data-status="true"] > [data-status="true"] {
            display: block;
        }
        &[data-status="false"] > [data-status="false"] {
            display: block;
        }
        &[data-status="checking"] > [data-status="checking"] {
            display: block;
        }
        &[data-status="fail"] > [data-status="fail"] {
            display: block;
        }
    }
</style>

<script>
    addEventListener("DOMContentLoaded", () => {
        // check for the admin password status
        const adminPasswordStatus = document.querySelector(
            '[data-role="passwordStatus"]',
        ) as HTMLElement;
        fetch(`${document.body.dataset.defaultBackend}/short/admin-password/status`)
            .then((res) => res.json())
            .then((res) => {
                adminPasswordStatus.dataset.status =
                    res.isPasswordSet.toString();
            })
            .catch(() => {
                adminPasswordStatus.dataset.status = "fail";
            });
    });
</script>


================================================
FILE: src/pages/shorter/create.astro
================================================
---
import Base from "@layouts/base.astro";
import BackendIndicator from "@components/backendIndicator.astro";

import KShorter from "@components/shorter/k-shorter.astro";
---
<Base>
    <h1 class="text-2xl font-bold">Create a new Short</h1>

    <BackendIndicator />

    <KShorter />
</Base>



================================================
FILE: src/pages/shorter/destory.astro
================================================
---
import Base from "@layouts/base.astro";
import BackendIndicator from "@components/backendIndicator.astro";

import ShortDestroyer from "@components/shorter/short-destroyer.astro";
---
<Base>
    <h1 class="text-2xl font-bold">Destory a existing Short</h1>

    <BackendIndicator />

    <ShortDestroyer />
</Base>



================================================
FILE: src/pages/shorter/edit.astro
================================================
---
import Base from "@layouts/base.astro";
import BackendIndicator from "@components/backendIndicator.astro";

import ShortEditor from "@components/shorter/short-editor.astro"
---
<Base>
    <h1 class="text-2xl font-bold">Short Editior</h1>
    <BackendIndicator />

    <ShortEditor />
</Base>


================================================
FILE: src/pages/shorter/list.astro
================================================
---
import Base from "@layouts/base.astro";
import BackendIndicator from "@components/backendIndicator.astro";

import ShorterList from "@components/shorter/shorter-list.astro"
---
<Base>
    <h1 class="text-2xl font-bold">List all the Shorts</h1>
    
    <BackendIndicator />

    <ShorterList />
</Base>


================================================
FILE: src/pages/shorter/reset-token.astro
================================================
---
import Base from "@layouts/base.astro";
import BackendIndicator from "@components/backendIndicator.astro";

import ShortTokenReset from "@components/shorter/short-token-reset.astro";
---
<Base>
    <h1 class="text-2xl font-bold">Reset Access Token for a existing Short</h1>

    <BackendIndicator />

    <ShortTokenReset />
</Base>



================================================
FILE: src/scripts/components/data-input.ts
================================================
import type { Dropdown } from "@scripts/components/k-dropdown";

export class DataInput extends HTMLElement {
    type = this.dataset.type;
    
    constructor () {
        super ();
    }

    get () { // boolean if toggle, string if any otherwise
        if (this.type === "textarea") {
            return this.querySelector("textarea").value.trim();
        } else if (this.type === "input") {
            return this.querySelector("input").value.trim();
        } else if (this.type === "k-dropdown") {
            const DropdownElement = this.querySelector("k-dropdown") as Dropdown;
            return DropdownElement.dataset.selectedValue;
        } else if (this.type === "toggle") {
            const ToggleElement = this.querySelector("input.toggle") as HTMLInputElement;
            return ToggleElement.checked;
        }
    }
    
    set (value: string) {
        if (this.type === "textarea") {
            this.querySelector("textarea").value = value.trim();
        } else if (this.type === "input") {
            this.querySelector("input").value = value.trim();
        } else if (this.type === "k-dropdown") {
            const DropdownElement = this.querySelector("k-dropdown") as Dropdown;
            DropdownElement.select(value);
        } else if (this.type === "toggle") {
            const SwitchElement = this.querySelector("toggle") as HTMLInputElement;
            SwitchElement.checked = value == "true"; // "true" or true or whatever.... it should be boolean
        }
    }

    setDetail(value: string) {
        if (this.type === "textarea") {
            this.querySelector("textarea").placeholder = value;
            return true;
        } else if (this.type === "input") {
            this.querySelector("input").placeholder = value;
            return true;
        }
        return false;
    }

    getDetail() {
        if (this.type === "textarea") {
            return this.querySelector("textarea").placeholder;
        } else if (this.type === "input") {
            return this.querySelector("input").placeholder;
        }
    }
}


function maybeWaitFor(tag) {
    return customElements.get(tag) || document.querySelector(tag)
      ? customElements.whenDefined(tag)
      : Promise.resolve(); // No need to wait
  }
  
Promise.all([
    maybeWaitFor("toggle"),
    maybeWaitFor("k-dropdown")
]).then(() => {
    console.log("[data-input] dependency elements toggle and k-dropdown registered, initializing");
    customElements.define("data-input", DataInput);
    console.info("[data-input] registered")
});

// Promise.all([
//     customElements.whenDefined("toggle"),
//     customElements.whenDefined("k-dropdown")
// ]).then(() => {
//     console.log("[data-input] dependency toggle and k-dropdown registration detected, initializing");
//     customElements.define("data-input", DataInput);
//     console.info("[data-input] registered")
// });


================================================
FILE: src/scripts/components/k-dropdown.ts
================================================
export class Dropdown extends HTMLElement {
    constructor () {
        super();
        
        this.initializeElements();
        this.setupEventListeners();
    }

    private initializeElements() {
        this.Elements = {
            DropdownBotton: this.querySelector("div.btn") as HTMLElement,
            DropdownBottonText: this.querySelector("div.btn > span") as HTMLElement,
            Items: this.querySelectorAll(".dropdown-content > li > a") as NodeListOf<HTMLButtonElement>
        };
    }

    private setupEventListeners() {
        this.Elements.Items.forEach(item => {
            item.addEventListener("click", (event) => {
                const targetElement = event.target as HTMLElement;
                this.select(targetElement.dataset.value);
            });
        });
    }

    public select(value: string) {
        if (!value) {
            console.error("[k-dropdown.select] value is required")
            return false;
        };

        this.dataset.selectedValue = value;
        
        // mark the selected
        this.Elements.Items.forEach(item => {
            if (item.dataset.value === value) {
                item.classList.add("menu-active")
                this.Elements.DropdownBottonText.innerText = item.innerText;
            } else {
                // cancel non-targets out
                item.classList.remove("menu-active")
            }
        });

        // dispatch custom event to notify
        this.dispatchEvent(new CustomEvent("dropdown-select", {
            bubbles: true,
            composed: true,
            detail: {
                value,
            }
        }));
    }

    Elements: {
        DropdownBotton: HTMLElement;
        DropdownBottonText: HTMLElement;
        Items: NodeListOf<HTMLButtonElement>;
    }
}

customElements.define("k-dropdown", Dropdown);
console.info("[k-dropdown] registered")

================================================
FILE: src/scripts/components/k-suburl-generator.ts
================================================
import type { DataInput } from "@scripts/components/data-input";
import type { EndpointExtendConfigPrototype, EndpointPrototype } from "@config/AvalibleOptoutFormat";
import { getDefaultBackend } from "@scripts/utils/getDefaultBackend";
import { copyToClipboard } from "@scripts/utils/copy";
import filterObject from "@scripts/utils/filterObject";

class SubURLGenerator extends HTMLElement {
    Endpoints: EndpointPrototype[] = JSON.parse(this.dataset.endpoints);
    defaultBackend = getDefaultBackend();

    constructor () {
        super()
        
        this.setupEventListeners();

        customElements.whenDefined("data-input").then(() => {
            this.Elements.Config.Basic.Backend.setDetail(`${this.Elements.Config.Basic.Backend.getDetail()} (${this.defaultBackend})`);
            console.info("[k-sub-url-generator] data-input registration detected, default backend modified")
        })
    }

    private setupEventListeners () {
        this.Elements.Action.Generate.addEventListener("click", () => {this.CheckAndGenerate()});
        this.Elements.Action.Copy.addEventListener("click", () => {
            copyToClipboard(this.Elements.Action.MsgBlock.innerText)
                .then(() => {
                    alert("已将连接复制到剪贴板");
                })
                .catch((err) => {
                    console.error("[k-suburl-generator] copy failed", err);
                    alert("复制失败, 请检查浏览器权限设置, 版本, 或尝试手动复制.");
                });
        });
        this.Elements.Config.Basic.Endpoint.addEventListener("dropdown-select", (event: CustomEvent) => {
            const SelectedEndpointPath: string = event.detail.selectedValue;
            let Endpoint: EndpointPrototype = this.GetEndpoint(SelectedEndpointPath);
            let NeededExtendConfig = Endpoint.ExtendConfig || [];

            for (let i in this.Elements.Config.Extended) {
                if (NeededExtendConfig.includes(i as EndpointExtendConfigPrototype)) {
                    this.Elements.Config.Extended[i].style.removeProperty("display")
                } else {
                    this.Elements.Config.Extended[i].style.setProperty("display", "none")
                }
            }
        });
    }

    private Elements = {
        Action: {
            Generate: this.querySelector("button#generate") as HTMLButtonElement,
            Copy: this.querySelector("button#copy") as HTMLButtonElement,
            MsgBlock: this.querySelector("code") as HTMLElement,
        },
        Config: {
            Basic: {
                SubURL: this.querySelector("data-input#SubURL") as DataInput,
                Backend: this.querySelector("data-input#Backend") as DataInput,
                Endpoint: this.querySelector("data-input#Endpoint") as DataInput,
            },
            UniversalExtended: {
                isShowHost: this.querySelector("data-input#isShowHost") as DataInput,
                HTTPHeaders: this.querySelector("data-input#HTTPHeaders") as DataInput,
                ExcludeRegExpPattern: this.querySelector("data-input#ExcludeRegExpPattern") as DataInput,
            },
            Extended: {
                RuleProviderUserspec: this.querySelector("data-input#RuleProviderUserspec") as DataInput,
                RuleProvider: this.querySelector("data-input#RuleProvider") as DataInput,
                RuleProvidersProxy: this.querySelector("data-input#RuleProvidersProxy") as DataInput,
                BaseConfig: this.querySelector("data-input#BaseConfig") as DataInput,
                isUDP: this.querySelector("data-input#isUDP") as DataInput,
                isSSUoT: this.querySelector("data-input#isSSUoT") as DataInput,
                ForcedWS0RTT: this.querySelector("data-input#ForcedWS0RTT") as DataInput,
            }
        }
    }

    private GetEndpoint (EndpointPath: string = String(this.Elements.Config.Basic.Endpoint.get())) {
        for (let i of this.Endpoints) {
            if (i.value === EndpointPath) {
                return i as EndpointPrototype;
            }
        }
        throw `no targeted endpoint found, expected value ${EndpointPath}`
    }

    private getConfig () {
        const Backend = new URL(String(this.Elements.Config.Basic.Backend.get() || this.defaultBackend));
        return {
            Basic: {
                SubURL: this.Elements.Config.Basic.SubURL.get() as string,
                Backend: Backend.toString() as string,
                Endpoint: this.Elements.Config.Basic.Endpoint.get() as string,
            },
            UniversalExtended: {
                isShowHost: this.Elements.Config.UniversalExtended.isShowHost.get() as boolean,
                ExcludeRegExpPattern: this.Elements.Config.UniversalExtended.ExcludeRegExpPattern.get() as string,
                HTTPHeaders: JSON.stringify(JSON.parse(String(this.Elements.Config.UniversalExtended.HTTPHeaders.get()) || "{}")) as string,
            },
            Extended: {
                RuleProvider: (this.Elements.Config.Extended.RuleProviderUserspec.get() || this.Elements.Config.Extended.RuleProvider.get()) as string,
                RuleProvidersProxy: (this.Elements.Config.Extended.RuleProvidersProxy.get() && this.Elements.Config.Basic.Backend.get() || this.defaultBackend) as string,
                BaseConfig: this.Elements.Config.Extended.BaseConfig.get() || "__DEFAULT" as String,
                isUDP: this.Elements.Config.Extended.isUDP.get() as boolean,
                isSSUoT: this.Elements.Config.Extended.isSSUoT.get() as boolean,
                ForcedWS0RTT: this.Elements.Config.Extended.ForcedWS0RTT.get() as boolean,
            }
        }
    }



    CheckAndGenerate () {
        // Get config
        const Config = this.getConfig();
        
        // non-empty check for basic configs 
        let ErrorOccurred = false;
        for (let [key, value] of Object.entries(Config.Basic)) {
            if (typeof value === "string" && value.length === 0) {
                alert(`${key} can't be empty`);
                ErrorOccurred = true;
                continue;
            }
        }
        if (ErrorOccurred === true) {
            return;
        }

        // now we do some real works! con---gra---tu---la--tion---s---!

        // grab the backend
        let URLObj = new URL(Config.Basic.Backend);
        URLObj.pathname = Config.Basic.Endpoint;
        URLObj.search = "";
        URLObj.hash = "";

        // append inputed data (subdata)
        URLObj.searchParams.append("url", Config.Basic.SubURL)

        // append extended config
        // - currently we do this mapping on client side, 
        //   but in the future we may want to do this on server side, 
        //   just to keep the URL clean and uniform.
        let Mapping = {
            "RuleProvider": "remote_config",
            "RuleProvidersProxy": "rule_providers_proxy",
            "isUDP": "udp",
            "isS
Download .txt
gitextract_a6ww6u21/

├── .gitattributes
├── .gitignore
├── LICENSE
├── astro.config.ts
├── bun.lockb
├── functions/
│   ├── _middleware.js
│   ├── internal/
│   │   ├── Converter/
│   │   │   ├── getClashMetaConfig.js
│   │   │   └── getSingBoxConfig.ts
│   │   ├── Dumpers/
│   │   │   ├── clash-meta.ts
│   │   │   ├── share-link.js
│   │   │   └── sing-box.js
│   │   ├── Parsers/
│   │   │   ├── clash-meta.js
│   │   │   ├── share-link.js
│   │   │   └── sing-box.js
│   │   ├── RuleProviderReader/
│   │   │   ├── Readers/
│   │   │   │   └── ini.js
│   │   │   └── main.js
│   │   ├── configs.ts
│   │   ├── data/
│   │   │   ├── rule/
│   │   │   │   ├── MetaToSingLogicalRule.ts
│   │   │   │   └── MetaToSingMapping.ts
│   │   │   └── ruleset/
│   │   │       └── transformGeoRef.ts
│   │   ├── getParsedSubData.ts
│   │   ├── types/
│   │   │   └── ClashMetaConfig.ts
│   │   └── utils/
│   │       ├── TrulyAssign.js
│   │       ├── fetchCached.ts
│   │       ├── parseContentDisposition.ts
│   │       └── removeUndefinedFields.ts
│   ├── ruleset/
│   │   ├── preprocessor/
│   │   │   └── sing-box.ts
│   │   └── proxy.ts
│   ├── short/
│   │   ├── admin-password/
│   │   │   ├── set.ts
│   │   │   └── status.ts
│   │   ├── delete/
│   │   │   └── [id].ts
│   │   ├── get/
│   │   │   └── [id].ts
│   │   ├── list.ts
│   │   ├── put.ts
│   │   ├── token-reset/
│   │   │   └── [id].ts
│   │   └── utils/
│   │       └── defaultHeader.ts
│   └── sub/
│       ├── base64.js
│       ├── clash-meta.js
│       ├── debug.js
│       ├── share-link.js
│       └── sing-box.js
├── package.json
├── public/
│   ├── basic-config/
│   │   ├── mihomo.yaml
│   │   └── sing-box.jsonc
│   └── minimal_remote_rules.ini
├── readme.md
├── src/
│   ├── components/
│   │   ├── NavBar.astro
│   │   ├── backendIndicator.astro
│   │   ├── data-input.astro
│   │   ├── index/
│   │   │   └── SubURLGenerator.astro
│   │   ├── k-dropdown.astro
│   │   ├── layouts/
│   │   │   └── SEOComponent.astro
│   │   └── shorter/
│   │       ├── k-shorter.astro
│   │       ├── short-destroyer.astro
│   │       ├── short-editor.astro
│   │       ├── short-token-reset.astro
│   │       ├── shorter-list.astro
│   │       └── shorter-password.astro
│   ├── config/
│   │   ├── AvalibleOptoutFormat.ts
│   │   └── RuleProviders.ts
│   ├── env.d.ts
│   ├── layouts/
│   │   └── base.astro
│   ├── pages/
│   │   ├── index.astro
│   │   └── shorter/
│   │       ├── admin.astro
│   │       ├── create.astro
│   │       ├── destory.astro
│   │       ├── edit.astro
│   │       ├── list.astro
│   │       └── reset-token.astro
│   ├── scripts/
│   │   ├── components/
│   │   │   ├── data-input.ts
│   │   │   ├── k-dropdown.ts
│   │   │   ├── k-suburl-generator.ts
│   │   │   └── shorter/
│   │   │       ├── k-shorter.ts
│   │   │       ├── short-destroyer.ts
│   │   │       ├── short-editor.ts
│   │   │       ├── short-token-reset.ts
│   │   │       ├── shorter-list.ts
│   │   │       └── shorter-password.ts
│   │   └── utils/
│   │       ├── copy.ts
│   │       ├── filterObject.ts
│   │       └── getDefaultBackend.ts
│   └── styles/
│       ├── app.scss
│       ├── import.css
│       ├── index.scss
│       └── main.scss
├── tsconfig.json
└── types/
    └── worker-configuration.d.ts
Download .txt
SYMBOL INDEX (642 symbols across 48 files)

FILE: functions/_middleware.js
  function RequestInfo (line 1) | async function RequestInfo (context) {
  function PerformanceCounting (line 9) | async function PerformanceCounting (context) {

FILE: functions/internal/Converter/getClashMetaConfig.js
  function getClashMetaConfig (line 19) | async function getClashMetaConfig (

FILE: functions/internal/Converter/getSingBoxConfig.ts
  function getSingBoxConfig (line 22) | async function getSingBoxConfig (

FILE: functions/internal/Dumpers/clash-meta.ts
  class Dumper (line 3) | class Dumper {
    method constructor (line 10) | constructor (
    method __validate (line 26) | __validate (ProxyObject) {
    method http (line 34) | http (HTTP) {
    method socks5 (line 45) | socks5 (SOCKS5) {
    method hysteria (line 58) | hysteria (hyObject) {
    method hysteria2 (line 75) | hysteria2 (hy2Object) {
    method tuic (line 93) | tuic (TUIC) {
    method vless (line 113) | vless (VLESS) {
    method vmess (line 140) | vmess (VMESS) {
    method vmess__shadowsocks_type (line 179) | vmess__shadowsocks_type (VMESS) {
    method ss (line 210) | ss (SS) {
    method trojan (line 224) | trojan (TROJAN) {
  function __genRealityConfig (line 252) | function __genRealityConfig (Obj) : RealityConfig | undefined {
  function __genTransportWS (line 260) | function __genTransportWS (Obj) : TransportWS | undefined {
  function __genTransportGRPC (line 283) | function __genTransportGRPC (Obj) : TransportGRPC | undefined {
  function __genTransportHTTP (line 290) | function __genTransportHTTP (Obj) : TransportHTTP | undefined {
  function __genTransportH2 (line 299) | function __genTransportH2 (Obj) : TransportH2 | undefined {

FILE: functions/internal/Dumpers/share-link.js
  class ShareLinkDumper (line 1) | class ShareLinkDumper {
    method constructor (line 2) | constructor () {
    method __validate (line 6) | __validate (ProxyObject) {
    method http (line 14) | http (HTTP) {
    method socks5 (line 17) | socks5 (SOCKS5) {
    method hysteria (line 21) | hysteria (Obj) {
    method hysteria2 (line 24) | hysteria2 (Obj) {
    method tuic (line 29) | tuic (Obj) {
    method vless (line 33) | vless (Obj) {
    method vmess (line 36) | vmess (Obj) {
    method vmess__shadowsocks_type (line 47) | vmess__shadowsocks_type (Obj) {
    method ss (line 65) | ss (Obj) {
    method trojan (line 68) | trojan (Obj) {
  function URLQueryWrapper (line 73) | function URLQueryWrapper (Obj) {

FILE: functions/internal/Dumpers/sing-box.js
  class Dumper (line 1) | class Dumper {
    method constructor (line 3) | constructor (
    method __validate (line 17) | __validate (ProxyObject) {
    method http (line 29) | http (HTTP) {
    method socks5 (line 45) | socks5 (SOCKS5) {
    method hysteria (line 58) | hysteria (hyObject) {
    method hysteria2 (line 79) | hysteria2 (hy2Object) {
    method tuic (line 108) | tuic (TUIC) {
    method vless (line 133) | vless (VLESS) {
    method vmess__shadowsocks_type (line 160) | vmess__shadowsocks_type (VMess) {
    method vmess (line 201) | vmess (VMESS) {
    method ss (line 228) | ss (SS) {
    method trojan (line 243) | trojan (TROJAN) {
  function __genRealityConfig (line 269) | function __genRealityConfig (URIObject) {
  function __genTransportConfig (line 276) | function __genTransportConfig (URIObject) {

FILE: functions/internal/Parsers/clash-meta.js
  class ClashMetaParser (line 1) | class ClashMetaParser {
    method constructor (line 2) | constructor () {}
    method __validate (line 4) | __validate (ProxyObject) {
    method http (line 12) | http (Obj) {
    method socks5 (line 24) | socks5 (Obj) {
    method hysteria (line 37) | hysteria (Obj) {
    method hysteria2 (line 53) | hysteria2 (Obj) {
    method tuic (line 70) | tuic (Obj) {
    method vless (line 88) | vless (Obj) {
    method vmess (line 128) | vmess (Obj) {
    method ss (line 160) | ss (Obj) {
    method trojan (line 170) | trojan (Obj) {
  function __searchParamsMapper (line 207) | function __searchParamsMapper (searchParams) {

FILE: functions/internal/Parsers/share-link.js
  class ShareLinkParser (line 1) | class ShareLinkParser {
    method constructor (line 2) | constructor () {}
    method __validate (line 4) | __validate (URI) {
    method http (line 12) | http (URI) {
    method socks5 (line 25) | socks5 (URI) {
    method hysteria (line 39) | hysteria (HYURL) {
    method hysteria2 (line 51) | hysteria2 (HY2URL) {
    method tuic (line 66) | tuic (TUICURI) {
    method vless (line 81) | vless (URI) {
    method vmess (line 93) | vmess (URI) {
    method ss (line 153) | ss (URI) {
    method trojan (line 181) | trojan (URI) {
  function __searchParamsMapper (line 196) | function __searchParamsMapper (searchParams) {

FILE: functions/internal/Parsers/sing-box.js
  class SingBoxParser (line 1) | class SingBoxParser {
    method constructor (line 2) | constructor () {}
    method __validate (line 4) | __validate (ProxyObject) {
    method http (line 16) | http (Obj) {
    method socks (line 28) | socks (Obj) {
    method hysteria (line 41) | hysteria (Obj) {
    method hysteria2 (line 57) | hysteria2 (Obj) {
    method tuic (line 75) | tuic (Obj) {
    method vless (line 93) | vless (Obj) {
    method vmess (line 127) | vmess (Obj) {
    method shadowsocks (line 153) | shadowsocks (Obj) {
    method trojan (line 163) | trojan (Obj) {

FILE: functions/internal/RuleProviderReader/Readers/ini.js
  function ini (line 5) | async function ini (RuleProviderURL, CacheDB, isForcedRefresh) {

FILE: functions/internal/RuleProviderReader/main.js
  class RuleProviderReader (line 3) | class RuleProviderReader {
    method constructor (line 8) | constructor (RuleProviderURL) {

FILE: functions/internal/data/rule/MetaToSingLogicalRule.ts
  function MetaToSingLogicalRule (line 16) | function MetaToSingLogicalRule (type: string, payload: string, EdgeSubIn...
  function parseParenthesizedItems (line 71) | function parseParenthesizedItems(inputString: string): string[] {

FILE: functions/internal/data/ruleset/transformGeoRef.ts
  type headlessRuleSet (line 1) | type headlessRuleSet = {
  function transformGeoRef (line 9) | function transformGeoRef (

FILE: functions/internal/getParsedSubData.ts
  type SubURL (line 13) | type SubURL = string;
  type SubURLs (line 14) | type SubURLs = string;
  type SubURLArr (line 15) | type SubURLArr = SubURL[];
  type ParsedSubscription (line 16) | type ParsedSubscription = {
  type SubscriptionUserInfo (line 20) | type SubscriptionUserInfo = {
  function getParsedSubData (line 29) | async function getParsedSubData (
  function ParseSubData (line 70) | async function ParseSubData (SubURL: SubURL, EdgeSubDB, RequestHeaders) ...

FILE: functions/internal/types/ClashMetaConfig.ts
  type ClashMetaProxyGroup (line 3) | type ClashMetaProxyGroup = {
  type ClashMetaConfig (line 12) | type ClashMetaConfig = {
  type TransportHTTP (line 34) | type TransportHTTP = {
  type TransportH2 (line 41) | type TransportH2 = {
  type TransportGRPC (line 45) | type TransportGRPC = {
  type TransportWS (line 48) | type TransportWS = {
  type RealityConfig (line 60) | type RealityConfig = {

FILE: functions/internal/utils/TrulyAssign.js
  function TrulyAssign (line 8) | function TrulyAssign (target, source) {

FILE: functions/internal/utils/fetchCached.ts
  function fetchCached (line 1) | async function fetchCached (URL: URL, Prefix = "Cached", CacheDB: KVName...

FILE: functions/internal/utils/parseContentDisposition.ts
  function parseContentDisposition (line 1) | function parseContentDisposition(RawContentDispositionHeader: string): s...

FILE: functions/internal/utils/removeUndefinedFields.ts
  function removeUndefinedFields (line 1) | function removeUndefinedFields (obj: object) : object {

FILE: functions/ruleset/preprocessor/sing-box.ts
  function onRequest (line 4) | async function onRequest (context) {

FILE: functions/ruleset/proxy.ts
  function onRequest (line 3) | async function onRequest (context) {

FILE: functions/short/admin-password/set.ts
  function onRequestPost (line 4) | async function onRequestPost (context) {
  function onRequestOptions (line 73) | async function onRequestOptions (context) {

FILE: functions/short/admin-password/status.ts
  function onRequest (line 3) | async function onRequest (context) {

FILE: functions/short/delete/[id].ts
  function onRequestDelete (line 3) | async function onRequestDelete (context) {
  function onRequestOptions (line 60) | async function onRequestOptions (context) {

FILE: functions/short/get/[id].ts
  function onRequest (line 3) | async function onRequest (context) {

FILE: functions/short/list.ts
  function onRequestPost (line 4) | async function onRequestPost (context) {
  function onRequestOptions (line 64) | async function onRequestOptions (context) {

FILE: functions/short/put.ts
  function onRequestPost (line 3) | async function onRequestPost (context) {
  function onRequestOptions (line 51) | async function onRequestOptions (context) {
  function generateToken (line 59) | async function generateToken (length, EdgeSubDB = undefined) {

FILE: functions/short/token-reset/[id].ts
  function onRequestPatch (line 3) | async function onRequestPatch (context) {
  function onRequestOptions (line 61) | async function onRequestOptions (context) {

FILE: functions/sub/base64.js
  function onRequest (line 3) | async function onRequest (context) {

FILE: functions/sub/clash-meta.js
  function onRequest (line 6) | async function onRequest (context) {

FILE: functions/sub/debug.js
  function onRequest (line 3) | async function onRequest (context) {

FILE: functions/sub/share-link.js
  function onRequest (line 4) | async function onRequest (context, isBase64 = false) {

FILE: functions/sub/sing-box.js
  function onRequest (line 4) | async function onRequest (context) {

FILE: src/config/AvalibleOptoutFormat.ts
  type EndpointExtendConfigPrototype (line 2) | type EndpointExtendConfigPrototype = "RuleProvider" | "RuleProvidersProx...
  type EndpointPrototype (line 4) | type EndpointPrototype = {

FILE: src/config/RuleProviders.ts
  type RuleProvider (line 1) | type RuleProvider = {

FILE: src/scripts/components/data-input.ts
  class DataInput (line 3) | class DataInput extends HTMLElement {
    method constructor (line 6) | constructor () {
    method get (line 10) | get () { // boolean if toggle, string if any otherwise
    method set (line 24) | set (value: string) {
    method setDetail (line 38) | setDetail(value: string) {
    method getDetail (line 49) | getDetail() {
  function maybeWaitFor (line 59) | function maybeWaitFor(tag) {

FILE: src/scripts/components/k-dropdown.ts
  class Dropdown (line 1) | class Dropdown extends HTMLElement {
    method constructor (line 2) | constructor () {
    method initializeElements (line 9) | private initializeElements() {
    method setupEventListeners (line 17) | private setupEventListeners() {
    method select (line 26) | public select(value: string) {

FILE: src/scripts/components/k-suburl-generator.ts
  class SubURLGenerator (line 7) | class SubURLGenerator extends HTMLElement {
    method constructor (line 11) | constructor () {
    method setupEventListeners (line 22) | private setupEventListeners () {
    method GetEndpoint (line 78) | private GetEndpoint (EndpointPath: string = String(this.Elements.Confi...
    method getConfig (line 87) | private getConfig () {
    method CheckAndGenerate (line 113) | CheckAndGenerate () {

FILE: src/scripts/components/shorter/k-shorter.ts
  class Shorter (line 4) | class Shorter extends HTMLElement {
    method constructor (line 6) | constructor () {
    method setupEventListeners (line 10) | private setupEventListeners () {
    method Copy (line 14) | private Copy () {
    method Submit (line 23) | private async Submit () {

FILE: src/scripts/components/shorter/short-destroyer.ts
  class Shorter (line 4) | class Shorter extends HTMLElement {
    method constructor (line 6) | constructor () {
    method Submit (line 10) | async Submit () {

FILE: src/scripts/components/shorter/short-editor.ts
  class ShortEditor (line 4) | class ShortEditor extends HTMLElement {
    method constructor (line 6) | constructor () {
    method Fetch (line 16) | Fetch () {
    method Submit (line 38) | Submit () {

FILE: src/scripts/components/shorter/short-token-reset.ts
  class ShortTokenResetter (line 4) | class ShortTokenResetter extends HTMLElement {
    method constructor (line 6) | constructor () {
    method Submit (line 10) | async Submit () {

FILE: src/scripts/components/shorter/shorter-list.ts
  class ShorterList (line 4) | class ShorterList extends HTMLElement {
    method constructor (line 6) | constructor () {
    method Submit (line 10) | async Submit () {
  class ListItem (line 67) | class ListItem extends HTMLElement {
    method constructor (line 69) | constructor () {
    method CopyID (line 75) | CopyID () {
    method JumpToEdit (line 86) | JumpToEdit () {
    method update (line 89) | update (ShortID, EditTimestamp) {

FILE: src/scripts/components/shorter/shorter-password.ts
  class ShorterPassword (line 4) | class ShorterPassword extends HTMLElement {
    method constructor (line 6) | constructor () {
    method Submit (line 10) | async Submit () {

FILE: src/scripts/utils/copy.ts
  function copyToClipboard (line 1) | function copyToClipboard(text: string) {

FILE: src/scripts/utils/filterObject.ts
  function filterObject (line 11) | function filterObject <T extends object> (

FILE: src/scripts/utils/getDefaultBackend.ts
  function getDefaultBackend (line 1) | function getDefaultBackend () {

FILE: types/worker-configuration.d.ts
  type Env (line 4) | interface Env {
  type Env (line 8) | interface Env extends Cloudflare.Env {}
  class DOMException (line 33) | class DOMException extends Error {
  type WorkerGlobalScopeEventMap (line 73) | type WorkerGlobalScopeEventMap = {
  type Console (line 84) | interface Console {
  type BufferSource (line 125) | type BufferSource = ArrayBufferView | ArrayBuffer;
  type TypedArray (line 126) | type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Arra...
  class CompileError (line 128) | class CompileError extends Error {
  class RuntimeError (line 131) | class RuntimeError extends Error {
  type ValueType (line 134) | type ValueType = "anyfunc" | "externref" | "f32" | "f64" | "i32" | "i64"...
  type GlobalDescriptor (line 135) | interface GlobalDescriptor {
  class Global (line 139) | class Global {
  type ImportValue (line 144) | type ImportValue = ExportValue | number;
  type ModuleImports (line 145) | type ModuleImports = Record<string, ImportValue>;
  type Imports (line 146) | type Imports = Record<string, ModuleImports>;
  type ExportValue (line 147) | type ExportValue = Function | Global | Memory | Table;
  type Exports (line 148) | type Exports = Record<string, ExportValue>;
  class Instance (line 149) | class Instance {
  type MemoryDescriptor (line 153) | interface MemoryDescriptor {
  class Memory (line 158) | class Memory {
  type ImportExportKind (line 163) | type ImportExportKind = "function" | "global" | "memory" | "table";
  type ModuleExportDescriptor (line 164) | interface ModuleExportDescriptor {
  type ModuleImportDescriptor (line 168) | interface ModuleImportDescriptor {
  type TableKind (line 178) | type TableKind = "anyfunc" | "externref";
  type TableDescriptor (line 179) | interface TableDescriptor {
  class Table (line 184) | class Table {
  type ServiceWorkerGlobalScope (line 200) | interface ServiceWorkerGlobalScope extends WorkerGlobalScope {
  type TestController (line 338) | interface TestController {
  type ExecutionContext (line 340) | interface ExecutionContext {
  type ExportedHandlerFetchHandler (line 345) | type ExportedHandlerFetchHandler<Env = unknown, CfHostMetadata = unknown...
  type ExportedHandlerTailHandler (line 346) | type ExportedHandlerTailHandler<Env = unknown> = (events: TraceItem[], e...
  type ExportedHandlerTraceHandler (line 347) | type ExportedHandlerTraceHandler<Env = unknown> = (traces: TraceItem[], ...
  type ExportedHandlerTailStreamHandler (line 348) | type ExportedHandlerTailStreamHandler<Env = unknown> = (event: TailStrea...
  type ExportedHandlerScheduledHandler (line 349) | type ExportedHandlerScheduledHandler<Env = unknown> = (controller: Sched...
  type ExportedHandlerQueueHandler (line 350) | type ExportedHandlerQueueHandler<Env = unknown, Message = unknown> = (ba...
  type ExportedHandlerTestHandler (line 351) | type ExportedHandlerTestHandler<Env = unknown> = (controller: TestContro...
  type ExportedHandler (line 352) | interface ExportedHandler<Env = unknown, QueueHandlerMessage = unknown, ...
  type StructuredSerializeOptions (line 362) | interface StructuredSerializeOptions {
  type Performance (line 383) | interface Performance {
  type AlarmInvocationInfo (line 389) | interface AlarmInvocationInfo {
  type Cloudflare (line 393) | interface Cloudflare {
  type DurableObject (line 396) | interface DurableObject {
  type DurableObjectStub (line 403) | type DurableObjectStub<T extends Rpc.DurableObjectBranded | undefined = ...
  type DurableObjectId (line 407) | interface DurableObjectId {
  type DurableObjectNamespace (line 412) | interface DurableObjectNamespace<T extends Rpc.DurableObjectBranded | un...
  type DurableObjectJurisdiction (line 419) | type DurableObjectJurisdiction = "eu" | "fedramp";
  type DurableObjectNamespaceNewUniqueIdOptions (line 420) | interface DurableObjectNamespaceNewUniqueIdOptions {
  type DurableObjectLocationHint (line 423) | type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeu...
  type DurableObjectNamespaceGetDurableObjectOptions (line 424) | interface DurableObjectNamespaceGetDurableObjectOptions {
  type DurableObjectState (line 427) | interface DurableObjectState {
  type DurableObjectTransaction (line 443) | interface DurableObjectTransaction {
  type DurableObjectStorage (line 456) | interface DurableObjectStorage {
  type DurableObjectListOptions (line 476) | interface DurableObjectListOptions {
  type DurableObjectGetOptions (line 486) | interface DurableObjectGetOptions {
  type DurableObjectGetAlarmOptions (line 490) | interface DurableObjectGetAlarmOptions {
  type DurableObjectPutOptions (line 493) | interface DurableObjectPutOptions {
  type DurableObjectSetAlarmOptions (line 498) | interface DurableObjectSetAlarmOptions {
  class WebSocketRequestResponsePair (line 502) | class WebSocketRequestResponsePair {
  type AnalyticsEngineDataset (line 507) | interface AnalyticsEngineDataset {
  type AnalyticsEngineDataPoint (line 510) | interface AnalyticsEngineDataPoint {
  class Event (line 520) | class Event {
  type EventInit (line 635) | interface EventInit {
  type EventListener (line 640) | type EventListener<EventType extends Event = Event> = (event: EventType)...
  type EventListenerObject (line 641) | interface EventListenerObject<EventType extends Event = Event> {
  type EventListenerOrEventListenerObject (line 644) | type EventListenerOrEventListenerObject<EventType extends Event = Event>...
  class EventTarget (line 650) | class EventTarget<EventMap extends Record<string, Event> = Record<string...
  type EventTargetEventListenerOptions (line 683) | interface EventTargetEventListenerOptions {
  type EventTargetAddEventListenerOptions (line 686) | interface EventTargetAddEventListenerOptions {
  type EventTargetHandlerObject (line 692) | interface EventTargetHandlerObject {
  class AbortController (line 700) | class AbortController {
  type Scheduler (line 742) | interface Scheduler {
  type SchedulerWaitOptions (line 745) | interface SchedulerWaitOptions {
  class CustomEvent (line 758) | class CustomEvent<T = any> extends Event {
  type CustomEventCustomEventInit (line 767) | interface CustomEventCustomEventInit {
  class Blob (line 778) | class Blob {
  type BlobOptions (line 794) | interface BlobOptions {
  class File (line 802) | class File extends Blob {
  type FileOptions (line 809) | interface FileOptions {
  type CacheQueryOptions (line 836) | interface CacheQueryOptions {
  type CryptoKeyPair (line 913) | interface CryptoKeyPair {
  type JsonWebKey (line 917) | interface JsonWebKey {
  type RsaOtherPrimesInfo (line 937) | interface RsaOtherPrimesInfo {
  type SubtleCryptoDeriveKeyAlgorithm (line 942) | interface SubtleCryptoDeriveKeyAlgorithm {
  type SubtleCryptoEncryptAlgorithm (line 950) | interface SubtleCryptoEncryptAlgorithm {
  type SubtleCryptoGenerateKeyAlgorithm (line 959) | interface SubtleCryptoGenerateKeyAlgorithm {
  type SubtleCryptoHashAlgorithm (line 967) | interface SubtleCryptoHashAlgorithm {
  type SubtleCryptoImportKeyAlgorithm (line 970) | interface SubtleCryptoImportKeyAlgorithm {
  type SubtleCryptoSignAlgorithm (line 977) | interface SubtleCryptoSignAlgorithm {
  type CryptoKeyKeyAlgorithm (line 983) | interface CryptoKeyKeyAlgorithm {
  type CryptoKeyAesKeyAlgorithm (line 986) | interface CryptoKeyAesKeyAlgorithm {
  type CryptoKeyHmacKeyAlgorithm (line 990) | interface CryptoKeyHmacKeyAlgorithm {
  type CryptoKeyRsaKeyAlgorithm (line 995) | interface CryptoKeyRsaKeyAlgorithm {
  type CryptoKeyEllipticKeyAlgorithm (line 1001) | interface CryptoKeyEllipticKeyAlgorithm {
  type CryptoKeyArbitraryKeyAlgorithm (line 1005) | interface CryptoKeyArbitraryKeyAlgorithm {
  class DigestStream (line 1011) | class DigestStream extends WritableStream<ArrayBuffer | ArrayBufferView> {
  class TextDecoder (line 1021) | class TextDecoder {
  class TextEncoder (line 1048) | class TextEncoder {
  type TextDecoderConstructorOptions (line 1064) | interface TextDecoderConstructorOptions {
  type TextDecoderDecodeOptions (line 1068) | interface TextDecoderDecodeOptions {
  type TextEncoderEncodeIntoResult (line 1071) | interface TextEncoderEncodeIntoResult {
  class ErrorEvent (line 1080) | class ErrorEvent extends Event {
  type ErrorEventErrorEventInit (line 1088) | interface ErrorEventErrorEventInit {
  class FormData (line 1100) | class FormData {
  type ContentOptions (line 1133) | interface ContentOptions {
  class HTMLRewriter (line 1136) | class HTMLRewriter {
  type HTMLRewriterElementContentHandlers (line 1142) | interface HTMLRewriterElementContentHandlers {
  type HTMLRewriterDocumentContentHandlers (line 1147) | interface HTMLRewriterDocumentContentHandlers {
  type Doctype (line 1153) | interface Doctype {
  type Element (line 1158) | interface Element {
  type EndTag (line 1177) | interface EndTag {
  type Comment (line 1183) | interface Comment {
  type Text (line 1191) | interface Text {
  type DocumentEnd (line 1200) | interface DocumentEnd {
  type HeadersInit (line 1215) | type HeadersInit = Headers | Iterable<Iterable<string>> | Record<string,...
  class Headers (line 1221) | class Headers {
  type BodyInit (line 1251) | type BodyInit = ReadableStream<Uint8Array> | string | ArrayBuffer | Arra...
  type Response (line 1286) | interface Response extends Body {
  type ResponseInit (line 1306) | interface ResponseInit {
  type RequestInfo (line 1314) | type RequestInfo<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetad...
  type Request (line 1329) | interface Request<CfHostMetadata = unknown, Cf = CfProperties<CfHostMeta...
  type RequestInit (line 1373) | interface RequestInit<Cf = CfProperties> {
  type Service (line 1390) | type Service<T extends Rpc.WorkerEntrypointBranded | undefined = undefin...
  type Fetcher (line 1391) | type Fetcher<T extends Rpc.EntrypointBranded | undefined = undefined, Re...
  type FetcherPutOptions (line 1395) | interface FetcherPutOptions {
  type KVNamespaceListKey (line 1399) | interface KVNamespaceListKey<Metadata, Key extends string = string> {
  type KVNamespaceListResult (line 1404) | type KVNamespaceListResult<Metadata, Key extends string = string> = {
  type KVNamespace (line 1414) | interface KVNamespace<Key extends string = string> {
  type KVNamespaceListOptions (line 1447) | interface KVNamespaceListOptions {
  type KVNamespaceGetOptions (line 1452) | interface KVNamespaceGetOptions<Type> {
  type KVNamespacePutOptions (line 1456) | interface KVNamespacePutOptions {
  type KVNamespaceGetWithMetadataResult (line 1461) | interface KVNamespaceGetWithMetadataResult<Value, Metadata> {
  type QueueContentType (line 1466) | type QueueContentType = "text" | "bytes" | "json" | "v8";
  type Queue (line 1467) | interface Queue<Body = unknown> {
  type QueueSendOptions (line 1471) | interface QueueSendOptions {
  type QueueSendBatchOptions (line 1475) | interface QueueSendBatchOptions {
  type MessageSendRequest (line 1478) | interface MessageSendRequest<Body = unknown> {
  type QueueRetryOptions (line 1483) | interface QueueRetryOptions {
  type Message (line 1486) | interface Message<Body = unknown> {
  type QueueEvent (line 1494) | interface QueueEvent<Body = unknown> extends ExtendableEvent {
  type MessageBatch (line 1500) | interface MessageBatch<Body = unknown> {
  type R2Error (line 1506) | interface R2Error extends Error {
  type R2ListOptions (line 1513) | interface R2ListOptions {
  type R2MultipartUpload (line 1536) | interface R2MultipartUpload {
  type R2UploadedPart (line 1543) | interface R2UploadedPart {
  type R2ObjectBody (line 1562) | interface R2ObjectBody extends R2Object {
  type R2Range (line 1570) | type R2Range = {
  type R2Conditional (line 1579) | interface R2Conditional {
  type R2GetOptions (line 1586) | interface R2GetOptions {
  type R2PutOptions (line 1591) | interface R2PutOptions {
  type R2MultipartOptions (line 1603) | interface R2MultipartOptions {
  type R2Checksums (line 1609) | interface R2Checksums {
  type R2StringChecksums (line 1617) | interface R2StringChecksums {
  type R2HTTPMetadata (line 1624) | interface R2HTTPMetadata {
  type R2Objects (line 1632) | type R2Objects = {
  type R2UploadPartOptions (line 1641) | interface R2UploadPartOptions {
  type ScheduledController (line 1649) | interface ScheduledController {
  type QueuingStrategy (line 1654) | interface QueuingStrategy<T = any> {
  type UnderlyingSink (line 1658) | interface UnderlyingSink<W = any> {
  type UnderlyingByteSource (line 1665) | interface UnderlyingByteSource {
  type UnderlyingSource (line 1672) | interface UnderlyingSource<R = any> {
  type Transformer (line 1679) | interface Transformer<I = any, O = any> {
  type StreamPipeOptions (line 1688) | interface StreamPipeOptions {
  type ReadableStreamReadResult (line 1711) | type ReadableStreamReadResult<R = any> = {
  type ReadableStream (line 1723) | interface ReadableStream<R = any> {
  class ReadableStreamDefaultReader (line 1755) | class ReadableStreamDefaultReader<R = any> {
  class ReadableStreamBYOBReader (line 1765) | class ReadableStreamBYOBReader {
  type ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions (line 1775) | interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions {
  type ReadableStreamGetReaderOptions (line 1778) | interface ReadableStreamGetReaderOptions {
  type ReadableWritablePair (line 1842) | interface ReadableWritablePair<R = any, W = any> {
  class WritableStream (line 1856) | class WritableStream<W = any> {
  class WritableStreamDefaultWriter (line 1872) | class WritableStreamDefaultWriter<W = any> {
  class TransformStream (line 1890) | class TransformStream<I = any, O = any> {
  class FixedLengthStream (line 1897) | class FixedLengthStream extends IdentityTransformStream {
  class IdentityTransformStream (line 1900) | class IdentityTransformStream extends TransformStream<ArrayBuffer | Arra...
  type IdentityTransformStreamQueuingStrategy (line 1903) | interface IdentityTransformStreamQueuingStrategy {
  type ReadableStreamValuesOptions (line 1906) | interface ReadableStreamValuesOptions {
  class CompressionStream (line 1910) | class CompressionStream extends TransformStream<ArrayBuffer | ArrayBuffe...
  class DecompressionStream (line 1914) | class DecompressionStream extends TransformStream<ArrayBuffer | ArrayBuf...
  class TextEncoderStream (line 1918) | class TextEncoderStream extends TransformStream<string, Uint8Array> {
  class TextDecoderStream (line 1923) | class TextDecoderStream extends TransformStream<ArrayBuffer | ArrayBuffe...
  type TextDecoderStreamTextDecoderStreamInit (line 1929) | interface TextDecoderStreamTextDecoderStreamInit {
  class ByteLengthQueuingStrategy (line 1938) | class ByteLengthQueuingStrategy implements QueuingStrategy<ArrayBufferVi...
  class CountQueuingStrategy (line 1950) | class CountQueuingStrategy implements QueuingStrategy {
  type QueuingStrategyInit (line 1957) | interface QueuingStrategyInit {
  type ScriptVersion (line 1965) | interface ScriptVersion {
  type TraceItem (line 1974) | interface TraceItem {
  type TraceItemAlarmEventInfo (line 1991) | interface TraceItemAlarmEventInfo {
  type TraceItemCustomEventInfo (line 1994) | interface TraceItemCustomEventInfo {
  type TraceItemScheduledEventInfo (line 1996) | interface TraceItemScheduledEventInfo {
  type TraceItemQueueEventInfo (line 2000) | interface TraceItemQueueEventInfo {
  type TraceItemEmailEventInfo (line 2004) | interface TraceItemEmailEventInfo {
  type TraceItemTailEventInfo (line 2009) | interface TraceItemTailEventInfo {
  type TraceItemTailEventInfoTailItem (line 2012) | interface TraceItemTailEventInfoTailItem {
  type TraceItemFetchEventInfo (line 2015) | interface TraceItemFetchEventInfo {
  type TraceItemFetchEventInfoRequest (line 2019) | interface TraceItemFetchEventInfoRequest {
  type TraceItemFetchEventInfoResponse (line 2026) | interface TraceItemFetchEventInfoResponse {
  type TraceItemJsRpcEventInfo (line 2029) | interface TraceItemJsRpcEventInfo {
  type TraceItemHibernatableWebSocketEventInfo (line 2032) | interface TraceItemHibernatableWebSocketEventInfo {
  type TraceItemHibernatableWebSocketEventInfoMessage (line 2035) | interface TraceItemHibernatableWebSocketEventInfoMessage {
  type TraceItemHibernatableWebSocketEventInfoClose (line 2038) | interface TraceItemHibernatableWebSocketEventInfoClose {
  type TraceItemHibernatableWebSocketEventInfoError (line 2043) | interface TraceItemHibernatableWebSocketEventInfoError {
  type TraceLog (line 2046) | interface TraceLog {
  type TraceException (line 2051) | interface TraceException {
  type TraceDiagnosticChannelEvent (line 2057) | interface TraceDiagnosticChannelEvent {
  type TraceMetrics (line 2062) | interface TraceMetrics {
  type UnsafeTraceMetrics (line 2066) | interface UnsafeTraceMetrics {
  class URL (line 2074) | class URL {
  class URLSearchParams (line 2134) | class URLSearchParams {
  class URLPattern (line 2193) | class URLPattern {
  type URLPatternURLPatternInit (line 2206) | interface URLPatternURLPatternInit {
  type URLPatternURLPatternComponentResult (line 2217) | interface URLPatternURLPatternComponentResult {
  type URLPatternURLPatternResult (line 2221) | interface URLPatternURLPatternResult {
  type URLPatternURLPatternOptions (line 2232) | interface URLPatternURLPatternOptions {
  class CloseEvent (line 2240) | class CloseEvent extends Event {
  type CloseEventInit (line 2261) | interface CloseEventInit {
  class MessageEvent (line 2271) | class MessageEvent extends Event {
  type MessageEventInit (line 2280) | interface MessageEventInit {
  type WebSocketEventMap (line 2283) | type WebSocketEventMap = {
  type WebSocket (line 2311) | interface WebSocket extends EventTarget<WebSocketEventMap> {
  type SqlStorage (line 2358) | interface SqlStorage {
  type SqlStorageValue (line 2366) | type SqlStorageValue = ArrayBuffer | string | number | null;
  type Socket (line 2383) | interface Socket {
  type SocketOptions (line 2391) | interface SocketOptions {
  type SocketAddress (line 2396) | interface SocketAddress {
  type TlsOptions (line 2400) | interface TlsOptions {
  type SocketInfo (line 2403) | interface SocketInfo {
  class EventSource (line 2408) | class EventSource extends EventTarget {
  type EventSourceEventSourceInit (line 2451) | interface EventSourceEventSourceInit {
  type Container (line 2455) | interface Container {
  type ContainerStartupOptions (line 2463) | interface ContainerStartupOptions {
  type AiImageClassificationInput (line 2468) | type AiImageClassificationInput = {
  type AiImageClassificationOutput (line 2471) | type AiImageClassificationOutput = {
  type AiImageToTextInput (line 2479) | type AiImageToTextInput = {
  type AiImageToTextOutput (line 2493) | type AiImageToTextOutput = {
  type AiImageTextToTextInput (line 2500) | type AiImageTextToTextInput = {
  type AiImageTextToTextOutput (line 2515) | type AiImageTextToTextOutput = {
  type AiObjectDetectionInput (line 2522) | type AiObjectDetectionInput = {
  type AiObjectDetectionOutput (line 2525) | type AiObjectDetectionOutput = {
  type AiSentenceSimilarityInput (line 2533) | type AiSentenceSimilarityInput = {
  type AiSentenceSimilarityOutput (line 2537) | type AiSentenceSimilarityOutput = number[];
  type AiAutomaticSpeechRecognitionInput (line 2542) | type AiAutomaticSpeechRecognitionInput = {
  type AiAutomaticSpeechRecognitionOutput (line 2545) | type AiAutomaticSpeechRecognitionOutput = {
  type AiSummarizationInput (line 2558) | type AiSummarizationInput = {
  type AiSummarizationOutput (line 2562) | type AiSummarizationOutput = {
  type AiTextClassificationInput (line 2569) | type AiTextClassificationInput = {
  type AiTextClassificationOutput (line 2572) | type AiTextClassificationOutput = {
  type AiTextEmbeddingsInput (line 2580) | type AiTextEmbeddingsInput = {
  type AiTextEmbeddingsOutput (line 2583) | type AiTextEmbeddingsOutput = {
  type RoleScopedChatInput (line 2591) | type RoleScopedChatInput = {
  type AiTextGenerationToolLegacyInput (line 2596) | type AiTextGenerationToolLegacyInput = {
  type AiTextGenerationToolInput (line 2610) | type AiTextGenerationToolInput = {
  type AiTextGenerationFunctionsInput (line 2627) | type AiTextGenerationFunctionsInput = {
  type AiTextGenerationResponseFormat (line 2631) | type AiTextGenerationResponseFormat = {
  type AiTextGenerationInput (line 2635) | type AiTextGenerationInput = {
  type AiTextGenerationOutput (line 2652) | type AiTextGenerationOutput = {
  type AiTextToSpeechInput (line 2663) | type AiTextToSpeechInput = {
  type AiTextToSpeechOutput (line 2667) | type AiTextToSpeechOutput = Uint8Array | {
  type AiTextToImageInput (line 2674) | type AiTextToImageInput = {
  type AiTextToImageOutput (line 2687) | type AiTextToImageOutput = ReadableStream<Uint8Array>;
  type AiTranslationInput (line 2692) | type AiTranslationInput = {
  type AiTranslationOutput (line 2697) | type AiTranslationOutput = {
  type Ai_Cf_Openai_Whisper_Input (line 2704) | type Ai_Cf_Openai_Whisper_Input = string | {
  type Ai_Cf_Openai_Whisper_Output (line 2710) | interface Ai_Cf_Openai_Whisper_Output {
  type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input (line 2733) | type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = string | {
  type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output (line 2772) | interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output {
  type Ai_Cf_Openai_Whisper_Tiny_En_Input (line 2779) | type Ai_Cf_Openai_Whisper_Tiny_En_Input = string | {
  type Ai_Cf_Openai_Whisper_Tiny_En_Output (line 2785) | interface Ai_Cf_Openai_Whisper_Tiny_En_Output {
  type Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input (line 2808) | interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input {
  type Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output (line 2834) | interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output {
  type Ai_Cf_Baai_Bge_M3_Input (line 2914) | type Ai_Cf_Baai_Bge_M3_Input = BGEM3InputQueryAndContexts | BGEM3InputEm...
  type BGEM3InputQueryAndContexts (line 2915) | interface BGEM3InputQueryAndContexts {
  type BGEM3InputEmbedding (line 2934) | interface BGEM3InputEmbedding {
  type Ai_Cf_Baai_Bge_M3_Output (line 2941) | type Ai_Cf_Baai_Bge_M3_Output = BGEM3OuputQuery | BGEM3OutputEmbeddingFo...
  type BGEM3OuputQuery (line 2942) | interface BGEM3OuputQuery {
  type BGEM3OutputEmbeddingForContexts (line 2954) | interface BGEM3OutputEmbeddingForContexts {
  type BGEM3OuputEmbedding (line 2962) | interface BGEM3OuputEmbedding {
  type Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input (line 2977) | interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input {
  type Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output (line 2987) | interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output {
  type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input (line 2997) | type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Prompt | Messages;
  type Prompt (line 2998) | interface Prompt {
  type Messages (line 3049) | interface Messages {
  type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output (line 3192) | type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = {
  type Ai_Cf_Meta_Llama_Guard_3_8B_Input (line 3215) | interface Ai_Cf_Meta_Llama_Guard_3_8B_Input {
  type Ai_Cf_Meta_Llama_Guard_3_8B_Output (line 3247) | interface Ai_Cf_Meta_Llama_Guard_3_8B_Output {
  type Ai_Cf_Baai_Bge_Reranker_Base_Input (line 3280) | interface Ai_Cf_Baai_Bge_Reranker_Base_Input {
  type Ai_Cf_Baai_Bge_Reranker_Base_Output (line 3298) | interface Ai_Cf_Baai_Bge_Reranker_Base_Output {
  type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input (line 3314) | type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_...
  type Ai_Cf_Meta_Llama_4_Prompt (line 3315) | interface Ai_Cf_Meta_Llama_4_Prompt {
  type Ai_Cf_Meta_Llama_4_Messages (line 3365) | interface Ai_Cf_Meta_Llama_4_Messages {
  type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output (line 3540) | type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = {
  type AiModels (line 3580) | interface AiModels {
  type AiOptions (line 3648) | type AiOptions = {
  type ConversionResponse (line 3654) | type ConversionResponse = {
  type AiModelsSearchParams (line 3661) | type AiModelsSearchParams = {
  type AiModelsSearchObject (line 3670) | type AiModelsSearchObject = {
  type InferenceUpstreamError (line 3686) | interface InferenceUpstreamError extends Error {
  type AiInternalError (line 3688) | interface AiInternalError extends Error {
  type AiModelListType (line 3690) | type AiModelListType = Record<string, any>;
  type GatewayOptions (line 3714) | type GatewayOptions = {
  type AiGatewayPatchLog (line 3722) | type AiGatewayPatchLog = {
  type AiGatewayLog (line 3727) | type AiGatewayLog = {
  type AIGatewayProviders (line 3754) | type AIGatewayProviders = "workers-ai" | "anthropic" | "aws-bedrock" | "...
  type AIGatewayHeaders (line 3755) | type AIGatewayHeaders = {
  type AIGatewayUniversalRequest (line 3771) | type AIGatewayUniversalRequest = {
  type AiGatewayInternalError (line 3777) | interface AiGatewayInternalError extends Error {
  type AiGatewayLogNotFound (line 3779) | interface AiGatewayLogNotFound extends Error {
  type AutoRAGInternalError (line 3787) | interface AutoRAGInternalError extends Error {
  type AutoRAGNotFoundError (line 3789) | interface AutoRAGNotFoundError extends Error {
  type AutoRAGUnauthorizedError (line 3791) | interface AutoRAGUnauthorizedError extends Error {
  type AutoRagSearchRequest (line 3793) | type AutoRagSearchRequest = {
  type AutoRagSearchResponse (line 3802) | type AutoRagSearchResponse = {
  type AutoRagAiSearchResponse (line 3818) | type AutoRagAiSearchResponse = AutoRagSearchResponse & {
  type BasicImageTransformations (line 3825) | interface BasicImageTransformations {
  type BasicImageTransformationsGravityCoordinates (line 3886) | interface BasicImageTransformationsGravityCoordinates {
  type RequestInitCfProperties (line 3900) | interface RequestInitCfProperties extends Record<string, unknown> {
  type RequestInitCfPropertiesImageDraw (line 3951) | interface RequestInitCfPropertiesImageDraw extends BasicImageTransformat...
  type RequestInitCfPropertiesImage (line 3988) | interface RequestInitCfPropertiesImage extends BasicImageTransformations {
  type RequestInitCfPropertiesImageMinify (line 4139) | interface RequestInitCfPropertiesImageMinify {
  type RequestInitCfPropertiesR2 (line 4144) | interface RequestInitCfPropertiesR2 {
  type IncomingRequestCfProperties (line 4153) | type IncomingRequestCfProperties<HostMetadata = unknown> = IncomingReque...
  type IncomingRequestCfPropertiesBase (line 4154) | interface IncomingRequestCfPropertiesBase extends Record<string, unknown> {
  type IncomingRequestCfPropertiesBotManagementBase (line 4232) | interface IncomingRequestCfPropertiesBotManagementBase {
  type IncomingRequestCfPropertiesBotManagement (line 4259) | interface IncomingRequestCfPropertiesBotManagement {
  type IncomingRequestCfPropertiesBotManagementEnterprise (line 4271) | interface IncomingRequestCfPropertiesBotManagementEnterprise extends Inc...
  type IncomingRequestCfPropertiesCloudflareForSaaSEnterprise (line 4283) | interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMet...
  type IncomingRequestCfPropertiesCloudflareAccessOrApiShield (line 4292) | interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield {
  type IncomingRequestCfPropertiesExportedAuthenticatorMetadata (line 4312) | interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata {
  type IncomingRequestCfPropertiesGeographicInformation (line 4341) | interface IncomingRequestCfPropertiesGeographicInformation {
  type IncomingRequestCfPropertiesTLSClientAuth (line 4418) | interface IncomingRequestCfPropertiesTLSClientAuth {
  type IncomingRequestCfPropertiesTLSClientAuthPlaceholder (line 4511) | interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder {
  type CertVerificationStatus (line 4531) | type CertVerificationStatus =
  type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus (line 4549) | type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = 0 /** Unkno...
  type Iso3166Alpha2Code (line 4551) | type Iso3166Alpha2Code = "AD" | "AE" | "AF" | "AG" | "AI" | "AL" | "AM" ...
  type ContinentCode (line 4553) | type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA";
  type CfProperties (line 4554) | type CfProperties<HostMetadata = unknown> = IncomingRequestCfProperties<...
  type D1Meta (line 4555) | interface D1Meta {
  type D1Response (line 4578) | interface D1Response {
  type D1Result (line 4583) | type D1Result<T = unknown> = D1Response & {
  type D1ExecResult (line 4586) | interface D1ExecResult {
  type D1SessionConstraint (line 4590) | type D1SessionConstraint =
  type D1SessionBookmark (line 4599) | type D1SessionBookmark = string;
  type Disposable (line 4648) | interface Disposable {
  type EmailMessage (line 4653) | interface EmailMessage {
  type ForwardableEmailMessage (line 4666) | interface ForwardableEmailMessage extends EmailMessage {
  type SendEmail (line 4702) | interface SendEmail {
  type EmailExportedHandler (line 4708) | type EmailExportedHandler<Env = unknown> = (message: ForwardableEmailMes...
  type Hyperdrive (line 4716) | interface Hyperdrive {
  type ImageInfoResponse (line 4766) | type ImageInfoResponse = {
  type ImageTransform (line 4774) | type ImageTransform = {
  type ImageDrawOptions (line 4815) | type ImageDrawOptions = {
  type ImageOutputOptions (line 4823) | type ImageOutputOptions = {
  type ImagesBinding (line 4828) | interface ImagesBinding {
  type ImageTransformer (line 4842) | interface ImageTransformer {
  type ImageTransformationResult (line 4863) | interface ImageTransformationResult {
  type ImagesError (line 4877) | interface ImagesError extends Error {
  type Params (line 4882) | type Params<P extends string = any> = Record<P, string | string[]>;
  type EventContext (line 4883) | type EventContext<Env, P extends string, Data> = {
  type PagesFunction (line 4897) | type PagesFunction<Env = unknown, Params extends string = any, Data exte...
  type EventPluginContext (line 4898) | type EventPluginContext<Env, P extends string, Data, PluginArgs> = {
  type PagesPluginFunction (line 4913) | type PagesPluginFunction<Env = unknown, Params extends string = any, Dat...
  type PipelineRecord (line 4934) | type PipelineRecord = Record<string, unknown>;
  type PipelineBatchMetadata (line 4935) | type PipelineBatchMetadata = {
  type Pipeline (line 4939) | interface Pipeline<T extends PipelineRecord = PipelineRecord> {
  type PubSubMessage (line 4952) | interface PubSubMessage {
  type JsonWebKeyWithKid (line 4978) | interface JsonWebKeyWithKid extends JsonWebKey {
  type RateLimitOptions (line 4982) | interface RateLimitOptions {
  type RateLimitOutcome (line 4985) | interface RateLimitOutcome {
  type RateLimit (line 4988) | interface RateLimit {
  type RpcTargetBranded (line 5009) | interface RpcTargetBranded {
  type WorkerEntrypointBranded (line 5012) | interface WorkerEntrypointBranded {
  type DurableObjectBranded (line 5015) | interface DurableObjectBranded {
  type WorkflowEntrypointBranded (line 5018) | interface WorkflowEntrypointBranded {
  type EntrypointBranded (line 5021) | type EntrypointBranded = WorkerEntrypointBranded | DurableObjectBranded ...
  type Stubable (line 5023) | type Stubable = RpcTargetBranded | ((...args: any[]) => any);
  type Serializable (line 5028) | type Serializable<T> =
  type StubBase (line 5041) | interface StubBase<T extends Stubable> extends Disposable {
  type Stub (line 5045) | type Stub<T extends Stubable> = Provider<T> & StubBase<T>;
  type BaseType (line 5047) | type BaseType = void | undefined | null | boolean | number | bigint | st...
  type Stubify (line 5050) | type Stubify<T> = T extends Stubable ? Stub<T> : T extends Map<infer K, ...
  type Unstubify (line 5059) | type Unstubify<T> = T extends StubBase<infer V> ? V : T extends Map<infe...
  type UnstubifyAll (line 5064) | type UnstubifyAll<A extends any[]> = {
  type MaybeProvider (line 5069) | type MaybeProvider<T> = T extends object ? Provider<T> : unknown;
  type MaybeDisposable (line 5070) | type MaybeDisposable<T> = T extends object ? Disposable : unknown;
  type Result (line 5079) | type Result<R> = R extends Stubable ? Promise<Stub<R>> & Provider<R> : R...
  type MethodOrProperty (line 5085) | type MethodOrProperty<V> = V extends (...args: infer P) => infer R ? (.....
  type MaybeCallableProvider (line 5088) | type MaybeCallableProvider<T> = T extends (...args: any[]) => any ? Meth...
  type Provider (line 5092) | type Provider<T extends object, Reserved extends string = never> = Maybe...
  type Env (line 5097) | interface Env {
  type RpcStub (line 5101) | type RpcStub<T extends Rpc.Stubable> = Rpc.Stub<T>;
  type WorkflowDurationLabel (line 5132) | type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'wee...
  type WorkflowSleepDuration (line 5133) | type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ...
  type WorkflowDelayDuration (line 5134) | type WorkflowDelayDuration = WorkflowSleepDuration;
  type WorkflowTimeoutDuration (line 5135) | type WorkflowTimeoutDuration = WorkflowSleepDuration;
  type WorkflowBackoff (line 5136) | type WorkflowBackoff = 'constant' | 'linear' | 'exponential';
  type WorkflowStepConfig (line 5137) | type WorkflowStepConfig = {
  type WorkflowEvent (line 5145) | type WorkflowEvent<T> = {
  type WorkflowStepEvent (line 5150) | type WorkflowStepEvent<T> = {
  type SecretsStoreSecret (line 5174) | interface SecretsStoreSecret {
  type Header (line 5186) | interface Header {
  type FetchEventInfo (line 5190) | interface FetchEventInfo {
  type JsRpcEventInfo (line 5197) | interface JsRpcEventInfo {
  type ScheduledEventInfo (line 5201) | interface ScheduledEventInfo {
  type AlarmEventInfo (line 5206) | interface AlarmEventInfo {
  type QueueEventInfo (line 5210) | interface QueueEventInfo {
  type EmailEventInfo (line 5215) | interface EmailEventInfo {
  type TraceEventInfo (line 5221) | interface TraceEventInfo {
  type HibernatableWebSocketEventInfoMessage (line 5225) | interface HibernatableWebSocketEventInfoMessage {
  type HibernatableWebSocketEventInfoError (line 5228) | interface HibernatableWebSocketEventInfoError {
  type HibernatableWebSocketEventInfoClose (line 5231) | interface HibernatableWebSocketEventInfoClose {
  type HibernatableWebSocketEventInfo (line 5236) | interface HibernatableWebSocketEventInfo {
  type Resume (line 5240) | interface Resume {
  type CustomEventInfo (line 5244) | interface CustomEventInfo {
  type FetchResponseInfo (line 5247) | interface FetchResponseInfo {
  type EventOutcome (line 5251) | type EventOutcome = "ok" | "canceled" | "exception" | "unknown" | "killS...
  type ScriptVersion (line 5252) | interface ScriptVersion {
  type Trigger (line 5257) | interface Trigger {
  type Onset (line 5262) | interface Onset {
  type Outcome (line 5272) | interface Outcome {
  type Hibernate (line 5278) | interface Hibernate {
  type SpanOpen (line 5281) | interface SpanOpen {
  type SpanClose (line 5286) | interface SpanClose {
  type DiagnosticChannelEvent (line 5290) | interface DiagnosticChannelEvent {
  type Exception (line 5295) | interface Exception {
  type Log (line 5301) | interface Log {
  type Return (line 5306) | interface Return {
  type Link (line 5310) | interface Link {
  type Attribute (line 5317) | interface Attribute {
  type Mark (line 5322) | type Mark = DiagnosticChannelEvent | Exception | Log | Return | Link | A...
  type TailEvent (line 5323) | interface TailEvent {
  type TailEventHandler (line 5331) | type TailEventHandler = (event: TailEvent) => void | Promise<void>;
  type TailEventHandlerName (line 5332) | type TailEventHandlerName = "onset" | "outcome" | "hibernate" | "spanOpe...
  type TailEventHandlerObject (line 5333) | type TailEventHandlerObject = Record<TailEventHandlerName, TailEventHand...
  type TailEventHandlerType (line 5334) | type TailEventHandlerType = TailEventHandler | TailEventHandlerObject;
  type VectorizeVectorMetadataValue (line 5342) | type VectorizeVectorMetadataValue = string | number | boolean | string[];
  type VectorizeVectorMetadata (line 5346) | type VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record<str...
  type VectorFloatArray (line 5347) | type VectorFloatArray = Float32Array | Float64Array;
  type VectorizeError (line 5348) | interface VectorizeError {
  type VectorizeVectorMetadataFilterOp (line 5357) | type VectorizeVectorMetadataFilterOp = "$eq" | "$ne";
  type VectorizeVectorMetadataFilter (line 5361) | type VectorizeVectorMetadataFilter = {
  type VectorizeDistanceMetric (line 5370) | type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product";
  type VectorizeMetadataRetrievalLevel (line 5380) | type VectorizeMetadataRetrievalLevel = "all" | "indexed" | "none";
  type VectorizeQueryOptions (line 5381) | interface VectorizeQueryOptions {
  type VectorizeIndexConfig (line 5391) | type VectorizeIndexConfig = {
  type VectorizeIndexDetails (line 5403) | interface VectorizeIndexDetails {
  type VectorizeIndexInfo (line 5418) | interface VectorizeIndexInfo {
  type VectorizeVector (line 5431) | interface VectorizeVector {
  type VectorizeMatch (line 5444) | type VectorizeMatch = Pick<Partial<VectorizeVector>, "values"> & Omit<Ve...
  type VectorizeMatches (line 5451) | interface VectorizeMatches {
  type VectorizeVectorMutation (line 5462) | interface VectorizeVectorMutation {
  type VectorizeAsyncMutation (line 5472) | interface VectorizeAsyncMutation {
  type WorkerVersionMetadata (line 5574) | type WorkerVersionMetadata = {
  type DynamicDispatchLimits (line 5582) | interface DynamicDispatchLimits {
  type DynamicDispatchOptions (line 5592) | interface DynamicDispatchOptions {
  type DispatchNamespace (line 5604) | interface DispatchNamespace {
  class NonRetryableError (line 5621) | class NonRetryableError extends Error {
  type WorkflowInstanceCreateOptions (line 5646) | interface WorkflowInstanceCreateOptions<PARAMS = unknown> {
  type InstanceStatus (line 5656) | type InstanceStatus = {
  type WorkflowError (line 5665) | interface WorkflowError {
Condensed preview — 87 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (470K chars).
[
  {
    "path": ".gitattributes",
    "chars": 66,
    "preview": "# Auto detect text files and perform LF normalization\n* text=auto\n"
  },
  {
    "path": ".gitignore",
    "chars": 326,
    "preview": "# build output\ndist/\n_worker.bundle\n\n# generated types\n.astro/\n.wrangler/\n\n# dependencies\nnode_modules/\n\n# logs\nnpm-debu"
  },
  {
    "path": "LICENSE",
    "chars": 34503,
    "preview": "GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software "
  },
  {
    "path": "astro.config.ts",
    "chars": 735,
    "preview": "import { defineConfig } from \"astro/config\";\n\n// astro integrations\nimport compress from \"astro-compress\";\nimport icon f"
  },
  {
    "path": "functions/_middleware.js",
    "chars": 575,
    "preview": "async function RequestInfo (context) {\n    const Path = (new URL(context.request.url)).pathname;\n    console.info(\"[Main"
  },
  {
    "path": "functions/internal/Converter/getClashMetaConfig.js",
    "chars": 4860,
    "preview": "import { TrulyAssign } from \"../utils/TrulyAssign\";\nimport { parseYAML } from \"confbox\";\nimport ClashMetaDumper from \".."
  },
  {
    "path": "functions/internal/Converter/getSingBoxConfig.ts",
    "chars": 9635,
    "preview": "import { TrulyAssign } from \"../utils/TrulyAssign\";\nimport SingBoxDumper from \"../Dumpers/sing-box.js\";\nimport { MetaToS"
  },
  {
    "path": "functions/internal/Dumpers/clash-meta.ts",
    "chars": 9904,
    "preview": "import type { RealityConfig, TransportGRPC, TransportH2, TransportHTTP, TransportWS } from \"../types/ClashMetaConfig\";\n\n"
  },
  {
    "path": "functions/internal/Dumpers/share-link.js",
    "chars": 2789,
    "preview": "export class ShareLinkDumper {\n    constructor () {\n        return true;\n    }\n\n    __validate (ProxyObject) {\n        i"
  },
  {
    "path": "functions/internal/Dumpers/sing-box.js",
    "chars": 9888,
    "preview": "export default class Dumper {\n    config = {}\n    constructor (\n        UDP = true,\n        SSUoT = false,\n        SkipC"
  },
  {
    "path": "functions/internal/Parsers/clash-meta.js",
    "chars": 6025,
    "preview": "export class ClashMetaParser {\n    constructor () {}\n\n    __validate (ProxyObject) {\n        if (!(ProxyObject.type in t"
  },
  {
    "path": "functions/internal/Parsers/share-link.js",
    "chars": 6824,
    "preview": "export class ShareLinkParser {\n    constructor () {}\n\n    __validate (URI) {\n        if (!(URI.split(\":\")[0] in this)) {"
  },
  {
    "path": "functions/internal/Parsers/sing-box.js",
    "chars": 6872,
    "preview": "export class SingBoxParser {\n    constructor () {}\n\n    __validate (ProxyObject) {\n        if (!(ProxyObject.type in thi"
  },
  {
    "path": "functions/internal/RuleProviderReader/Readers/ini.js",
    "chars": 2615,
    "preview": "import { parseINI } from \"confbox\";\n\nimport { fetchCached } from \"../../utils/fetchCached.js\";\n\nexport async function in"
  },
  {
    "path": "functions/internal/RuleProviderReader/main.js",
    "chars": 1254,
    "preview": "import { ini } from \"./Readers/ini.js\"\n\nexport class RuleProviderReader {\n    RuleProvider = {};\n    Reader = {\n        "
  },
  {
    "path": "functions/internal/configs.ts",
    "chars": 135,
    "preview": "export const DefaultRequestHeaders = {\n    \"Accept\": \"*/*\",\n    \"User-Agent\": \"EdgeSub-git/0.0.0 (Prefer ClashMeta / Mih"
  },
  {
    "path": "functions/internal/data/rule/MetaToSingLogicalRule.ts",
    "chars": 3995,
    "preview": "import { MetaToSingRuleMapping } from \"./MetaToSingMapping\";\nimport { transformGeoRef } from \"../ruleset/transformGeoRef"
  },
  {
    "path": "functions/internal/data/rule/MetaToSingMapping.ts",
    "chars": 1366,
    "preview": "// mihomo src rule syntax\n// <TYPE>, <PAYLOAD>, <OUTBOUND>, <Additional Parameters>\n// note: headless rule doesnt need t"
  },
  {
    "path": "functions/internal/data/ruleset/transformGeoRef.ts",
    "chars": 1226,
    "preview": "export type headlessRuleSet = {\n    type: \"remote\",\n    tag: string,\n    url: string,\n    format: \"binary\" | \"source\",\n}"
  },
  {
    "path": "functions/internal/getParsedSubData.ts",
    "chars": 7440,
    "preview": "import type { ClashMetaConfig } from \"./types/ClashMetaConfig\";\n\nimport { DefaultRequestHeaders } from \"./configs\";\n\nimp"
  },
  {
    "path": "functions/internal/types/ClashMetaConfig.ts",
    "chars": 1462,
    "preview": "// reference: https://wiki.metacubex.one/\n\ntype ClashMetaProxyGroup = {\n    name: string;\n    type: string; // head to h"
  },
  {
    "path": "functions/internal/utils/TrulyAssign.js",
    "chars": 552,
    "preview": "/**\n * Assign source to target, note that its only for the first frame. \n * You will not get the target modified, instea"
  },
  {
    "path": "functions/internal/utils/fetchCached.ts",
    "chars": 1348,
    "preview": "export async function fetchCached (URL: URL, Prefix = \"Cached\", CacheDB: KVNamespace, isForcedRefresh = false) {\n    // "
  },
  {
    "path": "functions/internal/utils/parseContentDisposition.ts",
    "chars": 965,
    "preview": "export function parseContentDisposition(RawContentDispositionHeader: string): string {\n    if (!RawContentDispositionHea"
  },
  {
    "path": "functions/internal/utils/removeUndefinedFields.ts",
    "chars": 313,
    "preview": "export function removeUndefinedFields (obj: object) : object {\n    for (const key in obj) {\n        if (typeof obj[key] "
  },
  {
    "path": "functions/ruleset/preprocessor/sing-box.ts",
    "chars": 1587,
    "preview": "import { fetchCached } from \"../../internal/utils/fetchCached.js\";\nimport { MetaToSingRuleMapping } from \"functions/inte"
  },
  {
    "path": "functions/ruleset/proxy.ts",
    "chars": 645,
    "preview": "import { fetchCached } from \"../internal/utils/fetchCached.js\";\n\nexport async function onRequest (context) {\n    const {"
  },
  {
    "path": "functions/short/admin-password/set.ts",
    "chars": 2427,
    "preview": "import { getDefaultHeader, getOptionsHeader } from \"../utils/defaultHeader\";\nimport { sha256 } from \"js-sha256\";\n\nexport"
  },
  {
    "path": "functions/short/admin-password/status.ts",
    "chars": 541,
    "preview": "import { getDefaultHeader, getOptionsHeader } from \"../utils/defaultHeader\";\n\nexport async function onRequest (context) "
  },
  {
    "path": "functions/short/delete/[id].ts",
    "chars": 1936,
    "preview": "import { getDefaultHeader, getOptionsHeader } from \"../utils/defaultHeader\";\n\nexport async function onRequestDelete (con"
  },
  {
    "path": "functions/short/get/[id].ts",
    "chars": 829,
    "preview": "import { getDefaultHeader } from \"../utils/defaultHeader\";\n\nexport async function onRequest (context) {\n    const { id }"
  },
  {
    "path": "functions/short/list.ts",
    "chars": 2230,
    "preview": "import { getDefaultHeader, getOptionsHeader } from \"./utils/defaultHeader\";\nimport { sha256 } from \"js-sha256\";\n\nexport "
  },
  {
    "path": "functions/short/put.ts",
    "chars": 2117,
    "preview": "import { getDefaultHeader, getOptionsHeader } from \"./utils/defaultHeader\";\n\nexport async function onRequestPost (contex"
  },
  {
    "path": "functions/short/token-reset/[id].ts",
    "chars": 2045,
    "preview": "import { getDefaultHeader, getOptionsHeader } from \"../utils/defaultHeader\";\n\nexport async function onRequestPatch (cont"
  },
  {
    "path": "functions/short/utils/defaultHeader.ts",
    "chars": 769,
    "preview": "export const getDefaultHeader = (url: URL) => { \n    return {\n        \"Access-Control-Allow-Origin\": getAllowedOriginHea"
  },
  {
    "path": "functions/sub/base64.js",
    "chars": 165,
    "preview": "import { onRequest as ShareLinkOnRequest } from \"./share-link.js\";\n\nexport async function onRequest (context) {\n    retu"
  },
  {
    "path": "functions/sub/clash-meta.js",
    "chars": 3038,
    "preview": "import { getClashMetaConfig } from \"../internal/Converter/getClashMetaConfig.js\";\nimport getParsedSubData from \"../inter"
  },
  {
    "path": "functions/sub/debug.js",
    "chars": 767,
    "preview": "import getParsedSubData from \"../internal/getParsedSubData.ts\";\n\nexport async function onRequest (context) {\n    const {"
  },
  {
    "path": "functions/sub/share-link.js",
    "chars": 1201,
    "preview": "import getParsedSubData from \"../internal/getParsedSubData.ts\";\nimport { ShareLinkDumper } from \"../internal/Dumpers/sha"
  },
  {
    "path": "functions/sub/sing-box.js",
    "chars": 2032,
    "preview": "import { getSingBoxConfig } from \"../internal/Converter/getSingBoxConfig.ts\";\nimport getParsedSubData from \"../internal/"
  },
  {
    "path": "package.json",
    "chars": 1021,
    "preview": "{\n  \"name\": \"edge-sub\",\n  \"type\": \"module\",\n  \"version\": \"1.0.0\",\n  \"license\": \"AGPL-3\",\n  \"author\": \"kobe-koto\",\n  \"hom"
  },
  {
    "path": "public/basic-config/mihomo.yaml",
    "chars": 834,
    "preview": "auto-detect-interface: true\nlog-level: \"info\"\n\nport: 7890\nmixed-port: 7891\n\nmode: \"Rule\"\nexternal-controller: \":9090\"\n\n\n"
  },
  {
    "path": "public/basic-config/sing-box.jsonc",
    "chars": 2800,
    "preview": "{\n    \"log\": {\n        \"disabled\": false,\n        \"level\": \"info\"\n    },\n    \"dns\": {\n        \"servers\": [\n            {"
  },
  {
    "path": "public/minimal_remote_rules.ini",
    "chars": 356,
    "preview": ";https://raw.githubusercontent.com/kobe-koto/EdgeSub/main/public/minimal_remote_rules.ini\n\n[custom]\nruleset=Proxies,[]DO"
  },
  {
    "path": "readme.md",
    "chars": 6125,
    "preview": "# Edge Sub\n\n在 CloudFlare 的全球網絡上轉換您的代理訂閱.\n\n請為我點一個 ⭐ Star!\n\n## 使用方式\n\n- ### UI\n  \n  在 Cloudflare Pages 部署後打開,並按提示操作。\n\n- ###"
  },
  {
    "path": "src/components/NavBar.astro",
    "chars": 2140,
    "preview": "---\nimport { Icon } from \"astro-icon/components\";\n---\n\n<div class=\"navbar bg-base-100 shadow-sm mx-auto max-w-5xl rounde"
  },
  {
    "path": "src/components/backendIndicator.astro",
    "chars": 568,
    "preview": "---\nimport { Icon } from \"astro-icon/components\";\n---\n\n<div role=\"alert\" class=\"alert bg-base-300 my-4\">\n    <Icon name="
  },
  {
    "path": "src/components/data-input.astro",
    "chars": 2013,
    "preview": "---\nimport type { DropdownItemPrototype } from \"@components/k-dropdown.astro\";\nimport KDropdown from \"@components/k-drop"
  },
  {
    "path": "src/components/index/SubURLGenerator.astro",
    "chars": 4181,
    "preview": "---\nimport DataInput from \"@components/data-input.astro\";\nimport { Icon } from \"astro-icon/components\";\nimport type { Dr"
  },
  {
    "path": "src/components/k-dropdown.astro",
    "chars": 959,
    "preview": "---\nimport { Icon } from \"astro-icon/components\";\n\nexport type DropdownItemPrototype = { key: string; value: string };\n\n"
  },
  {
    "path": "src/components/layouts/SEOComponent.astro",
    "chars": 941,
    "preview": "---\nimport { SEO } from \"astro-seo\";\n\ninterface Props {\n    Title?: string;\n    Desc?: string;\n    noindex?: boolean;\n}\n"
  },
  {
    "path": "src/components/shorter/k-shorter.astro",
    "chars": 1545,
    "preview": "---\nimport DataInput from \"@components/data-input.astro\";\nimport { Icon } from \"astro-icon/components\";\n---\n\n<k-shorter "
  },
  {
    "path": "src/components/shorter/short-destroyer.astro",
    "chars": 958,
    "preview": "---\nimport DataInput from \"@components/data-input.astro\";\nimport { Icon } from \"astro-icon/components\";\n---\n\n<short-dest"
  },
  {
    "path": "src/components/shorter/short-editor.astro",
    "chars": 1722,
    "preview": "---\nimport DataInput from \"@components/data-input.astro\";\nimport { Icon } from \"astro-icon/components\";\n---\n\n<short-edit"
  },
  {
    "path": "src/components/shorter/short-token-reset.astro",
    "chars": 1179,
    "preview": "---\nimport DataInput from \"@components/data-input.astro\";\nimport { Icon } from \"astro-icon/components\";\n---\n\n<short-toke"
  },
  {
    "path": "src/components/shorter/shorter-list.astro",
    "chars": 1946,
    "preview": "---\nimport DataInput from \"@components/data-input.astro\";\nimport { Icon } from \"astro-icon/components\";\n---\n\n<shorter-li"
  },
  {
    "path": "src/components/shorter/shorter-password.astro",
    "chars": 1139,
    "preview": "---\nimport DataInput from \"@components/data-input.astro\";\nimport { Icon } from \"astro-icon/components\";\n---\n\n<shorter-pa"
  },
  {
    "path": "src/config/AvalibleOptoutFormat.ts",
    "chars": 1419,
    "preview": "import { readdirSync } from \"node:fs\";\nexport type EndpointExtendConfigPrototype = \"RuleProvider\" | \"RuleProvidersProxy\""
  },
  {
    "path": "src/config/RuleProviders.ts",
    "chars": 2529,
    "preview": "type RuleProvider = {\n    key: string;\n    value: string | URL;\n}\n\nexport const RuleProviders: RuleProvider[] = [\n    {\n"
  },
  {
    "path": "src/env.d.ts",
    "chars": 84,
    "preview": "/// <reference path=\"../.astro/types.d.ts\" />\n/// <reference types=\"astro/client\" />"
  },
  {
    "path": "src/layouts/base.astro",
    "chars": 776,
    "preview": "---\nimport \"@styles/import.css\";\nimport SEOComponent from \"@components/layouts/SEOComponent.astro\";\ninterface Props {\n\tn"
  },
  {
    "path": "src/pages/index.astro",
    "chars": 218,
    "preview": "---\nimport Base from \"@layouts/base.astro\";\n\nimport SubURLGenerator from \"@components/index/SubURLGenerator.astro\";\n//im"
  },
  {
    "path": "src/pages/shorter/admin.astro",
    "chars": 3291,
    "preview": "---\nimport Base from \"@layouts/base.astro\";\nimport { Icon } from \"astro-icon/components\";\nimport BackendIndicator from \""
  },
  {
    "path": "src/pages/shorter/create.astro",
    "chars": 295,
    "preview": "---\nimport Base from \"@layouts/base.astro\";\nimport BackendIndicator from \"@components/backendIndicator.astro\";\n\nimport K"
  },
  {
    "path": "src/pages/shorter/destory.astro",
    "chars": 319,
    "preview": "---\nimport Base from \"@layouts/base.astro\";\nimport BackendIndicator from \"@components/backendIndicator.astro\";\n\nimport S"
  },
  {
    "path": "src/pages/shorter/edit.astro",
    "chars": 296,
    "preview": "---\nimport Base from \"@layouts/base.astro\";\nimport BackendIndicator from \"@components/backendIndicator.astro\";\n\nimport S"
  },
  {
    "path": "src/pages/shorter/list.astro",
    "chars": 307,
    "preview": "---\nimport Base from \"@layouts/base.astro\";\nimport BackendIndicator from \"@components/backendIndicator.astro\";\n\nimport S"
  },
  {
    "path": "src/pages/shorter/reset-token.astro",
    "chars": 338,
    "preview": "---\nimport Base from \"@layouts/base.astro\";\nimport BackendIndicator from \"@components/backendIndicator.astro\";\n\nimport S"
  },
  {
    "path": "src/scripts/components/data-input.ts",
    "chars": 2906,
    "preview": "import type { Dropdown } from \"@scripts/components/k-dropdown\";\n\nexport class DataInput extends HTMLElement {\n    type ="
  },
  {
    "path": "src/scripts/components/k-dropdown.ts",
    "chars": 1893,
    "preview": "export class Dropdown extends HTMLElement {\n    constructor () {\n        super();\n        \n        this.initializeElemen"
  },
  {
    "path": "src/scripts/components/k-suburl-generator.ts",
    "chars": 7644,
    "preview": "import type { DataInput } from \"@scripts/components/data-input\";\nimport type { EndpointExtendConfigPrototype, EndpointPr"
  },
  {
    "path": "src/scripts/components/shorter/k-shorter.ts",
    "chars": 2834,
    "preview": "import type { DataInput } from \"../data-input\";\nimport { getDefaultBackend } from \"@scripts/utils/getDefaultBackend\";\n\ne"
  },
  {
    "path": "src/scripts/components/shorter/short-destroyer.ts",
    "chars": 1757,
    "preview": "import type { DataInput } from \"../data-input\";\nimport { getDefaultBackend } from \"@scripts/utils/getDefaultBackend\";\n\ne"
  },
  {
    "path": "src/scripts/components/shorter/short-editor.ts",
    "chars": 3076,
    "preview": "import type { DataInput } from \"../data-input\";\nimport { getDefaultBackend } from \"@scripts/utils/getDefaultBackend\";\n\ne"
  },
  {
    "path": "src/scripts/components/shorter/short-token-reset.ts",
    "chars": 1931,
    "preview": "import type { DataInput } from \"../data-input\";\nimport { getDefaultBackend } from \"@scripts/utils/getDefaultBackend\";\n\ne"
  },
  {
    "path": "src/scripts/components/shorter/shorter-list.ts",
    "chars": 3923,
    "preview": "import type { DataInput } from \"../data-input\";\nimport { getDefaultBackend } from \"@scripts/utils/getDefaultBackend\";\n\ne"
  },
  {
    "path": "src/scripts/components/shorter/shorter-password.ts",
    "chars": 2157,
    "preview": "import type { DataInput } from \"../data-input\";\nimport { getDefaultBackend } from \"@scripts/utils/getDefaultBackend\";\n\ne"
  },
  {
    "path": "src/scripts/utils/copy.ts",
    "chars": 356,
    "preview": "export function copyToClipboard(text: string) {\n    return new Promise((resolve, reject) => {\n        if (!navigator.cli"
  },
  {
    "path": "src/scripts/utils/filterObject.ts",
    "chars": 899,
    "preview": "/**\n * Generic “object filter”.  Works exactly like Array.filter,\n * but the callback receives (key, value) instead of ("
  },
  {
    "path": "src/scripts/utils/getDefaultBackend.ts",
    "chars": 246,
    "preview": "export function getDefaultBackend () {\n    let URLObj = new URL(location.href);\n    URLObj.pathname = \"\";\n    URLObj.sea"
  },
  {
    "path": "src/styles/app.scss",
    "chars": 42,
    "preview": "@import \"tailwindcss\";\n@plugin \"daisyui\";\n"
  },
  {
    "path": "src/styles/import.css",
    "chars": 1410,
    "preview": "@import \"tailwindcss\";\n@plugin \"daisyui\" {\n    themes: \"LightMint\" --default;/* dark --prefersdark;*/\n}\n\n\n@plugin \"daisy"
  },
  {
    "path": "src/styles/index.scss",
    "chars": 685,
    "preview": ".main-card-con {\n    box-sizing: border-box;\n    width: 100%;\n    min-height: 100vh;\n    padding: 20px 0;\n    background"
  },
  {
    "path": "src/styles/main.scss",
    "chars": 919,
    "preview": "\n\n// body {\n//     margin: 0;\n//     font-family: \"Roboto\", sans-serif, system-ui;\n// }\n// button {\n//     width: 100%;\n"
  },
  {
    "path": "tsconfig.json",
    "chars": 400,
    "preview": "{\n  \"extends\": \"astro/tsconfigs/base\",\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"typeRoots\": [\"./types\", \"./node_m"
  },
  {
    "path": "types/worker-configuration.d.ts",
    "chars": 235001,
    "preview": "// Generated by Wrangler by running `wrangler types ./types/worker-configuration.d.ts` (hash: 2569fdb35d6c7f3f62093f7ff8"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the kobe-koto/EdgeSub GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 87 files (435.9 KB), approximately 106.3k tokens, and a symbol index with 642 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!