commit c1640c1754c4cd73507af1c638f28e72c94b688d Author: nihil carcosa Date: Sun Nov 3 17:41:45 2024 +0100 Initial commit diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..642bf8d --- /dev/null +++ b/LICENSE @@ -0,0 +1,232 @@ +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is 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. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +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. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +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 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. Use with the GNU Affero General Public License. +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 Affero 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 special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU 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 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 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 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. + + homepage + Copyright (C) 2024 valhrafnaz + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU 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 General Public License for more details. + + You should have received a copy of the GNU General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: + + homepage Copyright (C) 2024 valhrafnaz + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”. + +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 GPL, see . + +The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . diff --git a/README.md b/README.md new file mode 100644 index 0000000..10c69f5 --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# homepage + +this repo contains all the source files for my homepage + +for just the template parts: [homepage-template](https://git.valhrafnaz.gay/valhrafnaz/homepage-templates) \ No newline at end of file diff --git a/eleventy.config.cjs b/eleventy.config.cjs new file mode 100644 index 0000000..e6fbc82 --- /dev/null +++ b/eleventy.config.cjs @@ -0,0 +1,23 @@ +module.exports = async function(eleventyConfig) { + // Input directory: src + // Output directory: _site + eleventyConfig.addWatchTarget("tailwind.config.js"); + eleventyConfig.addWatchTarget(".src/**/*/*.css"); + + eleventyConfig.addFilter("truncatewords", function (str = "", limit = 30) { + return str.toString() + .trim() + .split(/\s+/g, limit) + .join(" ") + "…"; + }); + + eleventyConfig.addPassthroughCopy("src/**/*/tailwind.css"); + eleventyConfig.addPassthroughCopy("src/assets/img"); + eleventyConfig.addPassthroughCopy("src/scripts/"); + eleventyConfig.addPassthroughCopy("src/**/*.{png, jpeg, jpg, avif, gif}"); + eleventyConfig.addPassthroughCopy("src/**/*.{ttf,otf,woff}"); +}; +module.exports.config = { + markdownTemplateEngine: "njk", + htmlTemplateEngine: 'njk', +}; \ No newline at end of file diff --git a/node_modules/.bin/acorn b/node_modules/.bin/acorn new file mode 120000 index 0000000..cf76760 --- /dev/null +++ b/node_modules/.bin/acorn @@ -0,0 +1 @@ +../acorn/bin/acorn \ No newline at end of file diff --git a/node_modules/.bin/autoprefixer b/node_modules/.bin/autoprefixer new file mode 120000 index 0000000..e876d81 --- /dev/null +++ b/node_modules/.bin/autoprefixer @@ -0,0 +1 @@ +../autoprefixer/bin/autoprefixer \ No newline at end of file diff --git a/node_modules/.bin/browserslist b/node_modules/.bin/browserslist new file mode 120000 index 0000000..3cd991b --- /dev/null +++ b/node_modules/.bin/browserslist @@ -0,0 +1 @@ +../browserslist/cli.js \ No newline at end of file diff --git a/node_modules/.bin/cssesc b/node_modules/.bin/cssesc new file mode 120000 index 0000000..487b689 --- /dev/null +++ b/node_modules/.bin/cssesc @@ -0,0 +1 @@ +../cssesc/bin/cssesc \ No newline at end of file diff --git a/node_modules/.bin/dev-ip b/node_modules/.bin/dev-ip new file mode 120000 index 0000000..138e5ac --- /dev/null +++ b/node_modules/.bin/dev-ip @@ -0,0 +1 @@ +../dev-ip/lib/dev-ip.js \ No newline at end of file diff --git a/node_modules/.bin/eleventy b/node_modules/.bin/eleventy new file mode 120000 index 0000000..996774d --- /dev/null +++ b/node_modules/.bin/eleventy @@ -0,0 +1 @@ +../@11ty/eleventy/cmd.cjs \ No newline at end of file diff --git a/node_modules/.bin/eleventy-dev-server b/node_modules/.bin/eleventy-dev-server new file mode 120000 index 0000000..31a8419 --- /dev/null +++ b/node_modules/.bin/eleventy-dev-server @@ -0,0 +1 @@ +../@11ty/eleventy-dev-server/cmd.js \ No newline at end of file diff --git a/node_modules/.bin/errno b/node_modules/.bin/errno new file mode 120000 index 0000000..5a98e53 --- /dev/null +++ b/node_modules/.bin/errno @@ -0,0 +1 @@ +../errno/cli.js \ No newline at end of file diff --git a/node_modules/.bin/esparse b/node_modules/.bin/esparse new file mode 120000 index 0000000..7423b18 --- /dev/null +++ b/node_modules/.bin/esparse @@ -0,0 +1 @@ +../esprima/bin/esparse.js \ No newline at end of file diff --git a/node_modules/.bin/esvalidate b/node_modules/.bin/esvalidate new file mode 120000 index 0000000..16069ef --- /dev/null +++ b/node_modules/.bin/esvalidate @@ -0,0 +1 @@ +../esprima/bin/esvalidate.js \ No newline at end of file diff --git a/node_modules/.bin/glob b/node_modules/.bin/glob new file mode 120000 index 0000000..85c9c1d --- /dev/null +++ b/node_modules/.bin/glob @@ -0,0 +1 @@ +../glob/dist/esm/bin.mjs \ No newline at end of file diff --git a/node_modules/.bin/jiti b/node_modules/.bin/jiti new file mode 120000 index 0000000..031ee3f --- /dev/null +++ b/node_modules/.bin/jiti @@ -0,0 +1 @@ +../jiti/bin/jiti.js \ No newline at end of file diff --git a/node_modules/.bin/js-yaml b/node_modules/.bin/js-yaml new file mode 120000 index 0000000..9dbd010 --- /dev/null +++ b/node_modules/.bin/js-yaml @@ -0,0 +1 @@ +../js-yaml/bin/js-yaml.js \ No newline at end of file diff --git a/node_modules/.bin/liquid b/node_modules/.bin/liquid new file mode 120000 index 0000000..b06ee5f --- /dev/null +++ b/node_modules/.bin/liquid @@ -0,0 +1 @@ +../liquidjs/bin/liquid.js \ No newline at end of file diff --git a/node_modules/.bin/liquidjs b/node_modules/.bin/liquidjs new file mode 120000 index 0000000..b06ee5f --- /dev/null +++ b/node_modules/.bin/liquidjs @@ -0,0 +1 @@ +../liquidjs/bin/liquid.js \ No newline at end of file diff --git a/node_modules/.bin/markdown-it b/node_modules/.bin/markdown-it new file mode 120000 index 0000000..8a64108 --- /dev/null +++ b/node_modules/.bin/markdown-it @@ -0,0 +1 @@ +../markdown-it/bin/markdown-it.mjs \ No newline at end of file diff --git a/node_modules/.bin/mime b/node_modules/.bin/mime new file mode 120000 index 0000000..fbb7ee0 --- /dev/null +++ b/node_modules/.bin/mime @@ -0,0 +1 @@ +../mime/cli.js \ No newline at end of file diff --git a/node_modules/.bin/mkdirp b/node_modules/.bin/mkdirp new file mode 120000 index 0000000..0fd5193 --- /dev/null +++ b/node_modules/.bin/mkdirp @@ -0,0 +1 @@ +../mkdirp/dist/cjs/src/bin.js \ No newline at end of file diff --git a/node_modules/.bin/nanoid b/node_modules/.bin/nanoid new file mode 120000 index 0000000..e2be547 --- /dev/null +++ b/node_modules/.bin/nanoid @@ -0,0 +1 @@ +../nanoid/bin/nanoid.cjs \ No newline at end of file diff --git a/node_modules/.bin/node-which b/node_modules/.bin/node-which new file mode 120000 index 0000000..6f8415e --- /dev/null +++ b/node_modules/.bin/node-which @@ -0,0 +1 @@ +../which/bin/node-which \ No newline at end of file diff --git a/node_modules/.bin/npm-run-all b/node_modules/.bin/npm-run-all new file mode 120000 index 0000000..0424f3c --- /dev/null +++ b/node_modules/.bin/npm-run-all @@ -0,0 +1 @@ +../npm-run-all/bin/npm-run-all/index.js \ No newline at end of file diff --git a/node_modules/.bin/nunjucks-precompile b/node_modules/.bin/nunjucks-precompile new file mode 120000 index 0000000..3465a52 --- /dev/null +++ b/node_modules/.bin/nunjucks-precompile @@ -0,0 +1 @@ +../nunjucks/bin/precompile \ No newline at end of file diff --git a/node_modules/.bin/pidtree b/node_modules/.bin/pidtree new file mode 120000 index 0000000..42c3f06 --- /dev/null +++ b/node_modules/.bin/pidtree @@ -0,0 +1 @@ +../pidtree/bin/pidtree.js \ No newline at end of file diff --git a/node_modules/.bin/resolve b/node_modules/.bin/resolve new file mode 120000 index 0000000..b6afda6 --- /dev/null +++ b/node_modules/.bin/resolve @@ -0,0 +1 @@ +../resolve/bin/resolve \ No newline at end of file diff --git a/node_modules/.bin/rimraf b/node_modules/.bin/rimraf new file mode 120000 index 0000000..7e2fc27 --- /dev/null +++ b/node_modules/.bin/rimraf @@ -0,0 +1 @@ +../rimraf/dist/esm/bin.mjs \ No newline at end of file diff --git a/node_modules/.bin/run-p b/node_modules/.bin/run-p new file mode 120000 index 0000000..98a2c9c --- /dev/null +++ b/node_modules/.bin/run-p @@ -0,0 +1 @@ +../npm-run-all/bin/run-p/index.js \ No newline at end of file diff --git a/node_modules/.bin/run-s b/node_modules/.bin/run-s new file mode 120000 index 0000000..5938622 --- /dev/null +++ b/node_modules/.bin/run-s @@ -0,0 +1 @@ +../npm-run-all/bin/run-s/index.js \ No newline at end of file diff --git a/node_modules/.bin/semver b/node_modules/.bin/semver new file mode 120000 index 0000000..5aaadf4 --- /dev/null +++ b/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver.js \ No newline at end of file diff --git a/node_modules/.bin/sucrase b/node_modules/.bin/sucrase new file mode 120000 index 0000000..0ac7e77 --- /dev/null +++ b/node_modules/.bin/sucrase @@ -0,0 +1 @@ +../sucrase/bin/sucrase \ No newline at end of file diff --git a/node_modules/.bin/sucrase-node b/node_modules/.bin/sucrase-node new file mode 120000 index 0000000..8b96fae --- /dev/null +++ b/node_modules/.bin/sucrase-node @@ -0,0 +1 @@ +../sucrase/bin/sucrase-node \ No newline at end of file diff --git a/node_modules/.bin/tailwind b/node_modules/.bin/tailwind new file mode 120000 index 0000000..d497797 --- /dev/null +++ b/node_modules/.bin/tailwind @@ -0,0 +1 @@ +../tailwindcss/lib/cli.js \ No newline at end of file diff --git a/node_modules/.bin/tailwindcss b/node_modules/.bin/tailwindcss new file mode 120000 index 0000000..d497797 --- /dev/null +++ b/node_modules/.bin/tailwindcss @@ -0,0 +1 @@ +../tailwindcss/lib/cli.js \ No newline at end of file diff --git a/node_modules/.bin/update-browserslist-db b/node_modules/.bin/update-browserslist-db new file mode 120000 index 0000000..b11e16f --- /dev/null +++ b/node_modules/.bin/update-browserslist-db @@ -0,0 +1 @@ +../update-browserslist-db/cli.js \ No newline at end of file diff --git a/node_modules/.bin/yaml b/node_modules/.bin/yaml new file mode 120000 index 0000000..0368324 --- /dev/null +++ b/node_modules/.bin/yaml @@ -0,0 +1 @@ +../yaml/bin.mjs \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..3990af3 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,4516 @@ +{ + "name": "eleventy", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@11ty/dependency-tree": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@11ty/dependency-tree/-/dependency-tree-3.0.1.tgz", + "integrity": "sha512-aZizxcL4Z/clm3KPRx8i9ohW9R2gLssXfUSy7qQmQRXb4CUOyvmqk2gKeJqRmXIfMi2bB9w03SgtN5v1YwqpiA==", + "license": "MIT", + "dependencies": { + "@11ty/eleventy-utils": "^1.0.2" + } + }, + "node_modules/@11ty/dependency-tree-esm": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@11ty/dependency-tree-esm/-/dependency-tree-esm-1.0.0.tgz", + "integrity": "sha512-Z3KN1Fkv50UM/ZzTR3VBbyOY52HnmhIVCsAV1hn2UzFsGAjyF1Cw8uohhVtheDOSuBR7ZSeo1unwkz1HxFlUtQ==", + "license": "MIT", + "dependencies": { + "@11ty/eleventy-utils": "^1.0.2", + "acorn": "^8.10.0", + "dependency-graph": "^0.11.0", + "normalize-path": "^3.0.0" + } + }, + "node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/dependency-graph/-/dependency-graph-0.11.0.tgz", + "integrity": "sha512-JeMq7fEshyepOWDfcfHK06N3MhyPhz++vtqWhMT5O9A3K42rdsEDpfdVqjaqaAhsw6a+ZqeDvQVtD0hFHQWrzg==", + "license": "MIT", + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/@11ty/eleventy": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@11ty/eleventy/-/eleventy-3.0.0.tgz", + "integrity": "sha512-0P0ZsJXVW2QiNdhd7z+GYy6n+ivh0enx1DRdua5ta6NlzY2AhbkeWBY6U+FKA8lPS3H4+XsTpfLLfIScpPZLaQ==", + "license": "MIT", + "dependencies": { + "@11ty/dependency-tree": "^3.0.1", + "@11ty/dependency-tree-esm": "^1.0.0", + "@11ty/eleventy-dev-server": "^2.0.4", + "@11ty/eleventy-plugin-bundle": "^3.0.0", + "@11ty/eleventy-utils": "^1.0.3", + "@11ty/lodash-custom": "^4.17.21", + "@11ty/posthtml-urls": "^1.0.0", + "@11ty/recursive-copy": "^3.0.0", + "@sindresorhus/slugify": "^2.2.1", + "bcp-47-normalize": "^2.3.0", + "chardet": "^2.0.0", + "chokidar": "^3.6.0", + "cross-spawn": "^7.0.3", + "debug": "^4.3.7", + "dependency-graph": "^1.0.0", + "entities": "^5.0.0", + "fast-glob": "^3.3.2", + "filesize": "^10.1.6", + "graceful-fs": "^4.2.11", + "gray-matter": "^4.0.3", + "is-glob": "^4.0.3", + "iso-639-1": "^3.1.3", + "js-yaml": "^4.1.0", + "kleur": "^4.1.5", + "liquidjs": "^10.17.0", + "luxon": "^3.5.0", + "markdown-it": "^14.1.0", + "micromatch": "^4.0.8", + "minimist": "^1.2.8", + "moo": "^0.5.2", + "node-retrieve-globals": "^6.0.0", + "normalize-path": "^3.0.0", + "nunjucks": "^3.2.4", + "please-upgrade-node": "^3.2.0", + "posthtml": "^0.16.6", + "posthtml-match-helper": "^2.0.2", + "semver": "^7.6.3", + "slugify": "^1.6.6" + }, + "bin": { + "eleventy": "cmd.cjs" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + } + }, + "node_modules/@11ty/eleventy-dev-server": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@11ty/eleventy-dev-server/-/eleventy-dev-server-2.0.4.tgz", + "integrity": "sha512-d0CuufX6yPtVz+RW0oJZg1pVoxo1jOrPmpXYacoiKLJm0MMC9MkPQOCXlimguHVaceHejFo5+aZB9/aGB2RR0A==", + "license": "MIT", + "dependencies": { + "@11ty/eleventy-utils": "^1.0.3", + "chokidar": "^3.6.0", + "debug": "^4.3.7", + "dev-ip": "^1.0.1", + "finalhandler": "^1.3.0", + "mime": "^3.0.0", + "minimist": "^1.2.8", + "morphdom": "^2.7.4", + "please-upgrade-node": "^3.2.0", + "send": "^0.19.0", + "ssri": "^11.0.0", + "urlpattern-polyfill": "^10.0.0", + "ws": "^8.18.0" + }, + "bin": { + "eleventy-dev-server": "cmd.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + } + }, + "node_modules/@11ty/eleventy-plugin-bundle": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@11ty/eleventy-plugin-bundle/-/eleventy-plugin-bundle-3.0.0.tgz", + "integrity": "sha512-JSnqehT+sWSPi6e44jTXUW+KiV9284YF9fzPQvfGB4cXlk/m/SJk17CavHCleIvKXDN+jrUw9TZkwAwr85ONWQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.4", + "posthtml-match-helper": "^2.0.2" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + } + }, + "node_modules/@11ty/eleventy-utils": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@11ty/eleventy-utils/-/eleventy-utils-1.0.3.tgz", + "integrity": "sha512-nULO91om7vQw4Y/UBjM8i7nJ1xl+/nyK4rImZ41lFxiY2d+XUz7ChAj1CDYFjrLZeu0utAYJTZ45LlcHTkUG4g==", + "license": "MIT", + "dependencies": { + "normalize-path": "^3.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + } + }, + "node_modules/@11ty/lodash-custom": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/@11ty/lodash-custom/-/lodash-custom-4.17.21.tgz", + "integrity": "sha512-Mqt6im1xpb1Ykn3nbcCovWXK3ggywRJa+IXIdoz4wIIK+cvozADH63lexcuPpGS/gJ6/m2JxyyXDyupkMr5DHw==", + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + } + }, + "node_modules/@11ty/posthtml-urls": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@11ty/posthtml-urls/-/posthtml-urls-1.0.0.tgz", + "integrity": "sha512-CcsRdI933x613u7CjM+QGs7iD/m8SaDup3Apohg1+7dybigrEUHc2jGS3mcMgQKvF2+IphqmepD/FrKLlPkPEg==", + "license": "MIT", + "dependencies": { + "evaluate-value": "^2.0.0", + "http-equiv-refresh": "^2.0.1", + "list-to-array": "^1.1.0", + "object.entries": "^1.1.7", + "parse-srcset": "^1.0.2" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/@11ty/recursive-copy": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@11ty/recursive-copy/-/recursive-copy-3.0.0.tgz", + "integrity": "sha512-v1Mr7dWx5nk69/HRRtDHUYDV9N8+cE12IGiKSFOwML7HjOzUXwTP88e3cGuhqoVstkBil1ZEIaOB0KPP1zwqXA==", + "license": "ISC", + "dependencies": { + "errno": "^0.1.2", + "graceful-fs": "^4.2.11", + "junk": "^1.0.1", + "maximatch": "^0.1.0", + "mkdirp": "^3.0.1", + "pify": "^2.3.0", + "promise": "^7.0.1", + "rimraf": "^5.0.7", + "slash": "^1.0.0" + } + }, + "node_modules/@alloc/quick-lru": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", + "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.5.tgz", + "integrity": "sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/set-array": "^1.2.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.2.1.tgz", + "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz", + "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@sindresorhus/slugify": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@sindresorhus/slugify/-/slugify-2.2.1.tgz", + "integrity": "sha512-MkngSCRZ8JdSOCHRaYd+D01XhvU3Hjy6MGl06zhOk614hp9EOAp5gIkBeQg7wtmxpitU6eAL4kdiRMcJa2dlrw==", + "license": "MIT", + "dependencies": { + "@sindresorhus/transliterate": "^1.0.0", + "escape-string-regexp": "^5.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@sindresorhus/transliterate": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/transliterate/-/transliterate-1.6.0.tgz", + "integrity": "sha512-doH1gimEu3A46VX6aVxpHTeHrytJAG6HgdxntYnCFiIFHEM/ZGpG8KiZGBChchjQmG0XFIBL552kBTjVcMZXwQ==", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^5.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@tailwindcss/typography": { + "version": "0.5.15", + "resolved": "https://registry.npmjs.org/@tailwindcss/typography/-/typography-0.5.15.tgz", + "integrity": "sha512-AqhlCXl+8grUz8uqExv5OTtgpjuVIwFTSXTrh8y9/pw6q2ek7fJ+Y8ZEVw7EB2DCcuCOtEjf9w3+J3rzts01uA==", + "dev": true, + "license": "MIT", + "dependencies": { + "lodash.castarray": "^4.4.0", + "lodash.isplainobject": "^4.0.6", + "lodash.merge": "^4.6.2", + "postcss-selector-parser": "6.0.10" + }, + "peerDependencies": { + "tailwindcss": ">=3.0.0 || insiders || >=4.0.0-alpha.20" + } + }, + "node_modules/@tailwindcss/typography/node_modules/postcss-selector-parser": { + "version": "6.0.10", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.10.tgz", + "integrity": "sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/a-sync-waterfall": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/a-sync-waterfall/-/a-sync-waterfall-1.0.1.tgz", + "integrity": "sha512-RYTOHHdWipFUliRFMCS4X2Yn2X8M87V/OpSqWzKKOGhzqyUxzyVmhHDH9sAvG+ZuQf/TAOFsLCpMw09I1ufUnA==", + "license": "MIT" + }, + "node_modules/acorn": { + "version": "8.12.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.12.1.tgz", + "integrity": "sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg==", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.4", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz", + "integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==", + "license": "MIT", + "dependencies": { + "acorn": "^8.11.0" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "dev": true, + "license": "MIT" + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/arg": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", + "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==", + "dev": true, + "license": "MIT" + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "license": "Python-2.0" + }, + "node_modules/array-buffer-byte-length": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.1.tgz", + "integrity": "sha512-ahC5W1xgou+KTXix4sAO8Ki12Q+jf4i0+tmk3sC+zgcynshkHxzpXdImBehiUYKKKDwvfFiJl1tZt6ewscS1Mg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.5", + "is-array-buffer": "^3.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array-differ": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/array-differ/-/array-differ-1.0.0.tgz", + "integrity": "sha512-LeZY+DZDRnvP7eMuQ6LHfCzUGxAAIViUBliK24P3hWXL6y4SortgR6Nim6xrkfSLlmH0+k+9NYNwVC2s53ZrYQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/array-union": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", + "integrity": "sha512-Dxr6QJj/RdU/hCaBjOfxW+q6lyuVE6JFWIrAUpuOOhoJJoQ99cUn3igRaHVB5P9WrgFVN0FfArM3x0cueOU8ng==", + "license": "MIT", + "dependencies": { + "array-uniq": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/array-uniq": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", + "integrity": "sha512-MNha4BWQ6JbwhFhj03YK552f7cb3AzoE8SzeljgChvL1dl3IcvggXVz1DilzySZkCja+CXuZbdW7yATchWn8/Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/arraybuffer.prototype.slice": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.3.tgz", + "integrity": "sha512-bMxMKAjg13EBSVscxTaYA4mRc5t1UAXa2kXiGTNfZ079HIWXEkKmkgFrh/nJqamaLSrXO5H4WFFkPEaLJWbs3A==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.1", + "call-bind": "^1.0.5", + "define-properties": "^1.2.1", + "es-abstract": "^1.22.3", + "es-errors": "^1.2.1", + "get-intrinsic": "^1.2.3", + "is-array-buffer": "^3.0.4", + "is-shared-array-buffer": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/arrify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", + "integrity": "sha512-3CYzex9M9FGQjCGMGyi6/31c8GJbgb0qGyrx5HWxPd0aCwh4cB2YjMb2Xf9UuoogrMrlO9cTqnB5rI5GHZTcUA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/asap": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", + "integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==", + "license": "MIT" + }, + "node_modules/autoprefixer": { + "version": "10.4.20", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.20.tgz", + "integrity": "sha512-XY25y5xSv/wEoqzDyXXME4AFfkZI0P23z6Fs3YgymDnKJkCGOnkL0iTxCa85UTqaSgfcqyf3UA6+c7wUvx/16g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/autoprefixer" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "browserslist": "^4.23.3", + "caniuse-lite": "^1.0.30001646", + "fraction.js": "^4.3.7", + "normalize-range": "^0.1.2", + "picocolors": "^1.0.1", + "postcss-value-parser": "^4.2.0" + }, + "bin": { + "autoprefixer": "bin/autoprefixer" + }, + "engines": { + "node": "^10 || ^12 || >=14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/bcp-47": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/bcp-47/-/bcp-47-2.1.0.tgz", + "integrity": "sha512-9IIS3UPrvIa1Ej+lVDdDwO7zLehjqsaByECw0bu2RRGP73jALm6FYbzI5gWbgHLvNdkvfXB5YrSbocZdOS0c0w==", + "license": "MIT", + "dependencies": { + "is-alphabetical": "^2.0.0", + "is-alphanumerical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/bcp-47-match": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-2.0.3.tgz", + "integrity": "sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/bcp-47-normalize": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/bcp-47-normalize/-/bcp-47-normalize-2.3.0.tgz", + "integrity": "sha512-8I/wfzqQvttUFz7HVJgIZ7+dj3vUaIyIxYXaTRP1YWoSDfzt6TUmxaKZeuXR62qBmYr+nvuWINFRl6pZ5DlN4Q==", + "license": "MIT", + "dependencies": { + "bcp-47": "^2.0.0", + "bcp-47-match": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.24.2", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.24.2.tgz", + "integrity": "sha512-ZIc+Q62revdMcqC6aChtW4jz3My3klmCO1fEmINZY/8J3EpBg5/A/D0AKmBveUh6pgoeycoMkVMko84tuYS+Gg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "caniuse-lite": "^1.0.30001669", + "electron-to-chromium": "^1.5.41", + "node-releases": "^2.0.18", + "update-browserslist-db": "^1.1.1" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/call-bind": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/camelcase-css": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz", + "integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001676", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001676.tgz", + "integrity": "sha512-Qz6zwGCiPghQXGJvgQAem79esjitvJ+CxSbSQkW9H/UX5hg8XM88d4lp2W+MEQ81j+Hip58Il+jGVdazk1z9cw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/chalk/node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/chalk/node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/chalk/node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true, + "license": "MIT" + }, + "node_modules/chalk/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/chardet": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-2.0.0.tgz", + "integrity": "sha512-xVgPpulCooDjY6zH4m9YW3jbkaBe3FKIAvF5sj5t7aBNsVl2ljIE+xwJ4iNgiDZHFQvNIpjdKdVOQvvk5ZfxbQ==", + "license": "MIT" + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/commander": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-10.0.1.tgz", + "integrity": "sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "dev": true, + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/data-view-buffer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.1.tgz", + "integrity": "sha512-0lht7OugA5x3iJLOWFhWK/5ehONdprk0ISXqVFn/NFrDu+cuc8iADFrGQz5BnRK7LLU3JmkbXSxaqX+/mXYtUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.6", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/data-view-byte-length": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.1.tgz", + "integrity": "sha512-4J7wRJD3ABAzr8wP+OcIcqq2dlUKp4DVflx++hs5h5ZKydWMI6/D/fAot+yh6g2tHh8fLFTvNOaVN357NvSrOQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/data-view-byte-offset": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.0.tgz", + "integrity": "sha512-t/Ygsytq+R995EJ5PZlD4Cu56sWa8InXySaViRzw9apusqsOO2bQP+SbYzAhR0pFKoB+43lYy8rWban9JSuXnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.6", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/debug": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dependency-graph": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/dependency-graph/-/dependency-graph-1.0.0.tgz", + "integrity": "sha512-cW3gggJ28HZ/LExwxP2B++aiKxhJXMSIt9K48FOXQkm+vuG5gyatXnLsONRJdzO/7VfjDIiaOOa/bs4l464Lwg==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/dev-ip": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dev-ip/-/dev-ip-1.0.1.tgz", + "integrity": "sha512-LmVkry/oDShEgSZPNgqCIp2/TlqtExeGmymru3uCELnfyjY11IzpAproLYs+1X88fXO6DBoYP3ul2Xo2yz2j6A==", + "bin": { + "dev-ip": "lib/dev-ip.js" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/didyoumean": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", + "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/dlv": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz", + "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==", + "dev": true, + "license": "MIT" + }, + "node_modules/dom-serializer": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-1.4.1.tgz", + "integrity": "sha512-VHwB3KfrcOOkelEG2ZOfxqLZdfkil8PtJi4P8N2MMXucZq2yLp75ClViUlOVwyoHEDjYU433Aq+5zWP61+RGag==", + "license": "MIT", + "dependencies": { + "domelementtype": "^2.0.1", + "domhandler": "^4.2.0", + "entities": "^2.0.0" + }, + "funding": { + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/dom-serializer/node_modules/entities": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz", + "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==", + "license": "BSD-2-Clause", + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/domelementtype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "BSD-2-Clause" + }, + "node_modules/domhandler": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-4.3.1.tgz", + "integrity": "sha512-GrwoxYN+uWlzO8uhUXRl0P+kHE4GtVPfYzVLcUxPL7KNdHKj66vvlhiweIHqYYXWlw+T8iLMp42Lm67ghw4WMQ==", + "license": "BSD-2-Clause", + "dependencies": { + "domelementtype": "^2.2.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/domutils": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-2.8.0.tgz", + "integrity": "sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A==", + "license": "BSD-2-Clause", + "dependencies": { + "dom-serializer": "^1.0.1", + "domelementtype": "^2.2.0", + "domhandler": "^4.2.0" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "license": "MIT" + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/electron-to-chromium": { + "version": "1.5.50", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.50.tgz", + "integrity": "sha512-eMVObiUQ2LdgeO1F/ySTXsvqvxb6ZH2zPGaMYsWzRDdOddUa77tdmI0ltg+L16UpbWdhPmuF3wIQYyQq65WfZw==", + "dev": true, + "license": "ISC" + }, + "node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/entities": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-5.0.0.tgz", + "integrity": "sha512-BeJFvFRJddxobhvEdm5GqHzRV/X+ACeuw0/BuuxsCh1EUZcAIz8+kYmBp/LrQuloy6K1f3a0M7+IhmZ7QnkISA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/errno": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/errno/-/errno-0.1.8.tgz", + "integrity": "sha512-dJ6oBr5SQ1VSd9qkk7ByRgb/1SH4JZjCHSW/mr63/QcXO9zLVxvJ6Oy13nio03rxpSnVDDjFor75SjVeZWPW/A==", + "license": "MIT", + "dependencies": { + "prr": "~1.0.1" + }, + "bin": { + "errno": "cli.js" + } + }, + "node_modules/error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/es-abstract": { + "version": "1.23.3", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.23.3.tgz", + "integrity": "sha512-e+HfNH61Bj1X9/jLc5v1owaLYuHdeHHSQlkhCBiTK8rBvKaULl/beGMxwrMXjpYrv4pz22BlY570vVePA2ho4A==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.1", + "arraybuffer.prototype.slice": "^1.0.3", + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.7", + "data-view-buffer": "^1.0.1", + "data-view-byte-length": "^1.0.1", + "data-view-byte-offset": "^1.0.0", + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "es-set-tostringtag": "^2.0.3", + "es-to-primitive": "^1.2.1", + "function.prototype.name": "^1.1.6", + "get-intrinsic": "^1.2.4", + "get-symbol-description": "^1.0.2", + "globalthis": "^1.0.3", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2", + "has-proto": "^1.0.3", + "has-symbols": "^1.0.3", + "hasown": "^2.0.2", + "internal-slot": "^1.0.7", + "is-array-buffer": "^3.0.4", + "is-callable": "^1.2.7", + "is-data-view": "^1.0.1", + "is-negative-zero": "^2.0.3", + "is-regex": "^1.1.4", + "is-shared-array-buffer": "^1.0.3", + "is-string": "^1.0.7", + "is-typed-array": "^1.1.13", + "is-weakref": "^1.0.2", + "object-inspect": "^1.13.1", + "object-keys": "^1.1.1", + "object.assign": "^4.1.5", + "regexp.prototype.flags": "^1.5.2", + "safe-array-concat": "^1.1.2", + "safe-regex-test": "^1.0.3", + "string.prototype.trim": "^1.2.9", + "string.prototype.trimend": "^1.0.8", + "string.prototype.trimstart": "^1.0.8", + "typed-array-buffer": "^1.0.2", + "typed-array-byte-length": "^1.0.1", + "typed-array-byte-offset": "^1.0.2", + "typed-array-length": "^1.0.6", + "unbox-primitive": "^1.0.2", + "which-typed-array": "^1.1.15" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.0.0.tgz", + "integrity": "sha512-MZ4iQ6JwHOBQjahnjwaC1ZtIBH+2ohjamzAO3oaHcXYup7qxjF2fixyH+Q71voWHeOkI2q/TnJao/KfXYIZWbw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.3.tgz", + "integrity": "sha512-3T8uNMC3OQTHkFUsFq8r/BwAXLHvU/9O9mE0fBc/MY5iq/8H7ncvO947LmYA6ldWw9Uh8Yhf25zu6n7nML5QWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.2.4", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.1" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-to-primitive": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", + "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/escape-string-regexp": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz", + "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/esm-import-transformer": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/esm-import-transformer/-/esm-import-transformer-3.0.2.tgz", + "integrity": "sha512-PgvO0wro44lTDM9pYeeOIfpS0lGF80jA+rjT7sBd3b07rxv1AxeNMEI5kSCqRKke2W6SPEz17W3kHOLjaiD7Cw==", + "license": "MIT", + "dependencies": { + "acorn": "^8.11.2" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "license": "BSD-2-Clause", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/evaluate-value": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/evaluate-value/-/evaluate-value-2.0.0.tgz", + "integrity": "sha512-VonfiuDJc0z4sOO7W0Pd130VLsXN6vmBWZlrog1mCb/o7o/Nl5Lr25+Kj/nkCCAhG+zqeeGjxhkK9oHpkgTHhQ==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha512-zCnTtlxNoAiDc3gqY2aYAWFx7XWWiasuF2K8Me5WbN8otHKTUKBwjPtNpRs/rbUZm7KxWAaNj7P1a/p52GbVug==", + "license": "MIT", + "dependencies": { + "is-extendable": "^0.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/fast-glob": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz", + "integrity": "sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==", + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.4" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fastq": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.17.1.tgz", + "integrity": "sha512-sRVD3lWVIXWg6By68ZN7vho9a1pQcN/WBFaAAsDDFzlJjvoGx0P8z7V1t72grFJfJhu3YPZBuu25f7Kaw2jN1w==", + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/filesize": { + "version": "10.1.6", + "resolved": "https://registry.npmjs.org/filesize/-/filesize-10.1.6.tgz", + "integrity": "sha512-sJslQKU2uM33qH5nqewAwVB2QgR6w1aMNsYUp3aN5rMRyXEwJGmZvaWzeJFNTOXWlHQyBFCWrdj3fV/fsTOX8w==", + "license": "BSD-3-Clause", + "engines": { + "node": ">= 10.4.0" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", + "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/finalhandler/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/finalhandler/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/for-each": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", + "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-callable": "^1.1.3" + } + }, + "node_modules/foreground-child": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", + "integrity": "sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==", + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/fraction.js": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz", + "integrity": "sha512-ZsDfxO51wGAXREY55a7la9LScWpwv9RxIrYABrlvOFBlH/ShPnrtsXeuUIfXKKOVicNxQ+o8JTbJvjS4M89yew==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + }, + "funding": { + "type": "patreon", + "url": "https://github.com/sponsors/rawify" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/function.prototype.name": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.6.tgz", + "integrity": "sha512-Z5kx79swU5P27WEayXM1tBi5Ze/lbIyiNgU3qyXUOf9b2rgXYyF9Dy9Cx+IQv/Lc8WCG6L82zwUPpSS9hGehIg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1", + "functions-have-names": "^1.2.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-symbol-description": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.0.2.tgz", + "integrity": "sha512-g0QYk1dZBxGwk+Ngc+ltRH2IBp2f7zBkBMBJZCDerh6EhlhSR6+9irMCuT/09zD6qkarHUSn529sK/yL4S27mg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.5", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/glob": { + "version": "10.4.5", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", + "integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/glob/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC" + }, + "node_modules/gray-matter": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/gray-matter/-/gray-matter-4.0.3.tgz", + "integrity": "sha512-5v6yZd4JK3eMI3FqqCouswVqwugaA9r4dNZB1wwcmrD02QkV5H0y7XBQW8QwQqEaZY1pM9aqORSORhJRdNK44Q==", + "license": "MIT", + "dependencies": { + "js-yaml": "^3.13.1", + "kind-of": "^6.0.2", + "section-matter": "^1.0.0", + "strip-bom-string": "^1.0.0" + }, + "engines": { + "node": ">=6.0" + } + }, + "node_modules/gray-matter/node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/gray-matter/node_modules/js-yaml": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", + "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "license": "MIT", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/has-bigints": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz", + "integrity": "sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", + "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hosted-git-info": { + "version": "2.8.9", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz", + "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==", + "dev": true, + "license": "ISC" + }, + "node_modules/htmlparser2": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-7.2.0.tgz", + "integrity": "sha512-H7MImA4MS6cw7nbyURtLPO1Tms7C5H602LRETv95z1MxO/7CP7rDVROehUYeYBUYEON94NXXDEPmZuq+hX4sog==", + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "MIT", + "dependencies": { + "domelementtype": "^2.0.1", + "domhandler": "^4.2.2", + "domutils": "^2.8.0", + "entities": "^3.0.1" + } + }, + "node_modules/htmlparser2/node_modules/entities": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-3.0.1.tgz", + "integrity": "sha512-WiyBqoomrwMdFG1e0kqvASYfnlb0lp8M5o5Fw2OFq1hNZxxcNk8Ik0Xm7LxzBhuidnZB/UtBqVCgUz3kBOP51Q==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/http-equiv-refresh": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-equiv-refresh/-/http-equiv-refresh-2.0.1.tgz", + "integrity": "sha512-XJpDL/MLkV3dKwLzHwr2dY05dYNfBNlyPu4STQ8WvKCFdc6vC5tPXuq28of663+gHVg03C+16pHHs/+FmmDjcw==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/internal-slot": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.7.tgz", + "integrity": "sha512-NGnrKwXzSms2qUUih/ILZ5JBqNTSa1+ZmP6flaIp6KmSElgE9qdndzS3cqjrDovwFdmwsGsLdeFgB6suw+1e9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "hasown": "^2.0.0", + "side-channel": "^1.0.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-alphabetical": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz", + "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-alphanumerical": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz", + "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==", + "license": "MIT", + "dependencies": { + "is-alphabetical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.4.tgz", + "integrity": "sha512-wcjaerHw0ydZwfhiKbXJWLDY8A7yV7KhjQOpb83hGgGfId/aQa4TOvwyzn2PuswW2gPCYEL/nEAiSVpdOj1lXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "get-intrinsic": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-bigint": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.4.tgz", + "integrity": "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-bigints": "^1.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-boolean-object": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.2.tgz", + "integrity": "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-core-module": { + "version": "2.15.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.15.1.tgz", + "integrity": "sha512-z0vtXSwucUJtANQWldhbtbt7BnL0vxiFjIdDLAatwhDYty2bad6s+rijD6Ri4YuYJubLzIJLUidCh09e1djEVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-data-view": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.1.tgz", + "integrity": "sha512-AHkaJrsUVW6wq6JS8y3JnM/GJF/9cf+k20+iDzlSaJrinEo5+7vRiteOSwBhHRiAyQATN1AmY4hwzxJKPmYf+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-date-object": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", + "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-decimal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz", + "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-extendable": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", + "integrity": "sha512-5BMULNob1vgFX6EjQw5izWDxrecWK9AM72rugNr0TFldMOi0fj6Jk+zeKIt0xGj4cEfQIJth4w3OKWOJ4f+AFw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-json": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-json/-/is-json-2.0.1.tgz", + "integrity": "sha512-6BEnpVn1rcf3ngfmViLM6vjUjGErbdrL4rwlv+u1NO1XO8kqT4YGL8+19Q+Z/bas8tY90BTWMk2+fW1g6hQjbA==", + "license": "ISC" + }, + "node_modules/is-negative-zero": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz", + "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-number-object": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.7.tgz", + "integrity": "sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-regex": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", + "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.3.tgz", + "integrity": "sha512-nA2hv5XIhLR3uVzDDfCIknerhx8XUKnstuOERPNNIinXG7v9u+ohXF67vxm4TPTEPU6lm61ZkwP3c9PCB97rhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-string": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz", + "integrity": "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-symbol": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz", + "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.13.tgz", + "integrity": "sha512-uZ25/bUAlUY5fR4OKT4rZQEBrzQWYV9ZJYGGsUmEJ6thodVJ1HX64ePQ6Z0qPWP+m+Uq6e9UugrE38jeYsDSMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "which-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakref": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.0.2.tgz", + "integrity": "sha512-qctsuLZmIQ0+vSSMfoVvyFe2+GSEvnmZ2ezTup1SBse9+twCCeial6EEi3Nc2KFcf6+qz2FBPnjXsk8xhKSaPQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true, + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/iso-639-1": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/iso-639-1/-/iso-639-1-3.1.3.tgz", + "integrity": "sha512-1jz0Wh9hyLMRwqEPchb/KZCiTqfFWtc9R3nm7GHPygBAKS8wdKJ3FH4lvLsri6UtAE5Kz5SnowtXZa//6bqMyw==", + "license": "MIT", + "engines": { + "node": ">=6.0" + } + }, + "node_modules/jackspeak": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, + "node_modules/jiti": { + "version": "1.21.6", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.6.tgz", + "integrity": "sha512-2yTgeWTWzMWkHu6Jp9NKgePDaYHbntiwvYuuJLbbN9vl7DC9DvXKOB2BC3ZZ92D3cvV/aflH0osDfwpHepQ53w==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "bin/jiti.js" + } + }, + "node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/json-parse-better-errors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", + "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", + "dev": true, + "license": "MIT" + }, + "node_modules/junk": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/junk/-/junk-1.0.3.tgz", + "integrity": "sha512-3KF80UaaSSxo8jVnRYtMKNGFOoVPBdkkVPsw+Ad0y4oxKXPduS6G6iHkrf69yJVff/VAaYXkV42rtZ7daJxU3w==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/lilconfig": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-2.1.0.tgz", + "integrity": "sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true, + "license": "MIT" + }, + "node_modules/linkify-it": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.0.tgz", + "integrity": "sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ==", + "license": "MIT", + "dependencies": { + "uc.micro": "^2.0.0" + } + }, + "node_modules/liquidjs": { + "version": "10.17.0", + "resolved": "https://registry.npmjs.org/liquidjs/-/liquidjs-10.17.0.tgz", + "integrity": "sha512-M4MC5/nencttIJHirl5jFTkl7Yu+grIDLn3Qgl7BPAD3BsbTCQknDxlG5VXWRwslWIjk8lSZZjVq9LioILDk1Q==", + "license": "MIT", + "dependencies": { + "commander": "^10.0.0" + }, + "bin": { + "liquid": "bin/liquid.js", + "liquidjs": "bin/liquid.js" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/liquidjs" + } + }, + "node_modules/list-to-array": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/list-to-array/-/list-to-array-1.1.0.tgz", + "integrity": "sha512-+dAZZ2mM+/m+vY9ezfoueVvrgnHIGi5FvgSymbIgJOFwiznWyA59mav95L+Mc6xPtL3s9gm5eNTlNtxJLbNM1g==", + "license": "MIT" + }, + "node_modules/load-json-file": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", + "integrity": "sha512-Kx8hMakjX03tiGTLAIdJ+lL0htKnXjEZN6hk/tozf/WOuYGdZBJrZ+rCJRbVCugsjB3jMLn9746NsQIf5VjBMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.1.2", + "parse-json": "^4.0.0", + "pify": "^3.0.0", + "strip-bom": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/load-json-file/node_modules/pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha512-C3FsVNH1udSEX48gGX1xfvwTWfsYWj5U+8/uK15BGzIGrKoUpghX8hWZwa/OFnakBiiVNmBvemTJR5mcy7iPcg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/lodash.castarray": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/lodash.castarray/-/lodash.castarray-4.4.0.tgz", + "integrity": "sha512-aVx8ztPv7/2ULbArGJ2Y42bG1mEQ5mGjpdvrbJcJFU3TbYybe+QlLS4pst9zV52ymy2in1KpFPiZnAOATxD4+Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "license": "ISC" + }, + "node_modules/luxon": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/luxon/-/luxon-3.5.0.tgz", + "integrity": "sha512-rh+Zjr6DNfUYR3bPwJEnuwDdqMbxZW7LOQfUN4B54+Cl+0o5zaU9RJ6bcidfDtC1cWCZXQ+nvX8bf6bAji37QQ==", + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/markdown-it": { + "version": "14.1.0", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.0.tgz", + "integrity": "sha512-a54IwgWPaeBCAAsv13YgmALOF1elABB08FxO9i+r4VFk5Vl4pKokRPeX8u5TCgSsPi6ec1otfLjdOpVcgbpshg==", + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1", + "entities": "^4.4.0", + "linkify-it": "^5.0.0", + "mdurl": "^2.0.0", + "punycode.js": "^2.3.1", + "uc.micro": "^2.1.0" + }, + "bin": { + "markdown-it": "bin/markdown-it.mjs" + } + }, + "node_modules/markdown-it/node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/maximatch": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/maximatch/-/maximatch-0.1.0.tgz", + "integrity": "sha512-9ORVtDUFk4u/NFfo0vG/ND/z7UQCVZBL539YW0+U1I7H1BkZwizcPx5foFv7LCPcBnm2U6RjFnQOsIvN4/Vm2A==", + "license": "MIT", + "dependencies": { + "array-differ": "^1.0.0", + "array-union": "^1.0.1", + "arrify": "^1.0.0", + "minimatch": "^3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/mdurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.0.0.tgz", + "integrity": "sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==", + "license": "MIT" + }, + "node_modules/memorystream": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/memorystream/-/memorystream-0.3.1.tgz", + "integrity": "sha512-S3UwM3yj5mtUSEfP41UZmt/0SCoVYUcU1rkXv+BQ5Ig8ndL4sPoJNBUJERafdPb5jjHJGuMgytgKvKIf58XNBw==", + "dev": true, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mime": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz", + "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/mkdirp": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-3.0.1.tgz", + "integrity": "sha512-+NsyUUAZDmo6YVHzL/stxSu3t9YS1iljliy3BSDrXJ/dkn1KYdmtZODGGjLcc9XLgVVpH4KshHB8XmZgMhaBXg==", + "license": "MIT", + "bin": { + "mkdirp": "dist/cjs/src/bin.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/moo": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/moo/-/moo-0.5.2.tgz", + "integrity": "sha512-iSAJLHYKnX41mKcJKjqvnAN9sf0LMDTXDEvFv+ffuRR9a1MIuXLjMNL6EsnDHSkKLTWNqQQ5uo61P4EbU4NU+Q==", + "license": "BSD-3-Clause" + }, + "node_modules/morphdom": { + "version": "2.7.4", + "resolved": "https://registry.npmjs.org/morphdom/-/morphdom-2.7.4.tgz", + "integrity": "sha512-ATTbWMgGa+FaMU3FhnFYB6WgulCqwf6opOll4CBzmVDTLvPMmUPrEv8CudmLPK0MESa64+6B89fWOxP3+YIlxQ==", + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.7", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz", + "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/nice-try": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-releases": { + "version": "2.0.18", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.18.tgz", + "integrity": "sha512-d9VeXT4SJ7ZeOqGX6R5EM022wpL+eWPooLI+5UpWn2jCT1aosUQEhQP214x33Wkwx3JQMvIm+tIoVOdodFS40g==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-retrieve-globals": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/node-retrieve-globals/-/node-retrieve-globals-6.0.0.tgz", + "integrity": "sha512-VoEp6WMN/JcbBrJr6LnFE11kdzpKiBKNPFrHCEK2GgFWtiYpeL85WgcZpZFFnWxAU0O65+b+ipQAy4Oxy/+Pdg==", + "license": "MIT", + "dependencies": { + "acorn": "^8.1.3", + "acorn-walk": "^8.3.2", + "esm-import-transformer": "^3.0.2" + } + }, + "node_modules/normalize-package-data": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", + "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "hosted-git-info": "^2.1.4", + "resolve": "^1.10.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + } + }, + "node_modules/normalize-package-data/node_modules/semver": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", + "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/normalize-range": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/normalize-range/-/normalize-range-0.1.2.tgz", + "integrity": "sha512-bdok/XvKII3nUpklnV6P2hxtMNrCboOjAcyBuQnWEhO665FwrSNRxU+AqpsyvO6LgGYPspN+lu5CLtw4jPRKNA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npm-run-all": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/npm-run-all/-/npm-run-all-4.1.5.tgz", + "integrity": "sha512-Oo82gJDAVcaMdi3nuoKFavkIHBRVqQ1qvMb+9LHk/cF4P6B2m8aP04hGf7oL6wZ9BuGwX1onlLhpuoofSyoQDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^3.2.1", + "chalk": "^2.4.1", + "cross-spawn": "^6.0.5", + "memorystream": "^0.3.1", + "minimatch": "^3.0.4", + "pidtree": "^0.3.0", + "read-pkg": "^3.0.0", + "shell-quote": "^1.6.1", + "string.prototype.padend": "^3.0.0" + }, + "bin": { + "npm-run-all": "bin/npm-run-all/index.js", + "run-p": "bin/run-p/index.js", + "run-s": "bin/run-s/index.js" + }, + "engines": { + "node": ">= 4" + } + }, + "node_modules/npm-run-all/node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/npm-run-all/node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/npm-run-all/node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true, + "license": "MIT" + }, + "node_modules/npm-run-all/node_modules/cross-spawn": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + }, + "engines": { + "node": ">=4.8" + } + }, + "node_modules/npm-run-all/node_modules/path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/npm-run-all/node_modules/semver": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", + "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/npm-run-all/node_modules/shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha512-EV3L1+UQWGor21OmnvojK36mhg+TyIKDh3iFBKBohr5xeXIhNBcx8oWdgkTEEQ+BEFFYdLRuqMfd5L84N1V5Vg==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npm-run-all/node_modules/shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha512-wpoSFAxys6b2a2wHZ1XpDSgD7N9iVjg29Ph9uV/uaP9Ex/KXlkTZTeddxDPSYQpgvzKLGJke2UU0AzoGCjNIvQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npm-run-all/node_modules/which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "which": "bin/which" + } + }, + "node_modules/nunjucks": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/nunjucks/-/nunjucks-3.2.4.tgz", + "integrity": "sha512-26XRV6BhkgK0VOxfbU5cQI+ICFUtMLixv1noZn1tGU38kQH5A5nmmbk/O45xdyBhD1esk47nKrY0mvQpZIhRjQ==", + "license": "BSD-2-Clause", + "dependencies": { + "a-sync-waterfall": "^1.0.0", + "asap": "^2.0.3", + "commander": "^5.1.0" + }, + "bin": { + "nunjucks-precompile": "bin/precompile" + }, + "engines": { + "node": ">= 6.9.0" + }, + "peerDependencies": { + "chokidar": "^3.3.0" + }, + "peerDependenciesMeta": { + "chokidar": { + "optional": true + } + } + }, + "node_modules/nunjucks/node_modules/commander": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-5.1.0.tgz", + "integrity": "sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-hash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz", + "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/object-inspect": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz", + "integrity": "sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.5.tgz", + "integrity": "sha512-byy+U7gp+FVwmyzKPYhW2h5l3crpmGsxl7X2s8y43IgxvG4g3QZ6CffDtsNQy1WsmZpQbO+ybo0AlW7TY6DcBQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.5", + "define-properties": "^1.2.1", + "has-symbols": "^1.0.3", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.entries": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.8.tgz", + "integrity": "sha512-cmopxi8VwRIAw/fkijJohSfpef5PdN0pMQJN6VC/ZKvn0LIknWD8KtgY6KlQdEc4tIjcQ3HxSMmnvtzIscdaYQ==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "license": "BlueOak-1.0.0" + }, + "node_modules/parse-json": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", + "integrity": "sha512-aOIos8bujGN93/8Ox/jPLh7RwVnPEysynVFE+fQZyg6jKELEHwzgKdLRFHUgXJL6kylijVSBC4BvN9OmsB48Rw==", + "dev": true, + "license": "MIT", + "dependencies": { + "error-ex": "^1.3.1", + "json-parse-better-errors": "^1.0.1" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/parse-srcset": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/parse-srcset/-/parse-srcset-1.0.2.tgz", + "integrity": "sha512-/2qh0lav6CmI15FzA3i/2Bzk2zCgQhGMkvhOhKNcBVQ1ldgpbfiNTVslmooUmWJcADi1f1kIeynbDRVzNlfR6Q==", + "license": "MIT" + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-type": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz", + "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==", + "dev": true, + "license": "MIT", + "dependencies": { + "pify": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/path-type/node_modules/pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha512-C3FsVNH1udSEX48gGX1xfvwTWfsYWj5U+8/uK15BGzIGrKoUpghX8hWZwa/OFnakBiiVNmBvemTJR5mcy7iPcg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pidtree": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/pidtree/-/pidtree-0.3.1.tgz", + "integrity": "sha512-qQbW94hLHEqCg7nhby4yRC7G2+jYHY4Rguc2bjw7Uug4GIJuu1tvf2uHaZv5Q8zdt+WKJ6qK1FOI6amaWUo5FA==", + "dev": true, + "license": "MIT", + "bin": { + "pidtree": "bin/pidtree.js" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pirates": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.6.tgz", + "integrity": "sha512-saLsH7WeYYPiD25LDuLRRY/i+6HaPYr6G1OUlN39otzkSTxKnubR9RTxS3/Kk50s1g2JTgFwWQDQyplC5/SHZg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/please-upgrade-node": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/please-upgrade-node/-/please-upgrade-node-3.2.0.tgz", + "integrity": "sha512-gQR3WpIgNIKwBMVLkpMUeR3e1/E1y42bqDQZfql+kDeXd8COYfM8PQA4X6y7a8u9Ua9FHmsrrmirW2vHs45hWg==", + "license": "MIT", + "dependencies": { + "semver-compare": "^1.0.0" + } + }, + "node_modules/possible-typed-array-names": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.0.0.tgz", + "integrity": "sha512-d7Uw+eZoloe0EHDIYoe+bQ5WXnGMOpmiZFTuMWCwpjzzkL2nTjcKiAk4hh8TjnGye2TwWOk3UXucZ+3rbmBa8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/postcss": { + "version": "8.4.47", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.47.tgz", + "integrity": "sha512-56rxCq7G/XfB4EkXq9Egn5GCqugWvDFjafDOThIdMBsI15iqPqR5r15TfSr1YPYeEI19YeaXMCbY6u88Y76GLQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.7", + "picocolors": "^1.1.0", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-import": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-15.1.0.tgz", + "integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.0.0", + "read-cache": "^1.0.0", + "resolve": "^1.1.7" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "postcss": "^8.0.0" + } + }, + "node_modules/postcss-js": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/postcss-js/-/postcss-js-4.0.1.tgz", + "integrity": "sha512-dDLF8pEO191hJMtlHFPRa8xsizHaM82MLfNkUHdUtVEV3tgTp5oj+8qbEqYM57SLfc74KSbw//4SeJma2LRVIw==", + "dev": true, + "license": "MIT", + "dependencies": { + "camelcase-css": "^2.0.1" + }, + "engines": { + "node": "^12 || ^14 || >= 16" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + "peerDependencies": { + "postcss": "^8.4.21" + } + }, + "node_modules/postcss-load-config": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-4.0.2.tgz", + "integrity": "sha512-bSVhyJGL00wMVoPUzAVAnbEoWyqRxkjv64tUl427SKnPrENtq6hJwUojroMz2VB+Q1edmi4IfrAPpami5VVgMQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "lilconfig": "^3.0.0", + "yaml": "^2.3.4" + }, + "engines": { + "node": ">= 14" + }, + "peerDependencies": { + "postcss": ">=8.0.9", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "postcss": { + "optional": true + }, + "ts-node": { + "optional": true + } + } + }, + "node_modules/postcss-load-config/node_modules/lilconfig": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.2.tgz", + "integrity": "sha512-eop+wDAvpItUys0FWkHIKeC9ybYrTGbU41U5K7+bttZZeohvnY7M9dZ5kB21GNWiFT2q1OoPTvncPCgSOVO5ow==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/postcss-nested": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.2.0.tgz", + "integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^6.1.1" + }, + "engines": { + "node": ">=12.0" + }, + "peerDependencies": { + "postcss": "^8.2.14" + } + }, + "node_modules/postcss-selector-parser": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz", + "integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/posthtml": { + "version": "0.16.6", + "resolved": "https://registry.npmjs.org/posthtml/-/posthtml-0.16.6.tgz", + "integrity": "sha512-JcEmHlyLK/o0uGAlj65vgg+7LIms0xKXe60lcDOTU7oVX/3LuEuLwrQpW3VJ7de5TaFKiW4kWkaIpJL42FEgxQ==", + "license": "MIT", + "dependencies": { + "posthtml-parser": "^0.11.0", + "posthtml-render": "^3.0.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/posthtml-match-helper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/posthtml-match-helper/-/posthtml-match-helper-2.0.2.tgz", + "integrity": "sha512-ehnazjlSwcGa3P2LlFYmTmcnaembTSt9dLWIRRDVHDPidf6InWAr9leKeeLvUXgnU32g6BrFS64Je+c2Ld+l9g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "posthtml": "^0.16.6" + } + }, + "node_modules/posthtml-parser": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/posthtml-parser/-/posthtml-parser-0.11.0.tgz", + "integrity": "sha512-QecJtfLekJbWVo/dMAA+OSwY79wpRmbqS5TeXvXSX+f0c6pW4/SE6inzZ2qkU7oAMCPqIDkZDvd/bQsSFUnKyw==", + "license": "MIT", + "dependencies": { + "htmlparser2": "^7.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/posthtml-render": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/posthtml-render/-/posthtml-render-3.0.0.tgz", + "integrity": "sha512-z+16RoxK3fUPgwaIgH9NGnK1HKY9XIDpydky5eQGgAFVXTCSezalv9U2jQuNV+Z9qV1fDWNzldcw4eK0SSbqKA==", + "license": "MIT", + "dependencies": { + "is-json": "^2.0.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/promise": { + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/promise/-/promise-7.3.1.tgz", + "integrity": "sha512-nolQXZ/4L+bP/UGlkfaIujX9BKxGwmQ9OT4mOt5yvy8iK1h3wqTEJCijzGANTCCl9nWjY41juyAn2K3Q1hLLTg==", + "license": "MIT", + "dependencies": { + "asap": "~2.0.3" + } + }, + "node_modules/prr": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz", + "integrity": "sha512-yPw4Sng1gWghHQWj0B3ZggWUm4qVbPwPFcRG8KyxiU7J2OHFSoEHKS+EZ3fv5l1t9CyCiop6l/ZYeWbrgoQejw==", + "license": "MIT" + }, + "node_modules/punycode.js": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", + "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/read-cache": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", + "integrity": "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "pify": "^2.3.0" + } + }, + "node_modules/read-pkg": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz", + "integrity": "sha512-BLq/cCO9two+lBgiTYNqD6GdtK8s4NpaWrl6/rCO9w0TUS8oJl7cmToOZfRYllKTISY6nt1U7jQ53brmKqY6BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "load-json-file": "^4.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/regexp.prototype.flags": { + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.3.tgz", + "integrity": "sha512-vqlC04+RQoFalODCbCumG2xIOvapzVMHwsyIGM/SIE8fRhFFsXeH8/QQ+s0T0kDAhKc4k30s73/0ydkHQz6HlQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-errors": "^1.3.0", + "set-function-name": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve": { + "version": "1.22.8", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", + "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/reusify": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", + "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rimraf": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-5.0.10.tgz", + "integrity": "sha512-l0OE8wL34P4nJH/H2ffoaniAokM2qSmrtXHmlpvYr5AVVX8msAyW0l8NVJFDxlSK4u3Uh/f41cQheDVdnYijwQ==", + "license": "ISC", + "dependencies": { + "glob": "^10.3.7" + }, + "bin": { + "rimraf": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/safe-array-concat": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.2.tgz", + "integrity": "sha512-vj6RsCsWBCf19jIeHEfkRMw8DPiBb+DMXklQ/1SGDHOMlHdPUkZXFQ2YdplS23zESTijAcurb1aSgJA3AgMu1Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "get-intrinsic": "^1.2.4", + "has-symbols": "^1.0.3", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">=0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-regex-test": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.0.3.tgz", + "integrity": "sha512-CdASjNJPvRa7roO6Ra/gLYBTzYzzPyyBXxIMdGW3USQLyjWEls2RgW5UBTXaQVp+OrpeCK3bLem8smtmheoRuw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.6", + "es-errors": "^1.3.0", + "is-regex": "^1.1.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/section-matter": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/section-matter/-/section-matter-1.0.0.tgz", + "integrity": "sha512-vfD3pmTzGpufjScBh50YHKzEu2lxBWhVEHsNGoEXmCmn2hKGfeNLYMzCJpe8cD7gqX7TJluOVpBkAequ6dgMmA==", + "license": "MIT", + "dependencies": { + "extend-shallow": "^2.0.1", + "kind-of": "^6.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/semver": { + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/semver-compare": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz", + "integrity": "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==", + "license": "MIT" + }, + "node_modules/send": { + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.1.tgz", + "integrity": "sha512-p4rRk4f23ynFEfcD9LA0xRYngj+IyGiEYyqqOak8kaN0TvNmuxC2dcVeBn62GpCeR2CpWqyHCNScTP91QbAVFg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/send/node_modules/debug/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/send/node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-function-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz", + "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/shell-quote": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.1.tgz", + "integrity": "sha512-6j1W9l1iAs/4xYBI1SYOVZyFcCis9b4KCLQ8fgAGG07QvzaRLVVRQvAy85yNmmZSjYjg4MWh4gNvlPujU/5LpA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/slash": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-1.0.0.tgz", + "integrity": "sha512-3TYDR7xWt4dIqV2JauJr+EJeW356RXijHeUlO+8djJ+uBXPn8/2dpzBc8yQhh583sVvc9CvFAeQVgijsH+PNNg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/slugify": { + "version": "1.6.6", + "resolved": "https://registry.npmjs.org/slugify/-/slugify-1.6.6.tgz", + "integrity": "sha512-h+z7HKHYXj6wJU+AnS/+IH8Uh9fdcX1Lrhg1/VMdf9PwoBQXFcXiAdsy2tSK0P6gKwJLXp02r90ahUCqHk9rrw==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/spdx-correct": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.2.0.tgz", + "integrity": "sha512-kN9dJbvnySHULIluDHy32WHRUu3Og7B9sbY7tsFLctQkIqnMh3hErYgdMjTYuqmcXX+lK5T1lnUt3G7zNswmZA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/spdx-exceptions": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.5.0.tgz", + "integrity": "sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w==", + "dev": true, + "license": "CC-BY-3.0" + }, + "node_modules/spdx-expression-parse": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", + "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/spdx-license-ids": { + "version": "3.0.20", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.20.tgz", + "integrity": "sha512-jg25NiDV/1fLtSgEgyvVyDunvaNHbuwF9lfNV17gSmPFAlYzdfNBlLtLzXTevwkPj7DhGbmN9VnmJIgLnhvaBw==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "license": "BSD-3-Clause" + }, + "node_modules/ssri": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-11.0.0.tgz", + "integrity": "sha512-aZpUoMN/Jj2MqA4vMCeiKGnc/8SuSyHbGSBdgFbZxP8OJGF/lFkIuElzPxsN0q8TQQ+prw3P4EDfB3TBHHgfXw==", + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/string-width-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string.prototype.padend": { + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/string.prototype.padend/-/string.prototype.padend-3.1.6.tgz", + "integrity": "sha512-XZpspuSB7vJWhvJc9DLSlrXl1mcA2BdoY5jjnS135ydXqLoqhs96JjDtCkjJEQHvfqZIp9hBuBMgI589peyx9Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trim": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.9.tgz", + "integrity": "sha512-klHuCNxiMZ8MlsOihJhJEBJAiMVqU3Z2nEXWfWnIqjN0gEFS9J9+IxKozWWtQGcgoa1WUZzLjKPTr4ZHNFTFxw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.0", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimend": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.8.tgz", + "integrity": "sha512-p73uL5VCHCO2BZZ6krwwQE3kCzM7NKmis8S//xEC6fQonchbum4eP6kR4DLEjQFO3Wnj3Fuo8NM0kOSjVdHjZQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimstart": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz", + "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/strip-bom-string": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/strip-bom-string/-/strip-bom-string-1.0.0.tgz", + "integrity": "sha512-uCC2VHvQRYu+lMh4My/sFNmF2klFymLX1wHJeXnbEJERpV/ZsVuonzerjfrGpIGF7LBVa1O7i9kjiWvJiFck8g==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/sucrase": { + "version": "3.35.0", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.0.tgz", + "integrity": "sha512-8EbVDiu9iN/nESwxeSxDKe0dunta1GOlHufmSSXxMD2z2/tMZpDMpvXQGsc+ajGo8y2uYUmixaSRUc/QPoQ0GA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "glob": "^10.3.10", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/sucrase/node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tailwindcss": { + "version": "3.4.14", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.14.tgz", + "integrity": "sha512-IcSvOcTRcUtQQ7ILQL5quRDg7Xs93PdJEk1ZLbhhvJc7uj/OAhYOnruEiwnGgBvUtaUAJ8/mhSw1o8L2jCiENA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@alloc/quick-lru": "^5.2.0", + "arg": "^5.0.2", + "chokidar": "^3.5.3", + "didyoumean": "^1.2.2", + "dlv": "^1.1.3", + "fast-glob": "^3.3.0", + "glob-parent": "^6.0.2", + "is-glob": "^4.0.3", + "jiti": "^1.21.0", + "lilconfig": "^2.1.0", + "micromatch": "^4.0.5", + "normalize-path": "^3.0.0", + "object-hash": "^3.0.0", + "picocolors": "^1.0.0", + "postcss": "^8.4.23", + "postcss-import": "^15.1.0", + "postcss-js": "^4.0.1", + "postcss-load-config": "^4.0.1", + "postcss-nested": "^6.0.1", + "postcss-selector-parser": "^6.0.11", + "resolve": "^1.22.2", + "sucrase": "^3.32.0" + }, + "bin": { + "tailwind": "lib/cli.js", + "tailwindcss": "lib/cli.js" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tailwindcss/node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/ts-interface-checker": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", + "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/typed-array-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.2.tgz", + "integrity": "sha512-gEymJYKZtKXzzBzM4jqa9w6Q1Jjm7x2d+sh19AdsD4wqnMPDYyvwpsIc2Q/835kHuo3BEQ7CjelGhfTsoBb2MQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/typed-array-byte-length": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.1.tgz", + "integrity": "sha512-3iMJ9q0ao7WE9tWcaYKIptkNBuOIcZCCT0d4MRvuuH88fEoEH62IuQe0OtraD3ebQEoTRk8XCBoknUNc1Y67pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-proto": "^1.0.3", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-byte-offset": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.2.tgz", + "integrity": "sha512-Ous0vodHa56FviZucS2E63zkgtgrACj7omjwd/8lTEMEPFFyjfixMZ1ZXenpgCFBBt4EC1J2XsyVS2gkG0eTFA==", + "dev": true, + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-proto": "^1.0.3", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-length": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.6.tgz", + "integrity": "sha512-/OxDN6OtAk5KBpGb28T+HZc2M+ADtvRxXrKKbUwtsLgdoxgX13hyy7ek6bFRl5+aBs2yZzB0c4CnQfAtVypW/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-proto": "^1.0.3", + "is-typed-array": "^1.1.13", + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/uc.micro": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", + "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==", + "license": "MIT" + }, + "node_modules/unbox-primitive": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.2.tgz", + "integrity": "sha512-61pPlCD9h51VoreyJ0BReideM3MDKMKnh6+V9L08331ipq6Q8OFXZYiqP6n/tbHx4s5I9uRhcye6BrbkizkBDw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "has-bigints": "^1.0.2", + "has-symbols": "^1.0.3", + "which-boxed-primitive": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.1.tgz", + "integrity": "sha512-R8UzCaa9Az+38REPiJ1tXlImTJXlVfgHZsglwBD/k6nj76ctsH1E3q4doGrukiLQd3sGQYu56r5+lo5r94l29A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.0" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/urlpattern-polyfill": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/urlpattern-polyfill/-/urlpattern-polyfill-10.0.0.tgz", + "integrity": "sha512-H/A06tKD7sS1O1X2SshBVeA5FLycRpjqiBeqGKmBwBDBy28EnRjORxTNe269KSSr5un5qyWi1iL61wLxpd+ZOg==", + "license": "MIT" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/validate-npm-package-license": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/which-boxed-primitive": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", + "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-bigint": "^1.0.1", + "is-boolean-object": "^1.1.0", + "is-number-object": "^1.0.4", + "is-string": "^1.0.5", + "is-symbol": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-typed-array": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.15.tgz", + "integrity": "sha512-oV0jmFtUky6CXfkqehVvBP/LSWJ2sy4vWMioiENyJLePrBO/yKyV9OyJySfAKosh+RYkIl5zJCNZ8/4JncrpdA==", + "dev": true, + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ws": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz", + "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/yaml": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.6.0.tgz", + "integrity": "sha512-a6ae//JvKDEra2kdi1qzCyrJW/WZCgFi8ydDV+eXExl95t+5R+ijnqHJbz9tmMh8FUjx3iv2fCQ4dclAQlO2UQ==", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14" + } + } + } +} diff --git a/node_modules/@11ty/dependency-tree-esm/.github/workflows/ci.yml b/node_modules/@11ty/dependency-tree-esm/.github/workflows/ci.yml new file mode 100644 index 0000000..b675430 --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/.github/workflows/ci.yml @@ -0,0 +1,22 @@ +on: + push: + branches-ignore: + - "gh-pages" +jobs: + build: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: ["ubuntu-latest", "macos-latest", "windows-latest"] + node: ["16", "18", "20"] + name: Node.js ${{ matrix.node }} on ${{ matrix.os }} + steps: + - uses: actions/checkout@v3 + - name: Setup node + uses: actions/setup-node@v3 + with: + node-version: ${{ matrix.node }} + - run: npm install + - run: npm test +env: + YARN_GPG: no diff --git a/node_modules/@11ty/dependency-tree-esm/LICENSE b/node_modules/@11ty/dependency-tree-esm/LICENSE new file mode 100644 index 0000000..cb72e93 --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Zach Leatherman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@11ty/dependency-tree-esm/README.md b/node_modules/@11ty/dependency-tree-esm/README.md new file mode 100644 index 0000000..19484d2 --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/README.md @@ -0,0 +1,40 @@ +# `dependency-tree-esm` + +Returns an unordered array of local paths to dependencies of a Node ES module JavaScript file. + +* See also: [`dependency-tree`](https://github.com/11ty/eleventy-dependency-tree) for the CommonJS version. + +This is used by Eleventy to find dependencies of a JavaScript file to watch for changes to re-run Eleventy’s build. + +## Installation + +``` +npm install --save-dev @11ty/dependency-tree-esm +``` + +## Features + +* Ignores bare specifiers (e.g. `import "my-package"`) +* Ignores Node’s built-ins (e.g. `import "path"`) +* Handles circular dependencies +* Returns an empty set if the file does not exist. + +## Usage + +```js +// my-file.js + +// if my-local-dependency.js has dependencies, it will include those too +import "./my-local-dependency.js"; + + +// ignored, is a built-in +import path from "path"; +``` + +```js +const { find } = require("@11ty/dependency-tree-esm"); + +find("./my-file.js"); +// returns ["./my-local-dependency.js"] +``` diff --git a/node_modules/@11ty/dependency-tree-esm/main.js b/node_modules/@11ty/dependency-tree-esm/main.js new file mode 100644 index 0000000..0cbea2a --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/main.js @@ -0,0 +1,84 @@ +const path = require("path"); +const { existsSync } = require("fs"); +const { readFile } = require("fs/promises"); + +const acorn = require("acorn"); +const normalizePath = require("normalize-path"); +const { TemplatePath } = require("@11ty/eleventy-utils"); + +// Is *not* a bare specifier (e.g. 'some-package') +// https://nodejs.org/dist/latest-v18.x/docs/api/esm.html#terminology +function isNonBareSpecifier(importSource) { + // Change \\ to / on Windows + let normalized = normalizePath(importSource); + // Relative specifier (e.g. './startup.js') + if(normalized.startsWith("./") || normalized.startsWith("../")) { + return true; + } + // Absolute specifier (e.g. 'file:///opt/nodejs/config.js') + if(normalized.startsWith("file:")) { + return true; + } + + return false; +} + +function normalizeFilePath(filePath) { + return TemplatePath.standardizeFilePath(path.relative(".", filePath)); +} + +function normalizeImportSourceToFilePath(filePath, source) { + let { dir } = path.parse(filePath); + let normalized = path.join(dir, source); + return normalizeFilePath(normalized); +} + +async function findByContents(contents, filePath, alreadyParsedSet) { + // Should we use dependency-graph for these relationships? + let sources = new Set(); + + let ast = acorn.parse(contents, {sourceType: "module", ecmaVersion: "latest"}); + for(let node of ast.body) { + if(node.type === "ImportDeclaration" && isNonBareSpecifier(node.source.value)) { + let normalized = normalizeImportSourceToFilePath(filePath, node.source.value); + if(sources.has(normalized) || normalized === filePath) { + continue; + } + + sources.add(normalized); + } + } + + // Recurse for nested deps + for(let source of sources) { + let s = await find(source, alreadyParsedSet); + for(let p of s) { + if(sources.has(p) || p === filePath) { + continue; + } + + sources.add(p); + } + } + + return Array.from(sources); +} + +async function find(filePath, alreadyParsedSet = new Set()) { + // TODO add a cache here + // Unfortunately we need to read the entire file, imports need to be at the top level but they can be anywhere 🫠 + let normalized = normalizeFilePath(filePath); + if(alreadyParsedSet.has(normalized) || !existsSync(filePath)) { + return []; + } + alreadyParsedSet.add(normalized); + + let contents = await readFile(normalized, { encoding: 'utf8' }); + let sources = await findByContents(contents, normalized, alreadyParsedSet); + + return sources; +} + +module.exports = { + find +}; \ No newline at end of file diff --git a/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/CHANGELOG.md b/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/CHANGELOG.md new file mode 100755 index 0000000..5e6c4d9 --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/CHANGELOG.md @@ -0,0 +1,82 @@ +# Dependency Graph Changelog + +## 0.11.0 (March 5, 2021) + +- Add `entryNodes` method that returns the nodes that nothing depends on - thanks [amcdnl](https://github.com/amcdnl)! + +## 0.10.0 (January 9, 2021) + +- Add `directDependenciesOf` and `directDependantsOf` methods for retrieving direct dependency information. (Fixes #40) +- Add aliases `dependentsOf` and `directDependentsOf`. + +## 0.9.0 (February 10, 2020) + +- Rewrite the topological sort DFS to be more efficient (and work!) on large graphs. + - No longer uses recursion to avoid stack overflows with large/deep graphs + - No longer is accidentally `O(N^2)` (thanks [willtennien](https://github.com/willtennien) for pointing this out!) + +## 0.8.1 (December 3, 2019) + +- Ensure all nodes are included in overallOrder when cycles are allowed. (Fixes #33) + +## 0.8.0 (December 11, 2018) + +- Add a `DepGraphCycleError` with cyclePath property - thanks [jhugman](https://github.com/jhugman)! + +## 0.7.2 (August 30, 2018) + +- Make constructor parameter optional in Typescript definition. (Fixes #26) + +## 0.7.1 (June 5, 2018) + +- Fix Typescript definition to include the new constructor arguments added in `0.7.0` - thanks [tbranyen](https://github.com/tbranyen)! + +## 0.7.0 (January 17, 2018) + +- Allow circular dependencies by passing in `{circular: true}` into the constructor - thanks [tbranyen](https://github.com/tbranyen)! + +## 0.6.0 (October 22, 2017) + +- Add a `size` method that will return the number of nodes in the graph. +- Add a `clone` method that will clone the graph. Any custom node data will only be shallow-copied. (Fixes #14) + +## 0.5.2 (October 22, 2017) + +- Add missing parameter in TypeScript definition. (Fixes #19) + +## 0.5.1 (October 7, 2017) + +- Now exposes Typescript type definition - thanks [vangorra](https://github.com/vangorra)! + +## 0.5.0 (April 26, 2016) + +- Add optional data parameter for the addNode method. (Fixes #12) +- Add methods getNodeData and setNodeData to manipulate the data associated with a node name. (Fixes #12) +- Change the hasNode method to be able to cope with falsy node data. (Fixes #12) + +## 0.4.1 (Sept 3, 2015) + +- Check all nodes for potential cycles when calculating overall order. (Fixes #8) + +## 0.4.0 (Aug 1, 2015) + +- Better error messages + - When a cycle is detected, the error message will now include the cycle in it. E.g `Dependency Cycle Found: a -> b -> c -> a` (Fixes #7) + - When calling `addDependency` if one of the nodes does not exist, the error will say which one it was (instead of saying that "one" of the two nodes did not exist and making you manually determine which one) +- Calling `overallOrder` on an empty graph will no longer throw an error about a dependency cycle. It will return an empty array. + +## 0.3.0 (July 24, 2015) + +- Fix issue where if you call `addNode` twice with the same name, it would clear all edges for that node. Now it will do nothing if a node with the specified name already exists. (Fixes #3) + +## 0.2.1 (July 3, 2015) + +- Fixed removeNode leaving references in outgoingEdges and reference to non-existent var edges - thanks [juhoha](https://github.com/juhoha)! (Fixes #2) + +## 0.2.0 (May 1, 2015) + +- Removed dependency on Underscore - thanks [myndzi](https://github.com/myndzi)! (Fixes #1) + +## 0.1.0 (May 18, 2013) + +- Initial Release - extracted out of asset-smasher diff --git a/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/LICENSE b/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/LICENSE new file mode 100755 index 0000000..6ebe5b6 --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2013-2020 by Jim Riecken + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/README.md b/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/README.md new file mode 100755 index 0000000..763aaf8 --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/README.md @@ -0,0 +1,78 @@ +# Dependency Graph + +Simple dependency graph + +## Overview + +This is a simple dependency graph useful for determining the order to do a list of things that depend on certain items being done before they are. + +To use, `npm install dependency-graph` and then `require('dependency-graph').DepGraph` + +## API + +### DepGraph + +Nodes in the graph are just simple strings with optional data associated with them. + + - `addNode(name, data)` - add a node in the graph with optional data. If `data` is not given, `name` will be used as data + - `removeNode(name)` - remove a node from the graph + - `hasNode(name)` - check if a node exists in the graph + - `size()` - return the number of nodes in the graph + - `getNodeData(name)` - get the data associated with a node (will throw an `Error` if the node does not exist) + - `setNodeData(name, data)` - set the data for an existing node (will throw an `Error` if the node does not exist) + - `addDependency(from, to)` - add a dependency between two nodes (will throw an `Error` if one of the nodes does not exist) + - `removeDependency(from, to)` - remove a dependency between two nodes + - `clone()` - return a clone of the graph. Any data attached to the nodes will only be *shallow-copied* + - `dependenciesOf(name, leavesOnly)` - get an array containing the nodes that the specified node depends on (transitively). If `leavesOnly` is true, only nodes that do not depend on any other nodes will be returned in the array. + - `dependantsOf(name, leavesOnly)` (aliased as `dependentsOf`) - get an array containing the nodes that depend on the specified node (transitively). If `leavesOnly` is true, only nodes that do not have any dependants will be returned in the array. + - `directDependenciesOf(name)` - get an array containing the direct dependencies of the specified node + - `directDependantsOf(name)` (aliased as `directDependentsOf`) - get an array containing the nodes that directly depend on the specified node + - `overallOrder(leavesOnly)` - construct the overall processing order for the dependency graph. If `leavesOnly` is true, only nodes that do not depend on any other nodes will be returned. + - `entryNodes()` - array of nodes that have no dependants (i.e. nothing depends on them). + +Dependency Cycles are detected when running `dependenciesOf`, `dependantsOf`, and `overallOrder` and if one is found, a `DepGraphCycleError` will be thrown that includes what the cycle was in the message as well as the `cyclePath` property: e.g. `Dependency Cycle Found: a -> b -> c -> a`. If you wish to silence this error, pass `circular: true` when instantiating `DepGraph` (more below). + +## Examples + + var DepGraph = require('dependency-graph').DepGraph; + + var graph = new DepGraph(); + graph.addNode('a'); + graph.addNode('b'); + graph.addNode('c'); + + graph.size() // 3 + + graph.addDependency('a', 'b'); + graph.addDependency('b', 'c'); + + graph.dependenciesOf('a'); // ['c', 'b'] + graph.dependenciesOf('b'); // ['c'] + graph.dependantsOf('c'); // ['a', 'b'] + + graph.overallOrder(); // ['c', 'b', 'a'] + graph.overallOrder(true); // ['c'] + graph.entryNodes(); // ['a'] + + graph.addNode('d', 'data'); + + graph.getNodeData('d'); // 'data' + + graph.setNodeData('d', 'newData'); + + graph.getNodeData('d'); // 'newData' + + var circularGraph = new DepGraph({ circular: true }); + + circularGraph.addNode('a'); + circularGraph.addNode('b'); + circularGraph.addNode('c'); + circularGraph.addNode('d'); + + circularGraph.addDependency('a', 'b'); + circularGraph.addDependency('b', 'c'); // b depends on c + circularGraph.addDependency('c', 'a'); // c depends on a, which depends on b + circularGraph.addDependency('d', 'a'); + + circularGraph.dependenciesOf('b'); // ['a', 'c'] + circularGraph.overallOrder(); // ['c', 'b', 'a', 'd'] diff --git a/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/lib/dep_graph.js b/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/lib/dep_graph.js new file mode 100755 index 0000000..a64f801 --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/lib/dep_graph.js @@ -0,0 +1,364 @@ +/** + * A simple dependency graph + */ + +/** + * Helper for creating a Topological Sort using Depth-First-Search on a set of edges. + * + * Detects cycles and throws an Error if one is detected (unless the "circular" + * parameter is "true" in which case it ignores them). + * + * @param edges The set of edges to DFS through + * @param leavesOnly Whether to only return "leaf" nodes (ones who have no edges) + * @param result An array in which the results will be populated + * @param circular A boolean to allow circular dependencies + */ +function createDFS(edges, leavesOnly, result, circular) { + var visited = {}; + return function (start) { + if (visited[start]) { + return; + } + var inCurrentPath = {}; + var currentPath = []; + var todo = []; // used as a stack + todo.push({ node: start, processed: false }); + while (todo.length > 0) { + var current = todo[todo.length - 1]; // peek at the todo stack + var processed = current.processed; + var node = current.node; + if (!processed) { + // Haven't visited edges yet (visiting phase) + if (visited[node]) { + todo.pop(); + continue; + } else if (inCurrentPath[node]) { + // It's not a DAG + if (circular) { + todo.pop(); + // If we're tolerating cycles, don't revisit the node + continue; + } + currentPath.push(node); + throw new DepGraphCycleError(currentPath); + } + + inCurrentPath[node] = true; + currentPath.push(node); + var nodeEdges = edges[node]; + // (push edges onto the todo stack in reverse order to be order-compatible with the old DFS implementation) + for (var i = nodeEdges.length - 1; i >= 0; i--) { + todo.push({ node: nodeEdges[i], processed: false }); + } + current.processed = true; + } else { + // Have visited edges (stack unrolling phase) + todo.pop(); + currentPath.pop(); + inCurrentPath[node] = false; + visited[node] = true; + if (!leavesOnly || edges[node].length === 0) { + result.push(node); + } + } + } + }; +} + +/** + * Simple Dependency Graph + */ +var DepGraph = (exports.DepGraph = function DepGraph(opts) { + this.nodes = {}; // Node -> Node/Data (treated like a Set) + this.outgoingEdges = {}; // Node -> [Dependency Node] + this.incomingEdges = {}; // Node -> [Dependant Node] + this.circular = opts && !!opts.circular; // Allows circular deps +}); +DepGraph.prototype = { + /** + * The number of nodes in the graph. + */ + size: function () { + return Object.keys(this.nodes).length; + }, + /** + * Add a node to the dependency graph. If a node already exists, this method will do nothing. + */ + addNode: function (node, data) { + if (!this.hasNode(node)) { + // Checking the arguments length allows the user to add a node with undefined data + if (arguments.length === 2) { + this.nodes[node] = data; + } else { + this.nodes[node] = node; + } + this.outgoingEdges[node] = []; + this.incomingEdges[node] = []; + } + }, + /** + * Remove a node from the dependency graph. If a node does not exist, this method will do nothing. + */ + removeNode: function (node) { + if (this.hasNode(node)) { + delete this.nodes[node]; + delete this.outgoingEdges[node]; + delete this.incomingEdges[node]; + [this.incomingEdges, this.outgoingEdges].forEach(function (edgeList) { + Object.keys(edgeList).forEach(function (key) { + var idx = edgeList[key].indexOf(node); + if (idx >= 0) { + edgeList[key].splice(idx, 1); + } + }, this); + }); + } + }, + /** + * Check if a node exists in the graph + */ + hasNode: function (node) { + return this.nodes.hasOwnProperty(node); + }, + /** + * Get the data associated with a node name + */ + getNodeData: function (node) { + if (this.hasNode(node)) { + return this.nodes[node]; + } else { + throw new Error("Node does not exist: " + node); + } + }, + /** + * Set the associated data for a given node name. If the node does not exist, this method will throw an error + */ + setNodeData: function (node, data) { + if (this.hasNode(node)) { + this.nodes[node] = data; + } else { + throw new Error("Node does not exist: " + node); + } + }, + /** + * Add a dependency between two nodes. If either of the nodes does not exist, + * an Error will be thrown. + */ + addDependency: function (from, to) { + if (!this.hasNode(from)) { + throw new Error("Node does not exist: " + from); + } + if (!this.hasNode(to)) { + throw new Error("Node does not exist: " + to); + } + if (this.outgoingEdges[from].indexOf(to) === -1) { + this.outgoingEdges[from].push(to); + } + if (this.incomingEdges[to].indexOf(from) === -1) { + this.incomingEdges[to].push(from); + } + return true; + }, + /** + * Remove a dependency between two nodes. + */ + removeDependency: function (from, to) { + var idx; + if (this.hasNode(from)) { + idx = this.outgoingEdges[from].indexOf(to); + if (idx >= 0) { + this.outgoingEdges[from].splice(idx, 1); + } + } + + if (this.hasNode(to)) { + idx = this.incomingEdges[to].indexOf(from); + if (idx >= 0) { + this.incomingEdges[to].splice(idx, 1); + } + } + }, + /** + * Return a clone of the dependency graph. If any custom data is attached + * to the nodes, it will only be shallow copied. + */ + clone: function () { + var source = this; + var result = new DepGraph(); + var keys = Object.keys(source.nodes); + keys.forEach(function (n) { + result.nodes[n] = source.nodes[n]; + result.outgoingEdges[n] = source.outgoingEdges[n].slice(0); + result.incomingEdges[n] = source.incomingEdges[n].slice(0); + }); + return result; + }, + /** + * Get an array containing the direct dependencies of the specified node. + * + * Throws an Error if the specified node does not exist. + */ + directDependenciesOf: function (node) { + if (this.hasNode(node)) { + return this.outgoingEdges[node].slice(0); + } else { + throw new Error("Node does not exist: " + node); + } + }, + /** + * Get an array containing the nodes that directly depend on the specified node. + * + * Throws an Error if the specified node does not exist. + */ + directDependantsOf: function (node) { + if (this.hasNode(node)) { + return this.incomingEdges[node].slice(0); + } else { + throw new Error("Node does not exist: " + node); + } + }, + /** + * Get an array containing the nodes that the specified node depends on (transitively). + * + * Throws an Error if the graph has a cycle, or the specified node does not exist. + * + * If `leavesOnly` is true, only nodes that do not depend on any other nodes will be returned + * in the array. + */ + dependenciesOf: function (node, leavesOnly) { + if (this.hasNode(node)) { + var result = []; + var DFS = createDFS( + this.outgoingEdges, + leavesOnly, + result, + this.circular + ); + DFS(node); + var idx = result.indexOf(node); + if (idx >= 0) { + result.splice(idx, 1); + } + return result; + } else { + throw new Error("Node does not exist: " + node); + } + }, + /** + * get an array containing the nodes that depend on the specified node (transitively). + * + * Throws an Error if the graph has a cycle, or the specified node does not exist. + * + * If `leavesOnly` is true, only nodes that do not have any dependants will be returned in the array. + */ + dependantsOf: function (node, leavesOnly) { + if (this.hasNode(node)) { + var result = []; + var DFS = createDFS( + this.incomingEdges, + leavesOnly, + result, + this.circular + ); + DFS(node); + var idx = result.indexOf(node); + if (idx >= 0) { + result.splice(idx, 1); + } + return result; + } else { + throw new Error("Node does not exist: " + node); + } + }, + /** + * Construct the overall processing order for the dependency graph. + * + * Throws an Error if the graph has a cycle. + * + * If `leavesOnly` is true, only nodes that do not depend on any other nodes will be returned. + */ + overallOrder: function (leavesOnly) { + var self = this; + var result = []; + var keys = Object.keys(this.nodes); + if (keys.length === 0) { + return result; // Empty graph + } else { + if (!this.circular) { + // Look for cycles - we run the DFS starting at all the nodes in case there + // are several disconnected subgraphs inside this dependency graph. + var CycleDFS = createDFS(this.outgoingEdges, false, [], this.circular); + keys.forEach(function (n) { + CycleDFS(n); + }); + } + + var DFS = createDFS( + this.outgoingEdges, + leavesOnly, + result, + this.circular + ); + // Find all potential starting points (nodes with nothing depending on them) an + // run a DFS starting at these points to get the order + keys + .filter(function (node) { + return self.incomingEdges[node].length === 0; + }) + .forEach(function (n) { + DFS(n); + }); + + // If we're allowing cycles - we need to run the DFS against any remaining + // nodes that did not end up in the initial result (as they are part of a + // subgraph that does not have a clear starting point) + if (this.circular) { + keys + .filter(function (node) { + return result.indexOf(node) === -1; + }) + .forEach(function (n) { + DFS(n); + }); + } + + return result; + } + }, + /** + * Get an array of nodes that have no dependants (i.e. nothing depends on them). + */ + entryNodes: function () { + var self = this; + return Object.keys(this.nodes).filter(function (node) { + return self.incomingEdges[node].length === 0; + }); + } +}; + +// Create some aliases +DepGraph.prototype.directDependentsOf = DepGraph.prototype.directDependantsOf; +DepGraph.prototype.dependentsOf = DepGraph.prototype.dependantsOf; + +/** + * Cycle error, including the path of the cycle. + */ +var DepGraphCycleError = (exports.DepGraphCycleError = function (cyclePath) { + var message = "Dependency Cycle Found: " + cyclePath.join(" -> "); + var instance = new Error(message); + instance.cyclePath = cyclePath; + Object.setPrototypeOf(instance, Object.getPrototypeOf(this)); + if (Error.captureStackTrace) { + Error.captureStackTrace(instance, DepGraphCycleError); + } + return instance; +}); +DepGraphCycleError.prototype = Object.create(Error.prototype, { + constructor: { + value: Error, + enumerable: false, + writable: true, + configurable: true + } +}); +Object.setPrototypeOf(DepGraphCycleError, Error); diff --git a/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/lib/index.d.ts b/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/lib/index.d.ts new file mode 100755 index 0000000..6ed8de5 --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/lib/index.d.ts @@ -0,0 +1,127 @@ +declare module 'dependency-graph' { + export interface Options { + circular?: boolean; + } + + export class DepGraph { + /** + * Creates an instance of DepGraph with optional Options. + */ + constructor(opts?: Options); + + /** + * The number of nodes in the graph. + */ + size(): number; + + /** + * Add a node in the graph with optional data. If data is not given, name will be used as data. + * @param {string} name + * @param data + */ + addNode(name: string, data?: T): void; + + /** + * Remove a node from the graph. + * @param {string} name + */ + removeNode(name: string): void; + + /** + * Check if a node exists in the graph. + * @param {string} name + */ + hasNode(name: string): boolean; + + /** + * Get the data associated with a node (will throw an Error if the node does not exist). + * @param {string} name + */ + getNodeData(name: string): T; + + /** + * Set the data for an existing node (will throw an Error if the node does not exist). + * @param {string} name + * @param data + */ + setNodeData(name: string, data?: T): void; + + /** + * Add a dependency between two nodes (will throw an Error if one of the nodes does not exist). + * @param {string} from + * @param {string} to + */ + addDependency(from: string, to: string): void; + + /** + * Remove a dependency between two nodes. + * @param {string} from + * @param {string} to + */ + removeDependency(from: string, to: string): void; + + /** + * Return a clone of the dependency graph (If any custom data is attached + * to the nodes, it will only be shallow copied). + */ + clone(): DepGraph; + + /** + * Get an array containing the direct dependency nodes of the specified node. + * @param name + */ + directDependenciesOf(name: string): string[]; + + /** + * Get an array containing the nodes that directly depend on the specified node. + * @param name + */ + directDependantsOf(name: string): string[]; + + /** + * Alias of `directDependantsOf` + * + * @see directDependantsOf + * @param {string} name + */ + directDependentsOf(name: string): string[]; + + /** + * Get an array containing the nodes that the specified node depends on (transitively). If leavesOnly is true, only nodes that do not depend on any other nodes will be returned in the array. + * @param {string} name + * @param {boolean} leavesOnly + */ + dependenciesOf(name: string, leavesOnly?: boolean): string[]; + + /** + * Get an array containing the nodes that depend on the specified node (transitively). If leavesOnly is true, only nodes that do not have any dependants will be returned in the array. + * @param {string} name + * @param {boolean} leavesOnly + */ + dependantsOf(name: string, leavesOnly?: boolean): string[]; + + /** + * Alias of `dependantsOf` + * + * @see dependantsOf + * @param name + * @param leavesOnly + */ + dependentsOf(name: string, leavesOnly?: boolean): string[]; + + /** + * Get an array of nodes that have no dependants (i.e. nothing depends on them). + */ + entryNodes(): string[]; + + /** + * Construct the overall processing order for the dependency graph. If leavesOnly is true, only nodes that do not depend on any other nodes will be returned. + * @param {boolean} leavesOnly + */ + overallOrder(leavesOnly?: boolean): string[]; + } + + export class DepGraphCycleError extends Error { + cyclePath: string[]; + } +} diff --git a/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/package.json b/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/package.json new file mode 100755 index 0000000..d965899 --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/package.json @@ -0,0 +1,31 @@ +{ + "name": "dependency-graph", + "description": "Simple dependency graph.", + "version": "0.11.0", + "author": "Jim Riecken ", + "keywords": [ + "dependency", + "graph" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git://github.com/jriecken/dependency-graph.git" + }, + "bugs": { + "url": "http://github.com/jriecken/dependency-graph/issues" + }, + "main": "./lib/dep_graph.js", + "scripts": { + "test": "jasmine specs/**/*.js" + }, + "dependencies": {}, + "optionalDependencies": {}, + "devDependencies": { + "jasmine": "3.5.0" + }, + "engines": { + "node": ">= 0.6.0" + }, + "types": "./lib/index.d.ts" +} \ No newline at end of file diff --git a/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/specs/dep_graph_spec.js b/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/specs/dep_graph_spec.js new file mode 100755 index 0000000..07aa68e --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/node_modules/dependency-graph/specs/dep_graph_spec.js @@ -0,0 +1,542 @@ +var dep_graph = require("../lib/dep_graph"); +var DepGraph = dep_graph.DepGraph; + +describe("DepGraph", function () { + it("should be able to add/remove nodes", function () { + var graph = new DepGraph(); + + graph.addNode("Foo"); + graph.addNode("Bar"); + + expect(graph.hasNode("Foo")).toBeTrue(); + expect(graph.hasNode("Bar")).toBeTrue(); + expect(graph.hasNode("NotThere")).toBeFalse(); + + graph.removeNode("Bar"); + + expect(graph.hasNode("Bar")).toBeFalse(); + }); + + it("should calculate its size", function () { + var graph = new DepGraph(); + + expect(graph.size()).toBe(0); + + graph.addNode("Foo"); + graph.addNode("Bar"); + + expect(graph.size()).toBe(2); + + graph.removeNode("Bar"); + + expect(graph.size()).toBe(1); + }); + + it("should treat the node data parameter as optional and use the node name as data if node data was not given", function () { + var graph = new DepGraph(); + + graph.addNode("Foo"); + + expect(graph.getNodeData("Foo")).toBe("Foo"); + }); + + it("should be able to associate a node name with data on node add", function () { + var graph = new DepGraph(); + + graph.addNode("Foo", "data"); + + expect(graph.getNodeData("Foo")).toBe("data"); + }); + + it("should be able to add undefined as node data", function () { + var graph = new DepGraph(); + + graph.addNode("Foo", undefined); + + expect(graph.getNodeData("Foo")).toBeUndefined(); + }); + + it("should return true when using hasNode with a node which has falsy data", function () { + var graph = new DepGraph(); + + var falsyData = ["", 0, null, undefined, false]; + graph.addNode("Foo"); + + falsyData.forEach(function (data) { + graph.setNodeData("Foo", data); + + expect(graph.hasNode("Foo")).toBeTrue(); + + // Just an extra check to make sure that the saved data is correct + expect(graph.getNodeData("Foo")).toBe(data); + }); + }); + + it("should be able to set data after a node was added", function () { + var graph = new DepGraph(); + + graph.addNode("Foo", "data"); + graph.setNodeData("Foo", "data2"); + + expect(graph.getNodeData("Foo")).toBe("data2"); + }); + + it("should throw an error if we try to set data for a non-existing node", function () { + var graph = new DepGraph(); + + expect(function () { + graph.setNodeData("Foo", "data"); + }).toThrow(new Error("Node does not exist: Foo")); + }); + + it("should throw an error if the node does not exists and we try to get data", function () { + var graph = new DepGraph(); + + expect(function () { + graph.getNodeData("Foo"); + }).toThrow(new Error("Node does not exist: Foo")); + }); + + it("should do nothing if creating a node that already exists", function () { + var graph = new DepGraph(); + + graph.addNode("a"); + graph.addNode("b"); + + graph.addDependency("a", "b"); + + graph.addNode("a"); + + expect(graph.dependenciesOf("a")).toEqual(["b"]); + }); + + it("should do nothing if removing a node that does not exist", function () { + var graph = new DepGraph(); + + graph.addNode("a"); + expect(graph.hasNode("a")).toBeTrue(); + + graph.removeNode("a"); + expect(graph.hasNode("Foo")).toBeFalse(); + + graph.removeNode("a"); + expect(graph.hasNode("Foo")).toBeFalse(); + }); + + it("should be able to add dependencies between nodes", function () { + var graph = new DepGraph(); + + graph.addNode("a"); + graph.addNode("b"); + graph.addNode("c"); + + graph.addDependency("a", "b"); + graph.addDependency("a", "c"); + + expect(graph.dependenciesOf("a")).toEqual(["b", "c"]); + }); + + it("should find entry nodes", function () { + var graph = new DepGraph(); + + graph.addNode("a"); + graph.addNode("b"); + graph.addNode("c"); + + graph.addDependency("a", "b"); + graph.addDependency("a", "c"); + + expect(graph.entryNodes()).toEqual(["a"]); + }); + + it("should throw an error if a node does not exist and a dependency is added", function () { + var graph = new DepGraph(); + + graph.addNode("a"); + + expect(function () { + graph.addDependency("a", "b"); + }).toThrow(new Error("Node does not exist: b")); + }); + + it("should detect cycles", function () { + var graph = new DepGraph(); + + graph.addNode("a"); + graph.addNode("b"); + graph.addNode("c"); + graph.addNode("d"); + + graph.addDependency("a", "b"); + graph.addDependency("b", "c"); + graph.addDependency("c", "a"); + graph.addDependency("d", "a"); + + expect(function () { + graph.dependenciesOf("b"); + }).toThrow(new dep_graph.DepGraphCycleError(["b", "c", "a", "b"])); + }); + + it("should allow cycles when configured", function () { + var graph = new DepGraph({ circular: true }); + + graph.addNode("a"); + graph.addNode("b"); + graph.addNode("c"); + graph.addNode("d"); + + graph.addDependency("a", "b"); + graph.addDependency("b", "c"); + graph.addDependency("c", "a"); + graph.addDependency("d", "a"); + + expect(graph.dependenciesOf("b")).toEqual(["a", "c"]); + expect(graph.overallOrder()).toEqual(["c", "b", "a", "d"]); + }); + + it( + "should include all nodes in overall order even from " + + "cycles in disconnected subgraphs when circular is true", + function () { + var graph = new DepGraph({ circular: true }); + + graph.addNode("2a"); + graph.addNode("2b"); + graph.addNode("2c"); + graph.addDependency("2a", "2b"); + graph.addDependency("2b", "2c"); + graph.addDependency("2c", "2a"); + + graph.addNode("1a"); + graph.addNode("1b"); + graph.addNode("1c"); + graph.addNode("1d"); + graph.addNode("1e"); + + graph.addDependency("1a", "1b"); + graph.addDependency("1a", "1c"); + graph.addDependency("1b", "1c"); + graph.addDependency("1c", "1d"); + + expect(graph.overallOrder()).toEqual([ + "1d", + "1c", + "1b", + "1a", + "1e", + "2c", + "2b", + "2a" + ]); + } + ); + + it("should detect cycles in overall order", function () { + var graph = new DepGraph(); + + graph.addNode("a"); + graph.addNode("b"); + graph.addNode("c"); + graph.addNode("d"); + + graph.addDependency("a", "b"); + graph.addDependency("b", "c"); + graph.addDependency("c", "a"); + graph.addDependency("d", "a"); + + expect(function () { + graph.overallOrder(); + }).toThrow(new dep_graph.DepGraphCycleError(["a", "b", "c", "a"])); + }); + + it("should detect cycles in overall order when all nodes have dependants (incoming edges)", function () { + var graph = new DepGraph(); + + graph.addNode("a"); + graph.addNode("b"); + graph.addNode("c"); + + graph.addDependency("a", "b"); + graph.addDependency("b", "c"); + graph.addDependency("c", "a"); + + expect(function () { + graph.overallOrder(); + }).toThrow(new dep_graph.DepGraphCycleError(["a", "b", "c", "a"])); + }); + + it( + "should detect cycles in overall order when there are several " + + "disconnected subgraphs (with one that does not have a cycle", + function () { + var graph = new DepGraph(); + + graph.addNode("a_1"); + graph.addNode("a_2"); + graph.addNode("b_1"); + graph.addNode("b_2"); + graph.addNode("b_3"); + + graph.addDependency("a_1", "a_2"); + graph.addDependency("b_1", "b_2"); + graph.addDependency("b_2", "b_3"); + graph.addDependency("b_3", "b_1"); + + expect(function () { + graph.overallOrder(); + }).toThrow( + new dep_graph.DepGraphCycleError(["b_1", "b_2", "b_3", "b_1"]) + ); + } + ); + + it("should retrieve dependencies and dependants in the correct order", function () { + var graph = new DepGraph(); + + graph.addNode("a"); + graph.addNode("b"); + graph.addNode("c"); + graph.addNode("d"); + + graph.addDependency("a", "d"); + graph.addDependency("a", "b"); + graph.addDependency("b", "c"); + graph.addDependency("d", "b"); + + expect(graph.dependenciesOf("a")).toEqual(["c", "b", "d"]); + expect(graph.dependenciesOf("b")).toEqual(["c"]); + expect(graph.dependenciesOf("c")).toEqual([]); + expect(graph.dependenciesOf("d")).toEqual(["c", "b"]); + + expect(graph.dependantsOf("a")).toEqual([]); + expect(graph.dependantsOf("b")).toEqual(["a", "d"]); + expect(graph.dependantsOf("c")).toEqual(["a", "d", "b"]); + expect(graph.dependantsOf("d")).toEqual(["a"]); + + // check the alias "dependentsOf" + expect(graph.dependentsOf("a")).toEqual([]); + expect(graph.dependentsOf("b")).toEqual(["a", "d"]); + expect(graph.dependentsOf("c")).toEqual(["a", "d", "b"]); + expect(graph.dependentsOf("d")).toEqual(["a"]); + }); + + it("should be able to retrieve direct dependencies/dependants", function () { + var graph = new DepGraph(); + + graph.addNode("a"); + graph.addNode("b"); + graph.addNode("c"); + graph.addNode("d"); + + graph.addDependency("a", "d"); + graph.addDependency("a", "b"); + graph.addDependency("b", "c"); + graph.addDependency("d", "b"); + + expect(graph.directDependenciesOf("a")).toEqual(["d", "b"]); + expect(graph.directDependenciesOf("b")).toEqual(["c"]); + expect(graph.directDependenciesOf("c")).toEqual([]); + expect(graph.directDependenciesOf("d")).toEqual(["b"]); + + expect(graph.directDependantsOf("a")).toEqual([]); + expect(graph.directDependantsOf("b")).toEqual(["a", "d"]); + expect(graph.directDependantsOf("c")).toEqual(["b"]); + expect(graph.directDependantsOf("d")).toEqual(["a"]); + + // check the alias "directDependentsOf" + expect(graph.directDependentsOf("a")).toEqual([]); + expect(graph.directDependentsOf("b")).toEqual(["a", "d"]); + expect(graph.directDependentsOf("c")).toEqual(["b"]); + expect(graph.directDependentsOf("d")).toEqual(["a"]); + }); + + it("should be able to resolve the overall order of things", function () { + var graph = new DepGraph(); + + graph.addNode("a"); + graph.addNode("b"); + graph.addNode("c"); + graph.addNode("d"); + graph.addNode("e"); + + graph.addDependency("a", "b"); + graph.addDependency("a", "c"); + graph.addDependency("b", "c"); + graph.addDependency("c", "d"); + + expect(graph.overallOrder()).toEqual(["d", "c", "b", "a", "e"]); + }); + + it('should be able to only retrieve the "leaves" in the overall order', function () { + var graph = new DepGraph(); + + graph.addNode("a"); + graph.addNode("b"); + graph.addNode("c"); + graph.addNode("d"); + graph.addNode("e"); + + graph.addDependency("a", "b"); + graph.addDependency("a", "c"); + graph.addDependency("b", "c"); + graph.addDependency("c", "d"); + + expect(graph.overallOrder(true)).toEqual(["d", "e"]); + }); + + it("should be able to give the overall order for a graph with several disconnected subgraphs", function () { + var graph = new DepGraph(); + + graph.addNode("a_1"); + graph.addNode("a_2"); + graph.addNode("b_1"); + graph.addNode("b_2"); + graph.addNode("b_3"); + + graph.addDependency("a_1", "a_2"); + graph.addDependency("b_1", "b_2"); + graph.addDependency("b_2", "b_3"); + + expect(graph.overallOrder()).toEqual(["a_2", "a_1", "b_3", "b_2", "b_1"]); + }); + + it("should give an empty overall order for an empty graph", function () { + var graph = new DepGraph(); + + expect(graph.overallOrder()).toEqual([]); + }); + + it("should still work after nodes are removed", function () { + var graph = new DepGraph(); + + graph.addNode("a"); + graph.addNode("b"); + graph.addNode("c"); + graph.addDependency("a", "b"); + graph.addDependency("b", "c"); + + expect(graph.dependenciesOf("a")).toEqual(["c", "b"]); + + graph.removeNode("c"); + + expect(graph.dependenciesOf("a")).toEqual(["b"]); + }); + + it("should clone an empty graph", function () { + var graph = new DepGraph(); + expect(graph.size()).toEqual(0); + var cloned = graph.clone(); + expect(cloned.size()).toEqual(0); + + expect(graph === cloned).toBeFalse(); + }); + + it("should clone a non-empty graph", function () { + var graph = new DepGraph(); + + graph.addNode("a"); + graph.addNode("b"); + graph.addNode("c"); + graph.addDependency("a", "b"); + graph.addDependency("b", "c"); + + var cloned = graph.clone(); + + expect(graph === cloned).toBeFalse(); + expect(cloned.hasNode("a")).toBeTrue(); + expect(cloned.hasNode("b")).toBeTrue(); + expect(cloned.hasNode("c")).toBeTrue(); + expect(cloned.dependenciesOf("a")).toEqual(["c", "b"]); + expect(cloned.dependantsOf("c")).toEqual(["a", "b"]); + + // Changes to the original graph shouldn't affect the clone + graph.removeNode("c"); + expect(graph.dependenciesOf("a")).toEqual(["b"]); + expect(cloned.dependenciesOf("a")).toEqual(["c", "b"]); + + graph.addNode("d"); + graph.addDependency("b", "d"); + expect(graph.dependenciesOf("a")).toEqual(["d", "b"]); + expect(cloned.dependenciesOf("a")).toEqual(["c", "b"]); + }); + + it("should only be a shallow clone", function () { + var graph = new DepGraph(); + + var data = { a: 42 }; + graph.addNode("a", data); + + var cloned = graph.clone(); + expect(graph === cloned).toBeFalse(); + expect(graph.getNodeData("a") === cloned.getNodeData("a")).toBeTrue(); + + graph.getNodeData("a").a = 43; + expect(cloned.getNodeData("a").a).toBe(43); + + cloned.setNodeData("a", { a: 42 }); + expect(cloned.getNodeData("a").a).toBe(42); + expect(graph.getNodeData("a") === cloned.getNodeData("a")).toBeFalse(); + }); +}); + +describe("DepGraph Performance", function () { + it("should not exceed max call stack with a very deep graph", function () { + var g = new DepGraph(); + var expected = []; + for (var i = 0; i < 100000; i++) { + var istr = i.toString(); + g.addNode(istr); + expected.push(istr); + if (i > 0) { + g.addDependency(istr, (i - 1).toString()); + } + } + var order = g.overallOrder(); + expect(order).toEqual(expected); + }); + + it("should run an a reasonable amount of time for a very large graph", function () { + var randInt = function (min, max) { + return Math.floor(Math.random() * (max - min + 1)) + min; + }; + var g = new DepGraph(); + var nodes = []; + // Create a graph with 100000 nodes in it with 10 random connections to + // lower numbered nodes + for (var i = 0; i < 100000; i++) { + nodes.push(i.toString()); + g.addNode(i.toString()); + for (var j = 0; j < 10; j++) { + var dep = randInt(0, i); + if (i !== dep) { + g.addDependency(i.toString(), dep.toString()); + } + } + } + var start = new Date().getTime(); + g.overallOrder(); + var end = new Date().getTime(); + expect(start - end).toBeLessThan(1000); + }); +}); + +describe("DepGraphCycleError", function () { + var DepGraphCycleError = dep_graph.DepGraphCycleError; + + it("should have a message", function () { + var err = new DepGraphCycleError(["a", "b", "c", "a"]); + expect(err.message).toEqual("Dependency Cycle Found: a -> b -> c -> a"); + }); + + it("should be an instanceof DepGraphCycleError", function () { + var err = new DepGraphCycleError(["a", "b", "c", "a"]); + expect(err instanceof DepGraphCycleError).toBeTrue(); + expect(err instanceof Error).toBeTrue(); + }); + + it("should have a cyclePath", function () { + var cyclePath = ["a", "b", "c", "a"]; + var err = new DepGraphCycleError(cyclePath); + expect(err.cyclePath).toEqual(cyclePath); + }); +}); diff --git a/node_modules/@11ty/dependency-tree-esm/package.json b/node_modules/@11ty/dependency-tree-esm/package.json new file mode 100644 index 0000000..2ecd9db --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/package.json @@ -0,0 +1,36 @@ +{ + "name": "@11ty/dependency-tree-esm", + "version": "1.0.0", + "description": "Finds all JavaScript ES Module dependencies from a filename.", + "main": "main.js", + "scripts": { + "test": "npx ava" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/11ty/eleventy-dependency-tree.git" + }, + "author": { + "name": "Zach Leatherman", + "email": "zach@zachleat.com", + "url": "https://zachleat.com/" + }, + "license": "MIT", + "dependencies": { + "@11ty/eleventy-utils": "^1.0.2", + "acorn": "^8.10.0", + "dependency-graph": "^0.11.0", + "normalize-path": "^3.0.0" + }, + "devDependencies": { + "ava": "^5.3.1" + }, + "ava": { + "files": [ + "./test/*.js" + ], + "ignoredByWatcher": [ + "./test/stubs/**" + ] + } +} diff --git a/node_modules/@11ty/dependency-tree-esm/test/stubs/circular-child.js b/node_modules/@11ty/dependency-tree-esm/test/stubs/circular-child.js new file mode 100644 index 0000000..1b9ba5e --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/test/stubs/circular-child.js @@ -0,0 +1 @@ +import "./circular-parent.js"; \ No newline at end of file diff --git a/node_modules/@11ty/dependency-tree-esm/test/stubs/circular-parent.js b/node_modules/@11ty/dependency-tree-esm/test/stubs/circular-parent.js new file mode 100644 index 0000000..3153b84 --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/test/stubs/circular-parent.js @@ -0,0 +1 @@ +import "./circular-child.js"; \ No newline at end of file diff --git a/node_modules/@11ty/dependency-tree-esm/test/stubs/circular-self.js b/node_modules/@11ty/dependency-tree-esm/test/stubs/circular-self.js new file mode 100644 index 0000000..267b293 --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/test/stubs/circular-self.js @@ -0,0 +1,2 @@ +import "./circular-self.js"; +import "./empty.js"; \ No newline at end of file diff --git a/node_modules/@11ty/dependency-tree-esm/test/stubs/empty.js b/node_modules/@11ty/dependency-tree-esm/test/stubs/empty.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/@11ty/dependency-tree-esm/test/stubs/file.js b/node_modules/@11ty/dependency-tree-esm/test/stubs/file.js new file mode 100644 index 0000000..c97bcbb --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/test/stubs/file.js @@ -0,0 +1,2 @@ +import fs from "fs"; +import * as fdklsjf from "./imported-secondary.js"; \ No newline at end of file diff --git a/node_modules/@11ty/dependency-tree-esm/test/stubs/imported-secondary.js b/node_modules/@11ty/dependency-tree-esm/test/stubs/imported-secondary.js new file mode 100644 index 0000000..b70cefb --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/test/stubs/imported-secondary.js @@ -0,0 +1,3 @@ +import "fs"; + +export function hello() {} \ No newline at end of file diff --git a/node_modules/@11ty/dependency-tree-esm/test/stubs/imported.js b/node_modules/@11ty/dependency-tree-esm/test/stubs/imported.js new file mode 100644 index 0000000..479ee82 --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/test/stubs/imported.js @@ -0,0 +1,3 @@ +import * as fdklsjf from "./imported-secondary.js"; + +export function hello() {} \ No newline at end of file diff --git a/node_modules/@11ty/dependency-tree-esm/test/stubs/nested-grandchild.js b/node_modules/@11ty/dependency-tree-esm/test/stubs/nested-grandchild.js new file mode 100644 index 0000000..b533597 --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/test/stubs/nested-grandchild.js @@ -0,0 +1 @@ +import * as fdklsjf from "./nested.js"; \ No newline at end of file diff --git a/node_modules/@11ty/dependency-tree-esm/test/stubs/nested.js b/node_modules/@11ty/dependency-tree-esm/test/stubs/nested.js new file mode 100644 index 0000000..26618f6 --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/test/stubs/nested.js @@ -0,0 +1,2 @@ +import fs from "fs"; +import * as fdklsjf from "./imported.js"; \ No newline at end of file diff --git a/node_modules/@11ty/dependency-tree-esm/test/test.js b/node_modules/@11ty/dependency-tree-esm/test/test.js new file mode 100644 index 0000000..ace403d --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/test/test.js @@ -0,0 +1,30 @@ +const test = require("ava"); +const { find } = require("../main.js"); + +test("Empty", async t => { + t.deepEqual(await find("./test/stubs/empty.js"), []); +}); + +test("Doesn’t exist", async t => { + t.deepEqual(await find("./test/stubs/THIS_FILE_DOES_NOT_EXIST.js"), []); +}); + +test("Simple", async t => { + t.deepEqual(await find("./test/stubs/file.js"), ["./test/stubs/imported-secondary.js"]); +}); + +test("Nested two deep", async t => { + t.deepEqual(await find("./test/stubs/nested.js"), ["./test/stubs/imported.js", "./test/stubs/imported-secondary.js"]); +}); + +test("Nested three deep", async t => { + t.deepEqual(await find("./test/stubs/nested-grandchild.js"), ["./test/stubs/nested.js", "./test/stubs/imported.js", "./test/stubs/imported-secondary.js"]); +}); + +test("Circular", async t => { + t.deepEqual(await find("./test/stubs/circular-parent.js"), ["./test/stubs/circular-child.js"]); +}); + +test("Circular Self Reference", async t => { + t.deepEqual(await find("./test/stubs/circular-self.js"), ["./test/stubs/empty.js"]); +}); diff --git a/node_modules/@11ty/dependency-tree/LICENSE b/node_modules/@11ty/dependency-tree/LICENSE new file mode 100644 index 0000000..bad6417 --- /dev/null +++ b/node_modules/@11ty/dependency-tree/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Zach Leatherman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@11ty/dependency-tree/README.md b/node_modules/@11ty/dependency-tree/README.md new file mode 100644 index 0000000..110ab3a --- /dev/null +++ b/node_modules/@11ty/dependency-tree/README.md @@ -0,0 +1,94 @@ +# `dependency-tree` + +Returns an unordered array of local paths to dependencies of a CommonJS node JavaScript file (everything it or any of its dependencies `require`s). + +* See also: [`dependency-tree-esm`](https://github.com/11ty/eleventy-dependency-tree-esm) for ES Modules. + +Reduced feature (faster) alternative to the [`dependency-tree` package](https://www.npmjs.com/package/dependency-tree). This is used by Eleventy to find dependencies of a JavaScript file to watch for changes to re-run Eleventy’s build. + +## Big Huge Caveat + +⚠ A big caveat to this plugin is that it will require the file in order to build a dependency tree. So if your module has side effects and you don’t want it to execute—do not use this! + +## Installation + +``` +npm install --save-dev @11ty/dependency-tree +``` + +## Features + +* Ignores `node_modules` +* Or, use `nodeModuleNames` to control whether or not `node_modules` package names are included (added in v2.0.1) +* Ignores Node’s built-ins (e.g. `path`) +* Handles circular dependencies (Node does this too) + +## Usage + +```js +// my-file.js + +// if my-local-dependency.js has dependencies, it will include those too +const test = require("./my-local-dependency.js"); + +// ignored, is a built-in +const path = require("path"); +``` + +```js +const DependencyTree = require("@11ty/dependency-tree"); + +DependencyTree("./my-file.js"); +// returns ["./my-local-dependency.js"] +``` + +### `allowNotFound` + +```js +const DependencyTree = require("@11ty/dependency-tree"); + +DependencyTree("./this-does-not-exist.js"); // throws an error + +DependencyTree("./this-does-not-exist.js", { allowNotFound: true }); +// returns [] +``` + +### `nodeModuleNames` + +(Added in v2.0.1) Controls whether or not node package names are included in the list of dependencies. + +* `nodeModuleNames: "include"`: included alongside the local JS files. +* `nodeModuleNames: "exclude"` (default): node module package names are excluded. +* `nodeModuleNames: "only"`: only node module package names are returned. + +```js +// my-file.js: + +require("./my-local-dependency.js"); +require("@11ty/eleventy"); +``` + +```js +const DependencyTree = require("@11ty/dependency-tree"); + +DependencyTree("./my-file.js"); +// returns ["./my-local-dependency.js"] + +DependencyTree("./my-file.js", { nodeModuleNames: "exclude" }); +// returns ["./my-local-dependency.js"] + +DependencyTree("./my-file.js", { nodeModuleNames: "include" }); +// returns ["./my-local-dependency.js", "@11ty/eleventy"] + +DependencyTree("./my-file.js", { nodeModuleNames: "only" }); +// returns ["@11ty/eleventy"] +``` + +#### (Deprecated) `nodeModuleNamesOnly` + +(Added in v2.0.0) Changed to use `nodeModuleNames` option instead. Backwards compatibility is maintained automatically. + +* `nodeModuleNamesOnly: false` is mapped to `nodeModuleNames: "exclude"` +* `nodeModuleNamesOnly: true` is mapped to `nodeModuleNames: "only"` + +If both `nodeModuleNamesOnly` and `nodeModuleNames` are included in options, `nodeModuleNames` takes precedence. diff --git a/node_modules/@11ty/dependency-tree/main.js b/node_modules/@11ty/dependency-tree/main.js new file mode 100644 index 0000000..9edf2be --- /dev/null +++ b/node_modules/@11ty/dependency-tree/main.js @@ -0,0 +1,132 @@ +const path = require("path"); +const { TemplatePath } = require("@11ty/eleventy-utils"); + +function getAbsolutePath(filename) { + let normalizedFilename = path.normalize(filename); // removes dot slash + let hasDotSlash = filename.startsWith("./"); + return hasDotSlash ? path.join(path.resolve("."), normalizedFilename) : normalizedFilename; +} + +function getRelativePath(filename) { + let normalizedFilename = path.normalize(filename); // removes dot slash + let workingDirectory = path.resolve("."); + let result = "./" + (normalizedFilename.startsWith(workingDirectory) ? normalizedFilename.substr(workingDirectory.length + 1) : normalizedFilename); + return result; +} + +function getNodeModuleName(filename) { + let foundNodeModules = false; + let moduleName = []; + + let s = filename.split(path.sep); + for(let entry of s) { + if(entry === '.pnpm') { + foundNodeModules = false; + } + + if(foundNodeModules) { + moduleName.push(entry); + if(!entry.startsWith("@")) { + return moduleName.join("/"); + } + } + + if(entry === "node_modules") { + foundNodeModules = true; + } + } + + return false; +} + +/* unordered */ +function getDependenciesFor(filename, avoidCircular, optionsArg = {}) { + // backwards compatibility with `nodeModuleNamesOnly` boolean option + // Using `nodeModuleNames` property moving forward + if(("nodeModuleNamesOnly" in optionsArg) && !("nodeModuleNames" in optionsArg)) { + if(optionsArg.nodeModuleNamesOnly === true) { + optionsArg.nodeModuleNames = "only"; + } + if(optionsArg.nodeModuleNamesOnly === false) { + optionsArg.nodeModuleNames = "exclude"; + } + } + + let options = Object.assign({ + allowNotFound: false, + nodeModuleNames: "exclude", // also "include" or "only" + }, optionsArg); + let absoluteFilename = getAbsolutePath(filename) + + try { + require(absoluteFilename); + } catch(e) { + if(e.code === "MODULE_NOT_FOUND" && options.allowNotFound) { + // do nothing + } else { + throw e; + } + } + + + let mod; + for(let entry in require.cache) { + if(entry === absoluteFilename) { + mod = require.cache[entry]; + break; + } + } + + let dependencies = new Set(); + + if(!mod) { + if(!options.allowNotFound) { + throw new Error(`Could not find ${filename} in @11ty/dependency-tree`); + } + } else { + let relativeFilename = getRelativePath(mod.filename); + if(!avoidCircular) { + avoidCircular = {}; + } else if(options.nodeModuleNames !== "only") { + dependencies.add(relativeFilename); + } + + avoidCircular[relativeFilename] = true; + + if(mod.children) { + for(let child of mod.children) { + let relativeChildFilename = getRelativePath(child.filename); + let nodeModuleName = getNodeModuleName(child.filename); + + if(options.nodeModuleNames !== "exclude" && nodeModuleName) { + dependencies.add(nodeModuleName); + } + // Add dependencies of this dependency (not top level node_modules) + if(nodeModuleName === false) { + if(!dependencies.has(relativeChildFilename) && // avoid infinite looping with circular deps + !avoidCircular[relativeChildFilename] ) { + for(let dependency of getDependenciesFor(relativeChildFilename, avoidCircular, options)) { + dependencies.add(dependency); + } + } + } + } + } + } + + return dependencies; +} + +function getCleanDependencyListFor(filename, options = {}) { + let deps = Array.from( getDependenciesFor(filename, null, options) ); + + return deps.map(filePath => { + if(filePath.startsWith("./")) { + return TemplatePath.standardizeFilePath(filePath); + } + return filePath; // node_module name + }); +} + +module.exports = getCleanDependencyListFor; +module.exports.getNodeModuleName = getNodeModuleName; \ No newline at end of file diff --git a/node_modules/@11ty/dependency-tree/package.json b/node_modules/@11ty/dependency-tree/package.json new file mode 100644 index 0000000..367ca24 --- /dev/null +++ b/node_modules/@11ty/dependency-tree/package.json @@ -0,0 +1,39 @@ +{ + "name": "@11ty/dependency-tree", + "version": "3.0.1", + "description": "Finds all JavaScript CommmonJS require() dependencies from a filename.", + "main": "main.js", + "files": [ + "main.js", + "!test", + "!test/**" + ], + "scripts": { + "test": "npx ava" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/11ty/eleventy-dependency-tree.git" + }, + "author": { + "name": "Zach Leatherman", + "email": "zach@zachleat.com", + "url": "https://zachleat.com/" + }, + "license": "MIT", + "ava": { + "files": [ + "./test/*.js" + ], + "ignoredByWatcher": [ + "./test/stubs/**" + ] + }, + "devDependencies": { + "@sindresorhus/is": "^4.6.0", + "ava": "^5.3.1" + }, + "dependencies": { + "@11ty/eleventy-utils": "^1.0.2" + } +} diff --git a/node_modules/@11ty/eleventy-dev-server/README.md b/node_modules/@11ty/eleventy-dev-server/README.md new file mode 100644 index 0000000..2d74590 --- /dev/null +++ b/node_modules/@11ty/eleventy-dev-server/README.md @@ -0,0 +1,60 @@ +

11ty Logo

+ +# eleventy-dev-server 🕚⚡️🎈🐀 + +A minimal, modern, generic, hot-reloading local web server to help web developers. + +## ➡ [Documentation](https://www.11ty.dev/docs/watch-serve/#eleventy-dev-server) + +- Please star [Eleventy on GitHub](https://github.com/11ty/eleventy/)! +- Follow us on Twitter [@eleven_ty](https://twitter.com/eleven_ty) +- Support [11ty on Open Collective](https://opencollective.com/11ty) +- [11ty on npm](https://www.npmjs.com/org/11ty) +- [11ty on GitHub](https://github.com/11ty) + +[![npm Version](https://img.shields.io/npm/v/@11ty/eleventy-dev-server.svg?style=for-the-badge)](https://www.npmjs.com/package/@11ty/eleventy-dev-server) + +## Installation + +This is bundled with `@11ty/eleventy` (and you do not need to install it separately) in Eleventy v2.0. + +## CLI + +Eleventy Dev Server now also includes a CLI. The CLI is for **standalone** (non-Eleventy) use only: separate installation is unnecessary if you’re using this server with `@11ty/eleventy`. + +```sh +npm install -g @11ty/eleventy-dev-server + +# Alternatively, install locally into your project +npm install @11ty/eleventy-dev-server +``` + +This package requires Node 18 or newer. + +### CLI Usage + +```sh +# Serve the current directory +npx @11ty/eleventy-dev-server + +# Serve a different subdirectory (also aliased as --input) +npx @11ty/eleventy-dev-server --dir=_site + +# Disable the `domdiff` feature +npx @11ty/eleventy-dev-server --domdiff=false + +# Full command list in the Help +npx @11ty/eleventy-dev-server --help +``` + +## Tests + +``` +npm run test +``` + +- We use the [ava JavaScript test runner](https://github.com/avajs/ava) ([Assertions documentation](https://github.com/avajs/ava/blob/master/docs/03-assertions.md)) + +## Changelog + +* `v2.0.0` bumps Node.js minimum to 18. \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-dev-server/cli.js b/node_modules/@11ty/eleventy-dev-server/cli.js new file mode 100644 index 0000000..04be1ca --- /dev/null +++ b/node_modules/@11ty/eleventy-dev-server/cli.js @@ -0,0 +1,89 @@ +const pkg = require("./package.json"); +const EleventyDevServer = require("./server.js"); + +const Logger = { + info: function(...args) { + console.log( "[11ty/eleventy-dev-server]", ...args ); + }, + error: function(...args) { + console.error( "[11ty/eleventy-dev-server]", ...args ); + }, + fatal: function(...args) { + Logger.error(...args); + process.exitCode = 1; + } +}; + +Logger.log = Logger.info; + +class Cli { + static getVersion() { + return pkg.version; + } + + static getHelp() { + return `Usage: + + eleventy-dev-server + eleventy-dev-server --dir=_site + eleventy-dev-server --port=3000 + +Arguments: + + --version + + --dir=. + Directory to serve (default: \`.\`) + + --input (alias for --dir) + + --port=8080 + Run the web server on this port (default: \`8080\`) + Will autoincrement if already in use. + + --domdiff (enabled, default) + --domdiff=false (disabled) + Apply HTML changes without a full page reload. + + --help`; + } + + static getDefaultOptions() { + return { + port: "8080", + input: ".", + domDiff: true, + } + } + + async serve(options = {}) { + this.options = Object.assign(Cli.getDefaultOptions(), options); + + this.server = EleventyDevServer.getServer("eleventy-dev-server-cli", this.options.input, { + // TODO allow server configuration extensions + showVersion: true, + logger: Logger, + domDiff: this.options.domDiff, + + // CLI watches all files in the folder by default + // this is different from Eleventy usage! + watch: [ this.options.input ], + }); + + this.server.serve(this.options.port); + + // TODO? send any errors here to the server too + // with server.sendError({ error }); + } + + close() { + if(this.server) { + return this.server.close(); + } + } +} + +module.exports = { + Logger, + Cli +} diff --git a/node_modules/@11ty/eleventy-dev-server/client/reload-client.js b/node_modules/@11ty/eleventy-dev-server/client/reload-client.js new file mode 100644 index 0000000..22bed41 --- /dev/null +++ b/node_modules/@11ty/eleventy-dev-server/client/reload-client.js @@ -0,0 +1,294 @@ +class Util { + static pad(num, digits = 2) { + let zeroes = new Array(digits + 1).join(0); + return `${zeroes}${num}`.slice(-1 * digits); + } + + static log(message) { + Util.output("log", message); + } + static error(message, error) { + Util.output("error", message, error); + } + static output(type, ...messages) { + let now = new Date(); + let date = `${Util.pad(now.getUTCHours())}:${Util.pad( + now.getUTCMinutes() + )}:${Util.pad(now.getUTCSeconds())}.${Util.pad( + now.getUTCMilliseconds(), + 3 + )}`; + console[type](`[11ty][${date} UTC]`, ...messages); + } + + static capitalize(word) { + return word.substr(0, 1).toUpperCase() + word.substr(1); + } + + static matchRootAttributes(htmlContent) { + // Workaround for morphdom bug with attributes on https://github.com/11ty/eleventy-dev-server/issues/6 + // Note also `childrenOnly: true` above + const parser = new DOMParser(); + let parsed = parser.parseFromString(htmlContent, "text/html"); + let parsedDoc = parsed.documentElement; + let newAttrs = parsedDoc.getAttributeNames(); + + let docEl = document.documentElement; + // Remove old + let removedAttrs = docEl.getAttributeNames().filter(name => !newAttrs.includes(name)); + for(let attr of removedAttrs) { + docEl.removeAttribute(attr); + } + + // Add new + for(let attr of newAttrs) { + docEl.setAttribute(attr, parsedDoc.getAttribute(attr)); + } + } + + static isEleventyLinkNodeMatch(from, to) { + // Issue #18 https://github.com/11ty/eleventy-dev-server/issues/18 + // Don’t update a if the _11ty searchParam is the only thing that’s different + if(from.tagName !== "LINK" || to.tagName !== "LINK") { + return false; + } + + let oldWithoutHref = from.cloneNode(); + let newWithoutHref = to.cloneNode(); + + oldWithoutHref.removeAttribute("href"); + newWithoutHref.removeAttribute("href"); + + // if all other attributes besides href match + if(!oldWithoutHref.isEqualNode(newWithoutHref)) { + return false; + } + + let oldUrl = new URL(from.href); + let newUrl = new URL(to.href); + + // morphdom wants to force href="style.css?_11ty" => href="style.css" + let isErasing = oldUrl.searchParams.has("_11ty") && !newUrl.searchParams.has("_11ty"); + if(!isErasing) { + // not a match if _11ty has a new value (not being erased) + return false; + } + + oldUrl.searchParams.set("_11ty", ""); + newUrl.searchParams.set("_11ty", ""); + + // is a match if erasing and the rest of the href matches too + return oldUrl.toString() === newUrl.toString(); + } + + // https://github.com/patrick-steele-idem/morphdom/issues/178#issuecomment-652562769 + static runScript(source, target) { + let script = document.createElement('script'); + + // copy over the attributes + for(let attr of [...source.attributes]) { + script.setAttribute(attr.nodeName ,attr.nodeValue); + } + + script.innerHTML = source.innerHTML; + (target || source).replaceWith(script); + } +} + +class EleventyReload { + constructor() { + this.connectionMessageShown = false; + this.reconnectEventCallback = this.reconnect.bind(this); + } + + init(options = {}) { + if (!("WebSocket" in window)) { + return; + } + + let { protocol, host } = new URL(document.location.href); + + // works with http (ws) and https (wss) + let websocketProtocol = protocol.replace("http", "ws"); + + let socket = new WebSocket(`${websocketProtocol}//${host}`); + + socket.addEventListener("message", async (event) => { + try { + let data = JSON.parse(event.data); + // Util.log( JSON.stringify(data, null, 2) ); + + let { type } = data; + + if (type === "eleventy.reload") { + await this.onreload(data); + } else if (type === "eleventy.msg") { + Util.log(`${data.message}`); + } else if (type === "eleventy.error") { + // Log Eleventy build errors + // Extra parsing for Node Error objects + let e = JSON.parse(data.error); + Util.error(`Build error: ${e.message}`, e); + } else if (type === "eleventy.status") { + // Full page reload on initial reconnect + if (data.status === "connected" && options.mode === "reconnect") { + window.location.reload(); + } + + if(data.status === "connected") { + // With multiple windows, only show one connection message + if(!this.isConnected) { + Util.log(Util.capitalize(data.status)); + } + + this.connectionMessageShown = true; + } else { + if(data.status === "disconnected") { + this.addReconnectListeners(); + } + + Util.log(Util.capitalize(data.status)); + } + } else { + Util.log("Unknown event type", data); + } + } catch (e) { + Util.error(`Error parsing ${event.data}: ${e.message}`, e); + } + }); + + socket.addEventListener("open", () => { + // no reconnection when the connect is already open + this.removeReconnectListeners(); + }); + + socket.addEventListener("close", () => { + this.connectionMessageShown = false; + this.addReconnectListeners(); + }); + } + + reconnect() { + Util.log( "Reconnecting…" ); + this.init({ mode: "reconnect" }); + } + + async onreload({ subtype, files, build }) { + if (subtype === "css") { + for (let link of document.querySelectorAll(`link[rel="stylesheet"]`)) { + if (link.href) { + let url = new URL(link.href); + url.searchParams.set("_11ty", Date.now()); + link.href = url.toString(); + } + } + Util.log(`CSS updated without page reload.`); + } else { + let morphed = false; + + try { + if((build.templates || []).length > 0) { + // Important: using `./` in `./morphdom.js` allows the special `.11ty` folder to be changed upstream + const { default: morphdom } = await import(`./morphdom.js`); + + // { url, inputPath, content } + for (let template of build.templates || []) { + if (template.url === document.location.pathname) { + // Importantly, if this does not match but is still relevant (layout/include/etc), a full reload happens below. This could be improved. + if ((files || []).includes(template.inputPath)) { + // Notable limitation: this won’t re-run script elements or JavaScript page lifecycle events (load/DOMContentLoaded) + morphed = true; + + morphdom(document.documentElement, template.content, { + childrenOnly: true, + onBeforeElUpdated: function (fromEl, toEl) { + if (fromEl.nodeName === "SCRIPT" && toEl.nodeName === "SCRIPT") { + if(toEl.innerHTML !== fromEl.innerHTML) { + Util.log(`JavaScript modified, reload initiated.`); + window.location.reload(); + } + + return false; + } + + // Speed-up trick from morphdom docs + // https://dom.spec.whatwg.org/#concept-node-equals + if (fromEl.isEqualNode(toEl)) { + return false; + } + + if(Util.isEleventyLinkNodeMatch(fromEl, toEl)) { + return false; + } + + return true; + }, + addChild: function(parent, child) { + // Declarative Shadow DOM https://github.com/11ty/eleventy-dev-server/issues/90 + if(child.nodeName === "TEMPLATE" && child.hasAttribute("shadowrootmode")) { + let root = parent.shadowRoot; + if(root) { + // remove all shadow root children + while(root.firstChild) { + root.removeChild(root.firstChild); + } + } + for(let newChild of child.content.childNodes) { + root.appendChild(newChild); + } + } else { + parent.appendChild(child); + } + }, + onNodeAdded: function (node) { + if (node.nodeName === 'SCRIPT') { + Util.log(`JavaScript added, reload initiated.`); + window.location.reload(); + } + }, + onElUpdated: function(node) { + // Re-attach custom elements + if(customElements.get(node.tagName.toLowerCase())) { + let placeholder = document.createElement("div"); + node.replaceWith(placeholder); + requestAnimationFrame(() => { + placeholder.replaceWith(node); + placeholder = undefined; + }); + } + } + }); + + Util.matchRootAttributes(template.content); + Util.log(`HTML delta applied without page reload.`); + } + break; + } + } + } + } catch(e) { + Util.error( "Morphdom error", e ); + } + + if (!morphed) { + Util.log(`Page reload initiated.`); + window.location.reload(); + } + } + } + + addReconnectListeners() { + this.removeReconnectListeners(); + + window.addEventListener("focus", this.reconnectEventCallback); + window.addEventListener("visibilitychange", this.reconnectEventCallback); + } + + removeReconnectListeners() { + window.removeEventListener("focus", this.reconnectEventCallback); + window.removeEventListener("visibilitychange", this.reconnectEventCallback); + } +} + +let reloader = new EleventyReload(); +reloader.init(); \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-dev-server/cmd.js b/node_modules/@11ty/eleventy-dev-server/cmd.js new file mode 100755 index 0000000..695b845 --- /dev/null +++ b/node_modules/@11ty/eleventy-dev-server/cmd.js @@ -0,0 +1,77 @@ +#!/usr/bin/env node + +const pkg = require("./package.json"); + +// Node check +require("please-upgrade-node")(pkg, { + message: function (requiredVersion) { + return ( + "eleventy-dev-server requires Node " + + requiredVersion + + ". You will need to upgrade Node!" + ); + }, +}); + +const { Logger, Cli } = require("./cli.js"); + +const debug = require("debug")("Eleventy:DevServer"); + +try { + const defaults = Cli.getDefaultOptions(); + for(let key in defaults) { + if(key.toLowerCase() !== key) { + defaults[key.toLowerCase()] = defaults[key]; + delete defaults[key]; + } + } + + const argv = require("minimist")(process.argv.slice(2), { + string: [ + "dir", + "input", // alias for dir + "port", + ], + boolean: [ + "version", + "help", + "domdiff", + ], + default: defaults, + unknown: function (unknownArgument) { + throw new Error( + `We don’t know what '${unknownArgument}' is. Use --help to see the list of supported commands.` + ); + }, + }); + + debug("command: eleventy-dev-server %o", argv); + + process.on("unhandledRejection", (error, promise) => { + Logger.fatal("Unhandled rejection in promise:", promise, error); + }); + process.on("uncaughtException", (error) => { + Logger.fatal("Uncaught exception:", error); + }); + + if (argv.version) { + console.log(Cli.getVersion()); + } else if (argv.help) { + console.log(Cli.getHelp()); + } else { + let cli = new Cli(); + + cli.serve({ + input: argv.dir || argv.input, + port: argv.port, + domDiff: argv.domdiff, + }); + + process.on("SIGINT", async () => { + await cli.close(); + process.exitCode = 0; + }); + } +} catch (e) { + Logger.fatal("Fatal Error:", e) +} diff --git a/node_modules/@11ty/eleventy-dev-server/package.json b/node_modules/@11ty/eleventy-dev-server/package.json new file mode 100644 index 0000000..5c577bb --- /dev/null +++ b/node_modules/@11ty/eleventy-dev-server/package.json @@ -0,0 +1,58 @@ +{ + "name": "@11ty/eleventy-dev-server", + "version": "2.0.4", + "description": "A minimal, modern, generic, hot-reloading local web server to help web developers.", + "main": "server.js", + "scripts": { + "test": "npx ava --verbose", + "sample": "node cmd.js --input=test/stubs" + }, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + }, + "bin": { + "eleventy-dev-server": "./cmd.js" + }, + "keywords": [ + "eleventy", + "server", + "cli" + ], + "publishConfig": { + "access": "public" + }, + "author": { + "name": "Zach Leatherman", + "email": "zachleatherman@gmail.com", + "url": "https://zachleat.com/" + }, + "repository": { + "type": "git", + "url": "git://github.com/11ty/eleventy-dev-server.git" + }, + "bugs": "https://github.com/11ty/eleventy-dev-server/issues", + "homepage": "https://github.com/11ty/eleventy-dev-server/", + "dependencies": { + "@11ty/eleventy-utils": "^1.0.3", + "chokidar": "^3.6.0", + "debug": "^4.3.7", + "dev-ip": "^1.0.1", + "finalhandler": "^1.3.0", + "mime": "^3.0.0", + "minimist": "^1.2.8", + "morphdom": "^2.7.4", + "please-upgrade-node": "^3.2.0", + "send": "^0.19.0", + "ssri": "^11.0.0", + "urlpattern-polyfill": "^10.0.0", + "ws": "^8.18.0" + }, + "devDependencies": { + "ava": "^6.1.3" + } +} diff --git a/node_modules/@11ty/eleventy-dev-server/server.js b/node_modules/@11ty/eleventy-dev-server/server.js new file mode 100644 index 0000000..5e73964 --- /dev/null +++ b/node_modules/@11ty/eleventy-dev-server/server.js @@ -0,0 +1,950 @@ +const path = require("node:path"); +const fs = require("node:fs"); + +const finalhandler = require("finalhandler"); +const WebSocket = require("ws"); +const { WebSocketServer } = WebSocket; +const mime = require("mime"); +const ssri = require("ssri"); +const send = require("send"); +const devip = require("dev-ip"); +const chokidar = require("chokidar"); +const { TemplatePath, isPlainObject } = require("@11ty/eleventy-utils"); + +const debug = require("debug")("Eleventy:DevServer"); + +const pkg = require("./package.json"); +const wrapResponse = require("./server/wrapResponse.js"); + +if (!globalThis.URLPattern) { + require("urlpattern-polyfill"); +} + +const DEFAULT_OPTIONS = { + port: 8080, + liveReload: true, // Enable live reload at all + showAllHosts: false, // IP address based hosts (other than localhost) + injectedScriptsFolder: ".11ty", // Change the name of the special folder used for injected scripts + portReassignmentRetryCount: 10, // number of times to increment the port if in use + https: {}, // `key` and `cert`, required for http/2 and https + domDiff: true, // Use morphdom to apply DOM diffing delta updates to HTML + showVersion: false, // Whether or not to show the server version on the command line. + encoding: "utf-8", // Default file encoding + pathPrefix: "/", // May be overridden by Eleventy, adds a virtual base directory to your project + watch: [], // Globs to pass to separate dev server chokidar for watching + aliases: {}, // Aliasing feature + indexFileName: "index.html", // Allow custom index file name + useCache: false, // Use a cache for file contents + headers: {}, // Set default response headers + messageOnStart: ({ hosts, startupTime, version, options }) => { + let hostsStr = " started"; + if(Array.isArray(hosts) && hosts.length > 0) { + // TODO what happens when the cert doesn’t cover non-localhost hosts? + hostsStr = ` at ${hosts.join(" or ")}`; + } + + return `Server${hostsStr}${options.showVersion ? ` (v${version})` : ""}`; + }, + + onRequest: {}, // Maps URLPatterns to dynamic callback functions that run on a request from a client. + + // Example: + // "/foo/:name": function({ url, pattern, patternGroups }) { + // return { + // headers: { + // "Content-Type": "text/html", + // }, + // body: `${url} ${JSON.stringify(patternGroups)}` + // } + // } + + // Logger (fancier one is injected by Eleventy) + logger: { + info: console.log, + log: console.log, + error: console.error, + } +} + +class EleventyDevServer { + static getServer(...args) { + return new EleventyDevServer(...args); + } + + constructor(name, dir, options = {}) { + debug("Creating new Dev Server instance.") + this.name = name; + this.normalizeOptions(options); + + this.fileCache = {}; + // Directory to serve + if(!dir) { + throw new Error("Missing `dir` to serve."); + } + this.dir = dir; + this.logger = this.options.logger; + + if(this.options.watch.length > 0) { + this.getWatcher(); + } + } + + normalizeOptions(options = {}) { + this.options = Object.assign({}, DEFAULT_OPTIONS, options); + + // better names for options https://github.com/11ty/eleventy-dev-server/issues/41 + if(options.folder !== undefined) { + this.options.injectedScriptsFolder = options.folder; + delete this.options.folder; + } + if(options.domdiff !== undefined) { + this.options.domDiff = options.domdiff; + delete this.options.domdiff; + } + if(options.enabled !== undefined) { + this.options.liveReload = options.enabled; + delete this.options.enabled; + } + + this.options.pathPrefix = this.cleanupPathPrefix(this.options.pathPrefix); + } + + get watcher() { + if(!this._watcher) { + debug("Watching %O", this.options.watch); + // TODO if using Eleventy and `watch` option includes output folder (_site) this will trigger two update events! + this._watcher = chokidar.watch(this.options.watch, { + // TODO allow chokidar configuration extensions (or re-use the ones in Eleventy) + + ignored: ["**/node_modules/**", ".git"], + ignoreInitial: true, + + // same values as Eleventy + awaitWriteFinish: { + stabilityThreshold: 150, + pollInterval: 25, + }, + }); + + this._watcher.on("change", (path) => { + this.logger.log( `File changed: ${path} (skips build)` ); + this.reloadFiles([path]); + }); + + this._watcher.on("add", (path) => { + this.logger.log( `File added: ${path} (skips build)` ); + this.reloadFiles([path]); + }); + } + + return this._watcher; + } + + getWatcher() { + return this.watcher; + } + + watchFiles(files) { + if(Array.isArray(files)) { + files = files.map(entry => TemplatePath.stripLeadingDotSlash(entry)); + + debug("Also watching %O", files); + this.watcher.add(files); + } + } + + cleanupPathPrefix(pathPrefix) { + if(!pathPrefix || pathPrefix === "/") { + return "/"; + } + if(!pathPrefix.startsWith("/")) { + pathPrefix = `/${pathPrefix}` + } + if(!pathPrefix.endsWith("/")) { + pathPrefix = `${pathPrefix}/`; + } + return pathPrefix; + } + + // Allowed list of files that can be served from outside `dir` + setAliases(aliases) { + if(aliases) { + this.passthroughAliases = aliases; + debug( "Setting aliases (emulated passthrough copy) %O", aliases ); + } + } + + matchPassthroughAlias(url) { + let aliases = Object.assign({}, this.options.aliases, this.passthroughAliases); + for(let targetUrl in aliases) { + if(!targetUrl) { + continue; + } + + let file = aliases[targetUrl]; + if(url.startsWith(targetUrl)) { + let inputDirectoryPath = file + url.slice(targetUrl.length); + + // e.g. addPassthroughCopy("img/") but + // generated by the image plugin (written to the output folder) + // If they do not exist in the input directory, this will fallback to the output directory. + if(fs.existsSync(inputDirectoryPath)) { + return inputDirectoryPath; + } + } + } + return false; + } + + isFileInDirectory(dir, file) { + let absoluteDir = TemplatePath.absolutePath(dir); + let absoluteFile = TemplatePath.absolutePath(file); + return absoluteFile.startsWith(absoluteDir); + } + + getOutputDirFilePath(filepath, filename = "") { + let computedPath; + if(filename === ".html") { + // avoid trailing slash for filepath/.html requests + let prefix = path.join(this.dir, filepath); + if(prefix.endsWith(path.sep)) { + prefix = prefix.substring(0, prefix.length - path.sep.length); + } + computedPath = prefix + filename; + } else { + computedPath = path.join(this.dir, filepath, filename); + } + + computedPath = decodeURIComponent(computedPath); + + if(!filename) { // is a direct URL request (not an implicit .html or index.html add) + let alias = this.matchPassthroughAlias(filepath); + + if(alias) { + if(!this.isFileInDirectory(path.resolve("."), alias)) { + throw new Error("Invalid path"); + } + + return alias; + } + } + + // Check that the file is in the output path (error if folks try use `..` in the filepath) + if(!this.isFileInDirectory(this.dir, computedPath)) { + throw new Error("Invalid path"); + } + + return computedPath; + } + + isOutputFilePathExists(rawPath) { + return fs.existsSync(rawPath) && !TemplatePath.isDirectorySync(rawPath); + } + + /* Use conventions documented here https://www.zachleat.com/web/trailing-slash/ + * resource.html exists: + * /resource matches + * /resource/ redirects to /resource + * resource/index.html exists: + * /resource redirects to /resource/ + * /resource/ matches + * both resource.html and resource/index.html exists: + * /resource matches /resource.html + * /resource/ matches /resource/index.html + */ + mapUrlToFilePath(url) { + // Note: `localhost` is not important here, any host would work + let u = new URL(url, "http://localhost/"); + url = u.pathname; + + // Remove PathPrefix from start of URL + if (this.options.pathPrefix !== "/") { + // Requests to root should redirect to new pathPrefix + if(url === "/") { + return { + statusCode: 302, + url: this.options.pathPrefix, + } + } + + // Requests to anything outside of root should fail with 404 + if (!url.startsWith(this.options.pathPrefix)) { + return { + statusCode: 404, + }; + } + + url = url.slice(this.options.pathPrefix.length - 1); + } + + let rawPath = this.getOutputDirFilePath(url); + if (this.isOutputFilePathExists(rawPath)) { + return { + statusCode: 200, + filepath: rawPath, + }; + } + + let indexHtmlPath = this.getOutputDirFilePath(url, this.options.indexFileName); + let indexHtmlExists = fs.existsSync(indexHtmlPath); + + let htmlPath = this.getOutputDirFilePath(url, ".html"); + let htmlExists = fs.existsSync(htmlPath); + + // /resource/ => /resource/index.html + if (indexHtmlExists && url.endsWith("/")) { + return { + statusCode: 200, + filepath: indexHtmlPath, + }; + } + // /resource => resource.html + if (htmlExists && !url.endsWith("/")) { + return { + statusCode: 200, + filepath: htmlPath, + }; + } + + // /resource => redirect to /resource/ + if (indexHtmlExists && !url.endsWith("/")) { + return { + statusCode: 301, + url: u.pathname + "/", + }; + } + + // /resource/ => redirect to /resource + if (htmlExists && url.endsWith("/")) { + return { + statusCode: 301, + url: u.pathname.substring(0, u.pathname.length - 1), + }; + } + + return { + statusCode: 404, + }; + } + + _getFileContents(localpath, rootDir) { + if(this.options.useCache && this.fileCache[localpath]) { + return this.fileCache[localpath]; + } + + let filepath; + let searchLocations = []; + + if(rootDir) { + searchLocations.push(TemplatePath.absolutePath(rootDir, localpath)); + } + + // fallbacks for file:../ installations + searchLocations.push(TemplatePath.absolutePath(__dirname, localpath)); + searchLocations.push(TemplatePath.absolutePath(__dirname, "../../../", localpath)); + + for(let loc of searchLocations) { + if(fs.existsSync(loc)) { + filepath = loc; + break; + } + } + + let contents = fs.readFileSync(filepath, { + encoding: this.options.encoding, + }); + + if(this.options.useCache) { + this.fileCache[localpath] = contents; + } + return contents; + } + + augmentContentWithNotifier(content, inlineContents = false, options = {}) { + let { integrityHash, scriptContents } = options; + if(!scriptContents) { + scriptContents = this._getFileContents("./client/reload-client.js"); + } + if(!integrityHash) { + integrityHash = ssri.fromData(scriptContents); + } + + // This isn’t super necessary because it’s a local file, but it’s included anyway + let script = ``; + + if (content.includes("")) { + return content.replace("", `${script}`); + } + + // If the HTML document contains an importmap, insert the module script after the importmap element + let importMapRegEx = / + +``` + +* Existing calls via WebC helpers `getCss` or `getJs` (e.g. ` +{% endcss %} +* a way to declare dependencies? or just defer to buckets here +* What if we want to add code duplicates? Adding `alert(1);` `alert(1);` to alert twice? +* sourcemaps (maybe via magic-string module or https://www.npmjs.com/package/concat-with-sourcemaps) +--> \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-plugin-bundle/eleventy.bundle.js b/node_modules/@11ty/eleventy-plugin-bundle/eleventy.bundle.js new file mode 100644 index 0000000..1afb132 --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/eleventy.bundle.js @@ -0,0 +1,66 @@ +import { createRequire } from "node:module"; +import bundleManagersPlugin from "./src/eleventy.bundleManagers.js"; +import pruneEmptyBundlesPlugin from "./src/eleventy.pruneEmptyBundles.js"; +import shortcodesPlugin from "./src/eleventy.shortcodes.js"; +import debugUtil from "debug"; + +const require = createRequire(import.meta.url); +const debug = debugUtil("Eleventy:Bundle"); +const pkg = require("./package.json"); + +function normalizeOptions(options = {}) { + options = Object.assign({ + // Plugin defaults + bundles: [], // extra bundles: css, js, and html are guaranteed unless `bundles: false` + toFileDirectory: "bundle", + // post-process + transforms: [], + hoistDuplicateBundlesFor: [], + bundleExportKey: "bundle", // use a `bundle` export in a 11ty.js template to populate bundles + }, options); + + if(options.bundles !== false) { + options.bundles = Array.from(new Set(["css", "js", "html", ...(options.bundles || [])])); + } + + return options; +} + +function eleventyBundlePlugin(eleventyConfig, pluginOptions = {}) { + eleventyConfig.versionCheck(pkg["11ty"].compatibility); + + pluginOptions = normalizeOptions(pluginOptions); + + if(!("getBundleManagers" in eleventyConfig) && !("addBundle" in eleventyConfig)) { + bundleManagersPlugin(eleventyConfig, pluginOptions); + } + + pruneEmptyBundlesPlugin(eleventyConfig, pluginOptions); + + // should this be unique too? + shortcodesPlugin(eleventyConfig, pluginOptions); + + if(Array.isArray(pluginOptions.bundles)) { + debug("Adding bundles via `addPlugin`: %o", pluginOptions.bundles) + pluginOptions.bundles.forEach(name => { + let isHoisting = Array.isArray(pluginOptions.hoistDuplicateBundlesFor) && pluginOptions.hoistDuplicateBundlesFor.includes(name); + + eleventyConfig.addBundle(name, { + hoist: isHoisting, + outputFileExtension: name, // default as `name` + shortcodeName: name, // `false` will skip shortcode + transforms: pluginOptions.transforms, + toFileDirectory: pluginOptions.toFileDirectory, + bundleExportKey: pluginOptions.bundleExportKey, // `false` will skip bundle export + }); + }); + } +}; + +// This is used to find the package name for this plugin (used in eleventy-plugin-webc to prevent dupes) +Object.defineProperty(eleventyBundlePlugin, "eleventyPackage", { + value: pkg.name +}); + +export default eleventyBundlePlugin; +export { normalizeOptions }; diff --git a/node_modules/@11ty/eleventy-plugin-bundle/package.json b/node_modules/@11ty/eleventy-plugin-bundle/package.json new file mode 100644 index 0000000..40d0cdf --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/package.json @@ -0,0 +1,62 @@ +{ + "name": "@11ty/eleventy-plugin-bundle", + "version": "3.0.0", + "description": "Little bundles of code, little bundles of joy.", + "main": "eleventy.bundle.js", + "type": "module", + "scripts": { + "sample": "DEBUG=Eleventy:Bundle npx @11ty/eleventy --config=sample/sample-config.js --input=sample --serve", + "test": "npx ava" + }, + "publishConfig": { + "access": "public" + }, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "11ty": { + "compatibility": ">=3.0.0-alpha" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + }, + "keywords": [ + "eleventy", + "eleventy-plugin" + ], + "repository": { + "type": "git", + "url": "git://github.com/11ty/eleventy-plugin-bundle.git" + }, + "bugs": "https://github.com/11ty/eleventy-plugin-bundle/issues", + "homepage": "https://www.11ty.dev/", + "author": { + "name": "Zach Leatherman", + "email": "zachleatherman@gmail.com", + "url": "https://zachleat.com/" + }, + "ava": { + "failFast": true, + "files": [ + "test/*.js", + "test/*.mjs" + ], + "ignoredByWatcher": [ + "**/_site/**", + ".cache" + ] + }, + "devDependencies": { + "@11ty/eleventy": "3.0.0-alpha.20", + "ava": "^5.3.1", + "postcss": "^8.4.31", + "postcss-nested": "^6.0.1", + "sass": "^1.69.5" + }, + "dependencies": { + "debug": "^4.3.4", + "posthtml-match-helper": "^2.0.2" + } +} diff --git a/node_modules/@11ty/eleventy-plugin-bundle/src/BundleFileOutput.js b/node_modules/@11ty/eleventy-plugin-bundle/src/BundleFileOutput.js new file mode 100644 index 0000000..66fc929 --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/BundleFileOutput.js @@ -0,0 +1,76 @@ +import fs from "node:fs"; +import path from "node:path"; +import { createHash } from "node:crypto"; +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:Bundle"); + +const hashCache = {}; +const directoryExistsCache = {}; +const writingCache = new Set(); + +class BundleFileOutput { + constructor(outputDirectory, bundleDirectory) { + this.outputDirectory = outputDirectory; + this.bundleDirectory = bundleDirectory || ""; + this.hashLength = 10; + this.fileExtension = undefined; + } + + setFileExtension(ext) { + this.fileExtension = ext; + } + + getFilenameHash(content) { + if(hashCache[content]) { + return hashCache[content]; + } + + let hash = createHash("sha256"); + hash.update(content); + let base64hash = hash.digest('base64').replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); + let filenameHash = base64hash.substring(0, this.hashLength); + hashCache[content] = filenameHash; + return filenameHash; + } + + getFilename(filename, extension) { + return filename + (extension && !extension.startsWith(".") ? `.${extension}` : ""); + } + + modifyPathToUrl(dir, filename) { + return "/" + path.join(dir, filename).split(path.sep).join("/"); + } + + writeBundle(content, type, writeToFileSystem) { + // do not write a bundle, do not return a file name is content is empty + if(!content) { + return; + } + + let dir = path.join(this.outputDirectory, this.bundleDirectory); + let filenameHash = this.getFilenameHash(content); + let filename = this.getFilename(filenameHash, this.fileExtension || type); + + if(writeToFileSystem) { + let fullPath = path.join(dir, filename); + + // no duplicate writes, this may be improved with a fs exists check, but it would only save the first write + if(!writingCache.has(fullPath)) { + writingCache.add(fullPath); + + if(!directoryExistsCache[dir]) { + fs.mkdirSync(dir, { recursive: true }); + directoryExistsCache[dir] = true; + } + + debug("Writing bundle %o", fullPath); + fs.writeFileSync(fullPath, content); + } + } + + return this.modifyPathToUrl(this.bundleDirectory, filename); + } +} + +export { BundleFileOutput }; diff --git a/node_modules/@11ty/eleventy-plugin-bundle/src/CodeManager.js b/node_modules/@11ty/eleventy-plugin-bundle/src/CodeManager.js new file mode 100644 index 0000000..53677af --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/CodeManager.js @@ -0,0 +1,209 @@ +import { BundleFileOutput } from "./BundleFileOutput.js"; +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:Bundle"); +const DEBUG_LOG_TRUNCATION_SIZE = 200; + +class CodeManager { + // code is placed in this bucket by default + static DEFAULT_BUCKET_NAME = "default"; + + // code is hoisted to this bucket when necessary + static HOISTED_BUCKET_NAME = "default"; + + constructor(name) { + this.name = name; + this.trimOnAdd = true; + // TODO unindent on add + this.reset(); + this.transforms = []; + this.isHoisting = true; + this.fileExtension = undefined; + this.toFileDirectory = undefined; + this.bundleExportKey = "bundle"; + } + + setFileExtension(ext) { + this.fileExtension = ext; + } + + setHoisting(enabled) { + this.isHoisting = !!enabled; + } + + setBundleDirectory(dir) { + this.toFileDirectory = dir; + } + + setBundleExportKey(key) { + this.bundleExportKey = key; + } + + getBundleExportKey() { + return this.bundleExportKey; + } + + reset() { + this.pages = {}; + } + + static normalizeBuckets(bucket) { + if(Array.isArray(bucket)) { + return bucket; + } else if(typeof bucket === "string") { + return bucket.split(","); + } + return [CodeManager.DEFAULT_BUCKET_NAME]; + } + + setTransforms(transforms) { + if(!Array.isArray(transforms)) { + throw new Error("Array expected to setTransforms"); + } + + this.transforms = transforms; + } + + _initBucket(pageUrl, bucket) { + if(!this.pages[pageUrl][bucket]) { + this.pages[pageUrl][bucket] = new Set(); + } + } + + addToPage(pageUrl, code = [], bucket) { + if(!Array.isArray(code) && code) { + code = [code]; + } + if(code.length === 0) { + return; + } + + if(!this.pages[pageUrl]) { + this.pages[pageUrl] = {}; + } + + let buckets = CodeManager.normalizeBuckets(bucket); + + let codeContent = code.map(entry => { + if(this.trimOnAdd) { + return entry.trim(); + } + return entry; + }); + + + for(let b of buckets) { + this._initBucket(pageUrl, b); + + let debugLoggedContent = codeContent.join("\n"); + debug("Adding code to bundle %o for %o (bucket: %o, size: %o): %o", this.name, pageUrl, b, debugLoggedContent.length, debugLoggedContent.length > DEBUG_LOG_TRUNCATION_SIZE ? debugLoggedContent.slice(0, DEBUG_LOG_TRUNCATION_SIZE) + "…" : debugLoggedContent); + for(let content of codeContent) { + if(content) { + this.pages[pageUrl][b].add(content); + } + } + } + } + + async runTransforms(str, pageData, buckets) { + for (let callback of this.transforms) { + str = await callback.call( + { + page: pageData, + type: this.name, + buckets: buckets + }, + str + ); + } + + return str; + } + + getBucketsForPage(pageData) { + let pageUrl = pageData.url; + if(!this.pages[pageUrl]) { + return []; + } + return Object.keys(this.pages[pageUrl]); + } + + getRawForPage(pageData, buckets = undefined) { + let url = pageData.url; + if(!this.pages[url]) { + debug("No bundle code found for %o on %o, %O", this.name, url, this.pages); + return new Set(); + } + + buckets = CodeManager.normalizeBuckets(buckets); + + debug("Retrieving %o for %o (buckets: %o)", this.name, url, buckets); + let set = new Set(); + for(let b of buckets) { + if(!this.pages[url][b]) { + // Just continue, if you retrieve code from a bucket that doesn’t exist or has no code, it will return an empty set + continue; + } + + for(let entry of this.pages[url][b]) { + set.add(entry); + } + } + + return set; + } + + async getForPage(pageData, buckets = undefined) { + let set = this.getRawForPage(pageData, buckets); + let bundleContent = Array.from(set).join("\n"); + + // returns promise + return this.runTransforms(bundleContent, pageData, buckets); + } + + async writeBundle(pageData, buckets, options = {}) { + let url = pageData.url; + if(!this.pages[url]) { + debug("No bundle code found for %o on %o, %O", this.name, url, this.pages); + return ""; + } + + let { output, write } = options; + + buckets = CodeManager.normalizeBuckets(buckets); + + // TODO the bundle output URL might be useful in the transforms for sourcemaps + let content = await this.getForPage(pageData, buckets); + let writer = new BundleFileOutput(output, this.toFileDirectory); + writer.setFileExtension(this.fileExtension); + return writer.writeBundle(content, this.name, write); + } + + // Used when a bucket is output multiple times on a page and needs to be hoisted + hoistBucket(pageData, bucketName) { + let newTargetBucketName = CodeManager.HOISTED_BUCKET_NAME; + if(!this.isHoisting || bucketName === newTargetBucketName) { + return; + } + + let url = pageData.url; + if(!this.pages[url] || !this.pages[url][bucketName]) { + debug("No bundle code found for %o on %o, %O", this.name, url, this.pages); + return; + } + + debug("Code in bucket (%o) is being hoisted to a new bucket (%o)", bucketName, newTargetBucketName); + + this._initBucket(url, newTargetBucketName); + + for(let codeEntry of this.pages[url][bucketName]) { + this.pages[url][bucketName].delete(codeEntry); + this.pages[url][newTargetBucketName].add(codeEntry); + } + + // delete the bucket + delete this.pages[url][bucketName]; + } +} + +export { CodeManager }; diff --git a/node_modules/@11ty/eleventy-plugin-bundle/src/OutOfOrderRender.js b/node_modules/@11ty/eleventy-plugin-bundle/src/OutOfOrderRender.js new file mode 100644 index 0000000..1455bb5 --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/OutOfOrderRender.js @@ -0,0 +1,153 @@ +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:Bundle"); + +/* This class defers any `bundleGet` calls to a post-build transform step, + * to allow `getBundle` to be called before all of the `css` additions have been processed + */ +class OutOfOrderRender { + static SPLIT_REGEX = /(\/\*__EleventyBundle:[^:]*:[^:]*:[^:]*:EleventyBundle__\*\/)/; + static SEPARATOR = ":"; + + constructor(content) { + this.content = content; + this.managers = {}; + } + + // type if `get` (return string) or `file` (bundle writes to file, returns file url) + static getAssetKey(type, name, bucket) { + if(Array.isArray(bucket)) { + bucket = bucket.join(","); + } else if(typeof bucket === "string") { + } else { + bucket = ""; + } + return `/*__EleventyBundle:${type}:${name}:${bucket || "default"}:EleventyBundle__*/` + } + + static parseAssetKey(str) { + if(str.startsWith("/*__EleventyBundle:")) { + let [prefix, type, name, bucket, suffix] = str.split(OutOfOrderRender.SEPARATOR); + return { type, name, bucket }; + } + return false; + } + + setAssetManager(name, assetManager) { + this.managers[name] = assetManager; + } + + setOutputDirectory(dir) { + this.outputDirectory = dir; + } + + normalizeMatch(match) { + let ret = OutOfOrderRender.parseAssetKey(match) + return ret || match; + } + + findAll() { + let matches = this.content.split(OutOfOrderRender.SPLIT_REGEX); + let ret = []; + for(let match of matches) { + ret.push(this.normalizeMatch(match)); + } + return ret; + } + + setWriteToFileSystem(isWrite) { + this.writeToFileSystem = isWrite; + } + + getAllBucketsForPage(pageData) { + let availableBucketsForPage = new Set(); + for(let name in this.managers) { + for(let bucket of this.managers[name].getBucketsForPage(pageData)) { + availableBucketsForPage.add(`${name}::${bucket}`); + } + } + return availableBucketsForPage; + } + + getManager(name) { + if(!this.managers[name]) { + throw new Error(`No asset manager found for ${name}. Known names: ${Object.keys(this.managers)}`); + } + return this.managers[name]; + } + + async replaceAll(pageData) { + let matches = this.findAll(); + let availableBucketsForPage = this.getAllBucketsForPage(pageData); + let usedBucketsOnPage = new Set(); + let bucketsOutputStringCount = {}; + let bucketsFileCount = {}; + + for(let match of matches) { + if(typeof match === "string") { + continue; + } + + // type is `file` or `get` + let {type, name, bucket} = match; + let key = `${name}::${bucket}`; + if(!usedBucketsOnPage.has(key)) { + usedBucketsOnPage.add(key); + } + + if(type === "get") { + if(!bucketsOutputStringCount[key]) { + bucketsOutputStringCount[key] = 0; + } + bucketsOutputStringCount[key]++; + } else if(type === "file") { + if(!bucketsFileCount[key]) { + bucketsFileCount[key] = 0; + } + bucketsFileCount[key]++; + } + } + + // Hoist code in non-default buckets that are output multiple times + // Only hoist if 2+ `get` OR 1+ `get` and 1+ `file` + for(let bucketInfo in bucketsOutputStringCount) { + let stringOutputCount = bucketsOutputStringCount[bucketInfo]; + if(stringOutputCount > 1 || stringOutputCount === 1 && bucketsFileCount[bucketInfo] > 0) { + let [name, bucketName] = bucketInfo.split("::"); + this.getManager(name).hoistBucket(pageData, bucketName); + } + } + + let content = await Promise.all(matches.map(match => { + if(typeof match === "string") { + return match; + } + + let {type, name, bucket} = match; + let manager = this.getManager(name); + + if(type === "get") { + // returns promise + return manager.getForPage(pageData, bucket); + } else if(type === "file") { + // returns promise + return manager.writeBundle(pageData, bucket, { + output: this.outputDirectory, + write: this.writeToFileSystem, + }); + } + return ""; + })); + + for(let bucketInfo of availableBucketsForPage) { + if(!usedBucketsOnPage.has(bucketInfo)) { + let [name, bucketName] = bucketInfo.split("::"); + debug(`WARNING! \`${pageData.inputPath}\` has unbundled \`${name}\` assets (in the '${bucketName}' bucket) that were not written to or used on the page. You might want to add a call to \`getBundle('${name}', '${bucketName}')\` to your content! Learn more: https://github.com/11ty/eleventy-plugin-bundle#asset-bucketing`); + } + } + + return content.join(""); + } +} + +export { OutOfOrderRender }; diff --git a/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.bundleManagers.js b/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.bundleManagers.js new file mode 100644 index 0000000..0ee1bf4 --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.bundleManagers.js @@ -0,0 +1,74 @@ +import { createRequire } from "node:module"; +import debugUtil from "debug"; +import { CodeManager } from "./CodeManager.js"; + +const require = createRequire(import.meta.url); +const debug = debugUtil("Eleventy:Bundle"); +const pkg = require("../package.json"); + +function eleventyBundleManagers(eleventyConfig, pluginOptions = {}) { + if("getBundleManagers" in eleventyConfig || "addBundle" in eleventyConfig) { + throw new Error("Duplicate plugin calls for " + pkg.name); + } + + let managers = {}; + + function addBundle(name, bundleOptions = {}) { + if(name in managers) { + debug("Bundle exists %o, skipping.", name); + // note: shortcode must still be added + } else { + debug("Creating new bundle %o", name); + managers[name] = new CodeManager(name); + + if(bundleOptions.hoist !== undefined) { + managers[name].setHoisting(bundleOptions.hoist); + } + + if(bundleOptions.bundleExportKey !== undefined) { + managers[name].setBundleExportKey(bundleOptions.bundleExportKey); + } + + if(bundleOptions.outputFileExtension) { + managers[name].setFileExtension(bundleOptions.outputFileExtension); + } + + if(bundleOptions.toFileDirectory) { + managers[name].setBundleDirectory(bundleOptions.toFileDirectory); + } + + if(bundleOptions.transforms) { + managers[name].setTransforms(bundleOptions.transforms); + } + } + + // if undefined, defaults to `name` + if(bundleOptions.shortcodeName !== false) { + let shortcodeName = bundleOptions.shortcodeName || name; + + // e.g. `css` shortcode to add code to page bundle + // These shortcode names are not configurable on purpose (for wider plugin compatibility) + eleventyConfig.addPairedShortcode(shortcodeName, function addContent(content, bucket, explicitUrl) { + let url = explicitUrl || this.page?.url; + if(url) { // don’t add if a file doesn’t have an output URL + managers[name].addToPage(url, content, bucket); + } + return ""; + }); + } + }; + + eleventyConfig.addBundle = addBundle; + + eleventyConfig.getBundleManagers = function() { + return managers; + }; + + eleventyConfig.on("eleventy.before", async () => { + for(let key in managers) { + managers[key].reset(); + } + }); +}; + +export default eleventyBundleManagers; diff --git a/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.pruneEmptyBundles.js b/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.pruneEmptyBundles.js new file mode 100644 index 0000000..8ece03a --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.pruneEmptyBundles.js @@ -0,0 +1,88 @@ +import matchHelper from "posthtml-match-helper"; +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:Bundle"); + +const ATTRS = { + keep: "eleventy:keep" +} + +function getTextNodeContent(node) { + if (!node.content) { + return ""; + } + + return node.content + .map((entry) => { + if (typeof entry === "string") { + return entry; + } + if (Array.isArray(entry.content)) { + return getTextNodeContent(entry); + } + return ""; + }) + .join(""); +} + +function eleventyPruneEmptyBundles(eleventyConfig, options = {}) { + // Right now script[src],link[rel="stylesheet"] nodes are removed if the final bundles are empty. + // `false` to disable + options.pruneEmptySelector = options.pruneEmptySelector ?? `style,script,link[rel="stylesheet"]`; + + // `false` disables this plugin + if(options.pruneEmptySelector === false) { + return; + } + + if(!eleventyConfig.htmlTransformer || !eleventyConfig.htmlTransformer?.constructor?.SUPPORTS_PLUGINS_ENABLED_CALLBACK) { + debug("You will need to upgrade your version of Eleventy core to remove empty bundle tags automatically (v3 or newer)."); + return; + } + + eleventyConfig.htmlTransformer.addPosthtmlPlugin( + "html", + function (pluginOptions = {}) { + return function (tree) { + tree.match(matchHelper(options.pruneEmptySelector), function (node) { + if(node.attrs && node.attrs[ATTRS.keep] !== undefined) { + delete node.attrs[ATTRS.keep]; + return node; + } + + // + if(node.tag === "link") { + if(node.attrs?.rel === "stylesheet" && (node.attrs?.href || "").trim().length === 0) { + return false; + } + } else { + let content = getTextNodeContent(node); + + if(!content) { + // or + if(node.tag === "script" && (node.attrs?.src || "").trim().length === 0) { + return false; + } + + // + if(node.tag === "style") { + return false; + } + } + } + + + return node; + }); + }; + }, + { + // the `enabled` callback for plugins is available on v3.0.0-alpha.20+ and v3.0.0-beta.2+ + enabled: () => { + return Object.keys(eleventyConfig.getBundleManagers()).length > 0; + } + } + ); +} + +export default eleventyPruneEmptyBundles; diff --git a/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.shortcodes.js b/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.shortcodes.js new file mode 100644 index 0000000..efb598d --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.shortcodes.js @@ -0,0 +1,83 @@ +import { OutOfOrderRender } from "./OutOfOrderRender.js"; +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:Bundle"); + +function eleventyBundleShortcodes(eleventyConfig, pluginOptions = {}) { + let managers = eleventyConfig.getBundleManagers(); + let writeToFileSystem = true; + let pagesUsingBundles = {}; + + eleventyConfig.on("eleventy.before", async ({ outputMode }) => { + if(Object.keys(managers).length === 0) { + return; + } + + pagesUsingBundles = {}; + + if(outputMode !== "fs") { + writeToFileSystem = false; + debug("Skipping writing to the file system due to output mode: %o", outputMode); + } + }); + + // e.g. `getBundle` shortcode to get code in current page bundle + // bucket can be an array + // This shortcode name is not configurable on purpose (for wider plugin compatibility) + eleventyConfig.addShortcode("getBundle", function getContent(type, bucket, explicitUrl) { + if(!type || !(type in managers) || Object.keys(managers).length === 0) { + throw new Error(`Invalid bundle type: ${type}. Available options: ${Object.keys(managers)}`); + } + + let url = explicitUrl || this.page?.url; + if(url) { + pagesUsingBundles[url] = true; + } + + return OutOfOrderRender.getAssetKey("get", type, bucket); + }); + + // write a bundle to the file system + // This shortcode name is not configurable on purpose (for wider plugin compatibility) + eleventyConfig.addShortcode("getBundleFileUrl", function(type, bucket, explicitUrl) { + if(!type || !(type in managers) || Object.keys(managers).length === 0) { + throw new Error(`Invalid bundle type: ${type}. Available options: ${Object.keys(managers)}`); + } + + let url = explicitUrl || this.page?.url; + if(url) { + pagesUsingBundles[url] = true; + } + + return OutOfOrderRender.getAssetKey("file", type, bucket); + }); + + eleventyConfig.addTransform("@11ty/eleventy-bundle", function(content) { + // `page.outputPath` is required to perform bundle transform, unless + // we're running in Eleventy Serverless. + let missingOutputPath = !this.page.outputPath && process.env.ELEVENTY_SERVERLESS !== "true"; + if(missingOutputPath || typeof content !== "string") { + return content; + } + + // Only run if managers are in play + // Only run on pages that have fetched bundles via `getBundle` or `getBundleFileUrl` + if(Object.keys(managers).length === 0 || this.page.url && !pagesUsingBundles[this.page.url]) { + return content; + } + + debug("Processing %o", this.page.url); + + let render = new OutOfOrderRender(content); + for(let key in managers) { + render.setAssetManager(key, managers[key]); + } + + render.setOutputDirectory(eleventyConfig.directories.output); + render.setWriteToFileSystem(writeToFileSystem); + + return render.replaceAll(this.page); + }); +}; + +export default eleventyBundleShortcodes; diff --git a/node_modules/@11ty/eleventy-utils/LICENSE b/node_modules/@11ty/eleventy-utils/LICENSE new file mode 100644 index 0000000..2fde565 --- /dev/null +++ b/node_modules/@11ty/eleventy-utils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Zach Leatherman @zachleat + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@11ty/eleventy-utils/README.md b/node_modules/@11ty/eleventy-utils/README.md new file mode 100644 index 0000000..0581359 --- /dev/null +++ b/node_modules/@11ty/eleventy-utils/README.md @@ -0,0 +1,29 @@ +

eleventy Logo

+ +# eleventy-utils 🕚⚡️🎈🐀 + +Low level internal utilities to be shared amongst Eleventy projects. + +## ➡ [Documentation](https://www.11ty.dev/docs/) + +- Please star [Eleventy on GitHub](https://github.com/11ty/eleventy/)! +- Follow us on Twitter [@eleven_ty](https://twitter.com/eleven_ty) +- Support [11ty on Open Collective](https://opencollective.com/11ty) +- [11ty on npm](https://www.npmjs.com/org/11ty) +- [11ty on GitHub](https://github.com/11ty) + +[![npm Version](https://img.shields.io/npm/v/@11ty/eleventy-utils.svg?style=for-the-badge)](https://www.npmjs.com/package/@11ty/eleventy-utils) + +## Installation + +``` +npm install @11ty/eleventy-utils +``` + +## Tests + +``` +npm run test +``` + +- We use the [ava JavaScript test runner](https://github.com/avajs/ava) ([Assertions documentation](https://github.com/avajs/ava/blob/master/docs/03-assertions.md)) diff --git a/node_modules/@11ty/eleventy-utils/index.js b/node_modules/@11ty/eleventy-utils/index.js new file mode 100644 index 0000000..1cfa0e2 --- /dev/null +++ b/node_modules/@11ty/eleventy-utils/index.js @@ -0,0 +1,11 @@ +const TemplatePath = require("./src/TemplatePath.js"); +const isPlainObject = require("./src/IsPlainObject.js"); +const Merge = require("./src/Merge.js"); +const { DeepCopy } = Merge; + +module.exports = { + TemplatePath, + isPlainObject, + Merge, + DeepCopy, +}; \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-utils/package.json b/node_modules/@11ty/eleventy-utils/package.json new file mode 100644 index 0000000..eca3bce --- /dev/null +++ b/node_modules/@11ty/eleventy-utils/package.json @@ -0,0 +1,47 @@ +{ + "name": "@11ty/eleventy-utils", + "version": "1.0.3", + "description": "Low level internal utilities to be shared amongst Eleventy projects", + "main": "index.js", + "files": [ + "src", + "src/**", + "index.js", + "!test", + "!test/**" + ], + "scripts": { + "test": "npx ava --verbose" + }, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + }, + "keywords": [ + "eleventy" + ], + "publishConfig": { + "access": "public" + }, + "author": { + "name": "Zach Leatherman", + "email": "zachleatherman@gmail.com", + "url": "https://zachleat.com/" + }, + "repository": { + "type": "git", + "url": "git://github.com/11ty/eleventy-utils.git" + }, + "bugs": "https://github.com/11ty/eleventy-utils/issues", + "homepage": "https://github.com/11ty/eleventy-utils/", + "dependencies": { + "normalize-path": "^3.0.0" + }, + "devDependencies": { + "ava": "^6.1.3" + } +} diff --git a/node_modules/@11ty/eleventy-utils/src/IsPlainObject.js b/node_modules/@11ty/eleventy-utils/src/IsPlainObject.js new file mode 100644 index 0000000..1d4c752 --- /dev/null +++ b/node_modules/@11ty/eleventy-utils/src/IsPlainObject.js @@ -0,0 +1,24 @@ +/* Prior art: this utility was created for https://github.com/11ty/eleventy/issues/2214 + + * Inspired by implementations from `is-what`, `typechecker`, `jQuery`, and `lodash` + + * `is-what` + * More reading at https://www.npmjs.com/package/is-what#user-content-isplainobject-vs-isanyobject + * if (Object.prototype.toString.call(value).slice(8, -1) !== 'Object') return false; + * return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype; + + * `typechecker` + * return value !== null && typeof value === 'object' && value.__proto__ === Object.prototype; + + * Notably jQuery and lodash have very similar implementations. + + * For later, remember the `value === Object(value)` trick + */ + +module.exports = function (value) { + if (value === null || typeof value !== "object") { + return false; + } + let proto = Object.getPrototypeOf(value); + return !proto || proto === Object.prototype; +}; diff --git a/node_modules/@11ty/eleventy-utils/src/Merge.js b/node_modules/@11ty/eleventy-utils/src/Merge.js new file mode 100644 index 0000000..c3cfbaf --- /dev/null +++ b/node_modules/@11ty/eleventy-utils/src/Merge.js @@ -0,0 +1,84 @@ +"use strict"; +// above is required for Object.freeze to fail correctly. + +const isPlainObject = require("./IsPlainObject.js"); + +const OVERRIDE_PREFIX = "override:"; + +function cleanKey(key, prefix) { + if (prefix && key.startsWith(prefix)) { + return key.slice(prefix.length); + } + return key; +} + +function getMergedItem(target, source, prefixes = {}) { + let { override } = prefixes; + + // Shortcut for frozen source (if target does not exist) + if (!target && isPlainObject(source) && Object.isFrozen(source)) { + return source; + } + + let sourcePlainObjectShortcut; + if (!target && isPlainObject(source)) { + // deep copy objects to avoid sharing and to effect key renaming + target = {}; + sourcePlainObjectShortcut = true; + } + + if (Array.isArray(target) && Array.isArray(source)) { + return target.concat(source); + } else if (isPlainObject(target)) { + if (sourcePlainObjectShortcut || isPlainObject(source)) { + for (let key in source) { + let overrideKey = cleanKey(key, override); + + // An error happens here if the target is frozen + target[overrideKey] = getMergedItem(target[key], source[key], prefixes); + } + } + return target; + } + // number, string, class instance, etc + return source; +} + +// The same as Merge but without override prefixes +function DeepCopy(targetObject, ...sources) { + for (let source of sources) { + if (!source) { + continue; + } + + targetObject = getMergedItem(targetObject, source); + } + return targetObject; +} + +function Merge(target, ...sources) { + // Remove override prefixes from root target. + if (isPlainObject(target)) { + for (let key in target) { + if (key.indexOf(OVERRIDE_PREFIX) === 0) { + target[key.slice(OVERRIDE_PREFIX.length)] = target[key]; + delete target[key]; + } + } + } + + for (let source of sources) { + if (!source) { + continue; + } + + target = getMergedItem(target, source, { + override: OVERRIDE_PREFIX, + }); + } + + return target; +} + +module.exports = Merge; +module.exports.DeepCopy = DeepCopy; diff --git a/node_modules/@11ty/eleventy-utils/src/TemplatePath.js b/node_modules/@11ty/eleventy-utils/src/TemplatePath.js new file mode 100644 index 0000000..efbf464 --- /dev/null +++ b/node_modules/@11ty/eleventy-utils/src/TemplatePath.js @@ -0,0 +1,368 @@ +const path = require("path"); +const normalize = require("normalize-path"); +const fs = require("fs"); + +function TemplatePath() {} + +/** + * @returns {String} the absolute path to Eleventy’s project directory. + */ +TemplatePath.getWorkingDir = function () { + return TemplatePath.normalize(path.resolve(".")); +}; + +/** + * Returns the directory portion of a path. + * Works for directory and file paths and paths ending in a glob pattern. + * + * @param {String} path A path + * @returns {String} the directory portion of a path. + */ +TemplatePath.getDir = function (path) { + if (TemplatePath.isDirectorySync(path)) { + return path; + } + + return TemplatePath.getDirFromFilePath(path); +}; + +/** + * Returns the directory portion of a path that either points to a file + * or ends in a glob pattern. If `path` points to a directory, + * the returned value will have its last path segment stripped + * due to how [`path.parse`][1] works. + * + * [1]: https://nodejs.org/api/path.html#path_path_parse_path + * + * @param {String} path A path + * @returns {String} the directory portion of a path. + */ +TemplatePath.getDirFromFilePath = function (filePath) { + return path.parse(filePath).dir || "."; +}; + +/** + * Returns the last path segment in a path (no leading/trailing slashes). + * + * Assumes [`path.parse`][1] was called on `path` before. + * + * [1]: https://nodejs.org/api/path.html#path_path_parse_path + * + * @param {String} path A path + * @returns {String} the last path segment in a path + */ +TemplatePath.getLastPathSegment = function (path) { + if (!path.includes("/")) { + return path; + } + + // Trim a trailing slash if there is one + path = path.replace(/\/$/, ""); + + return path.substr(path.lastIndexOf("/") + 1); +}; + +/** + * @param {String} path A path + * @returns {String[]} an array of paths pointing to each path segment of the + * provided `path`. + */ +TemplatePath.getAllDirs = function (path) { + // Trim a trailing slash if there is one + path = path.replace(/\/$/, ""); + + if (!path.includes("/")) { + return [path]; + } + + return path + .split("/") + .map((segment, index, array) => array.slice(0, index + 1).join("/")) + .filter((path) => path !== ".") + .reverse(); +}; + +/** + * Normalizes a path, resolving single-dot and double-dot segments. + * + * Node.js’ [`path.normalize`][1] is called to strip a possible leading `"./"` segment. + * + * [1]: https://nodejs.org/api/path.html#path_path_normalize_path + * + * @param {String} thePath The path that should be normalized. + * @returns {String} the normalized path. + */ +TemplatePath.normalize = function (thePath) { + return normalize(path.normalize(thePath)); +}; + +/** + * Joins all given path segments together. + * + * It uses Node.js’ [`path.join`][1] method and the [normalize-path][2] package. + * + * [1]: https://nodejs.org/api/path.html#path_path_join_paths + * [2]: https://www.npmjs.com/package/normalize-path + * + * @param {String[]} paths An arbitrary amount of path segments. + * @returns {String} the normalized and joined path. + */ +TemplatePath.join = function (...paths) { + return normalize(path.join(...paths)); +}; + +/** + * Joins the given URL path segments and normalizes the resulting path. + * Maintains a single trailing slash if the last URL path argument + * had at least one. + * + * @param {String[]} urlPaths + * @returns {String} a normalized URL path described by the given URL path segments. + */ +TemplatePath.normalizeUrlPath = function (...urlPaths) { + const urlPath = path.posix.join(...urlPaths); + return urlPath.replace(/\/+$/, "/"); +}; + +/** + * Joins the given path segments. Since the first path is absolute, + * the resulting path will be absolute as well. + * + * @param {String[]} paths + * @returns {String} the absolute path described by the given path segments. + */ +TemplatePath.absolutePath = function (...paths) { + let i = 0; + // check all the paths before we short circuit from the first index + for (let p of paths) { + if (path.isAbsolute(p) && i > 0) { + throw new Error( + `Only the first parameter to Template.absolutePath can be an absolute path. Received: ${p} from ${paths}` + ); + } + i++; + } + + let j = 0; + for (let p of paths) { + if (j === 0 && path.isAbsolute(p)) { + return TemplatePath.join(...paths); + } + j++; + } + + return TemplatePath.join(TemplatePath.getWorkingDir(), ...paths); +}; + +/** + * Turns an absolute path into a path relative to the project directory. + * + * @param {String} absolutePath + * @returns {String} the relative path. + */ +TemplatePath.relativePath = function (absolutePath) { + return TemplatePath.stripLeadingSubPath( + absolutePath, + TemplatePath.getWorkingDir() + ); +}; + +/** + * Adds a leading dot-slash segment to each path in the `paths` array. + * + * @param {String[]} paths + * @returns {String[]} + */ +TemplatePath.addLeadingDotSlashArray = function (paths) { + return paths.map((path) => TemplatePath.addLeadingDotSlash(path)); +}; + +/** + * Adds a leading dot-slash segment to `path`. + * + * @param {String} path + * @returns {String} + */ +TemplatePath.addLeadingDotSlash = function (pathArg) { + if (pathArg === "." || pathArg === "..") { + return pathArg + "/"; + } + + if ( + path.isAbsolute(pathArg) || + pathArg.startsWith("./") || + pathArg.startsWith("../") + ) { + return pathArg; + } + + return "./" + pathArg; +}; + +/** + * Removes a leading dot-slash segment. + * + * @param {String} path + * @returns {String} the `path` without a leading dot-slash segment. + */ +TemplatePath.stripLeadingDotSlash = function (path) { + return typeof path === "string" ? path.replace(/^\.\//, "") : path; +}; + +/** + * Determines whether a path starts with a given sub path. + * + * @param {String} path A path + * @param {String} subPath A path + * @returns {Boolean} whether `path` starts with `subPath`. + */ +TemplatePath.startsWithSubPath = function (path, subPath) { + path = TemplatePath.normalize(path); + subPath = TemplatePath.normalize(subPath); + + return path.startsWith(subPath); +}; + +/** + * Removes the `subPath` at the start of `path` if present + * and returns the remainding path. + * + * @param {String} path A path + * @param {String} subPath A path + * @returns {String} the `path` without `subPath` at the start of it. + */ +TemplatePath.stripLeadingSubPath = function (path, subPath) { + path = TemplatePath.normalize(path); + subPath = TemplatePath.normalize(subPath); + + if (subPath !== "." && path.startsWith(subPath)) { + return path.substr(subPath.length + 1); + } + + return path; +}; + +/** + * @param {String} path A path + * @returns {Boolean} whether `path` points to an existing directory. + */ +TemplatePath.isDirectorySync = function (path) { + return fs.existsSync(path) && fs.statSync(path).isDirectory(); +}; + +/** + * @param {String} path A path + * @returns {Boolean} whether `path` points to an existing directory. + */ +TemplatePath.isDirectory = async function (path) { + return new Promise((resolve) => { + fs.stat(path, (err, stats) => { + if (stats) { + resolve(stats.isDirectory()); + } + resolve(false); + }); + }); +}; + +/** + * Appends a recursive wildcard glob pattern to `path` + * unless `path` is not a directory; then, `path` is assumed to be a file path + * and is left unchaged. + * + * @param {String} path + * @returns {String} + */ +TemplatePath.convertToRecursiveGlobSync = function (path) { + if (path === "") { + return "./**"; + } + + path = TemplatePath.addLeadingDotSlash(path); + + if (TemplatePath.isDirectorySync(path)) { + return path + (!path.endsWith("/") ? "/" : "") + "**"; + } + + return path; +}; + +/** + * Appends a recursive wildcard glob pattern to `path` + * unless `path` is not a directory; then, `path` is assumed to be a file path + * and is left unchaged. + * + * @param {String} path + * @returns {String} + */ +TemplatePath.convertToRecursiveGlob = async function (path) { + if (path === "") { + return "./**"; + } + + path = TemplatePath.addLeadingDotSlash(path); + + if (await TemplatePath.isDirectory(path)) { + return path + (!path.endsWith("/") ? "/" : "") + "**"; + } + + return path; +}; + +/** + * Returns the extension of the path without the leading dot. + * If the path has no extensions, the empty string is returned. + * + * @param {String} thePath + * @returns {String} the path’s extension if it exists; + * otherwise, the empty string. + */ +TemplatePath.getExtension = function (thePath) { + return path.extname(thePath).replace(/^\./, ""); +}; + +/** + * Removes the extension from a path. + * + * @param {String} path + * @param {String} extension + * @returns {String} + */ +TemplatePath.removeExtension = function (path, extension = undefined) { + if (extension === undefined) { + return path; + } + + const pathExtension = TemplatePath.getExtension(path); + if (pathExtension !== "" && extension.endsWith(pathExtension)) { + return path.substring(0, path.lastIndexOf(pathExtension) - 1); + } + + return path; +}; + +/** + * Accepts a relative file path that is using a standard directory separator and + * normalizes it using the local operating system separator. + * e.g. `./my/dir/` stays `./my/dir/` on *nix and becomes `.\\my\\dir\\` on Windows + * + * @param {String} filePath + * @returns {String} a file path with the correct local directory separator. + */ +TemplatePath.normalizeOperatingSystemFilePath = function (filePath, sep = "/") { + return filePath.split(sep).join(path.sep); +}; + +/** + * Accepts a relative file path with the local operating system directory separator and + * normalizes it using a forward slash directory separator. (Leaves trailing slash as-is) + * e.g. `./my/dir/` stays `./my/dir/` on *nix and becomes `.\\my\\dir\\` on Windows + * + * @param {String} filePath + * @returns {String} a file path with the correct local directory separator. + */ +TemplatePath.standardizeFilePath = function (filePath, sep = "/") { + return TemplatePath.addLeadingDotSlash(filePath.split(path.sep).join(sep)); +}; + +module.exports = TemplatePath; diff --git a/node_modules/@11ty/eleventy/CODE_OF_CONDUCT.md b/node_modules/@11ty/eleventy/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..318db57 --- /dev/null +++ b/node_modules/@11ty/eleventy/CODE_OF_CONDUCT.md @@ -0,0 +1,48 @@ +# Eleventy Community Code of Conduct + +View the [Code of Conduct](https://www.11ty.dev/docs/code-of-conduct/) on 11ty.dev + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +- The use of sexualized language or imagery and unwelcome sexual attention or advances +- Trolling, insulting/derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or electronic address, without explicit permission +- Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, chat messages, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at eleventy@zachleat.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/node_modules/@11ty/eleventy/LICENSE b/node_modules/@11ty/eleventy/LICENSE new file mode 100644 index 0000000..5027c0d --- /dev/null +++ b/node_modules/@11ty/eleventy/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017–2024 Zach Leatherman @zachleat + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@11ty/eleventy/README.md b/node_modules/@11ty/eleventy/README.md new file mode 100644 index 0000000..4b464b8 --- /dev/null +++ b/node_modules/@11ty/eleventy/README.md @@ -0,0 +1,47 @@ +

eleventy Logo

+ +# eleventy 🕚⚡️🎈🐀 + +A simpler static site generator. An alternative to Jekyll. Written in JavaScript. Transforms a directory of templates (of varying types) into HTML. + +Works with HTML, Markdown, JavaScript, Liquid, Nunjucks, with addons for WebC, Sass, Vue, Svelte, TypeScript, JSX, and many others! + +## ➡ [Documentation](https://www.11ty.dev/docs/) + +- Please star [this repo on GitHub](https://github.com/11ty/eleventy/)! +- Follow us on Mastodon [@eleventy@fosstodon.org](https://fosstodon.org/@eleventy) or Twitter [@eleven_ty](https://twitter.com/eleven_ty) +- Join us on [Discord](https://www.11ty.dev/blog/discord/) +- Support [11ty on Open Collective](https://opencollective.com/11ty) +- [11ty on npm](https://www.npmjs.com/org/11ty) +- [11ty on GitHub](https://github.com/11ty) + +[![npm Version](https://img.shields.io/npm/v/@11ty/eleventy.svg?style=for-the-badge)](https://www.npmjs.com/package/@11ty/eleventy) [![GitHub issues](https://img.shields.io/github/issues/11ty/eleventy.svg?style=for-the-badge)](https://github.com/11ty/eleventy/issues) [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=for-the-badge)](https://github.com/prettier/prettier) [![npm Downloads](https://img.shields.io/npm/dt/@11ty/eleventy.svg?style=for-the-badge)](https://www.npmjs.com/package/@11ty/eleventy) + +## Installation + +``` +npm install @11ty/eleventy --save-dev +``` + +Read our [Getting Started guide](https://www.11ty.dev/docs/getting-started/). + +## Tests + +``` +npm run test +``` + +- We use the [ava JavaScript test runner](https://github.com/avajs/ava) ([Assertions documentation](https://github.com/avajs/ava/blob/master/docs/03-assertions.md)) +- ℹ️ To keep tests fast, thou shalt try to avoid writing files in tests. +- [Continuous Integration on GitHub Actions](https://github.com/11ty/eleventy/actions/workflows/ci.yml) +- [Code Coverage Statistics](https://github.com/11ty/eleventy/blob/master/docs/coverage.md) +- [Benchmark for Performance Regressions](https://github.com/11ty/eleventy-benchmark) + +## Community Roadmap + +- [Top Feature Requests](https://github.com/11ty/eleventy/issues?q=label%3Aneeds-votes+sort%3Areactions-%2B1-desc+label%3Aenhancement) (Add your own votes using the 👍 reaction) +- [Top Bugs 😱](https://github.com/11ty/eleventy/issues?q=is%3Aissue+is%3Aopen+label%3Abug+sort%3Areactions) (Add your own votes using the 👍 reaction) + +## Plugins + +See the [official docs on plugins](https://www.11ty.dev/docs/plugins/). diff --git a/node_modules/@11ty/eleventy/SECURITY.md b/node_modules/@11ty/eleventy/SECURITY.md new file mode 100644 index 0000000..0947081 --- /dev/null +++ b/node_modules/@11ty/eleventy/SECURITY.md @@ -0,0 +1,9 @@ +# Security Policy + +## Reporting a Vulnerability + +Privately report a security issue by navigating to https://github.com/11ty/eleventy/security and using the “Report a vulnerability” button. + +Read more at: https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability + +Alternatively, you may report security issues via an email to `security@11ty.dev`. diff --git a/node_modules/@11ty/eleventy/cmd.cjs b/node_modules/@11ty/eleventy/cmd.cjs new file mode 100755 index 0000000..b51e592 --- /dev/null +++ b/node_modules/@11ty/eleventy/cmd.cjs @@ -0,0 +1,165 @@ +#!/usr/bin/env node + +// This file intentionally uses older code conventions to be as friendly +// as possible with error messaging to folks on older runtimes. + +const pkg = require("./package.json"); +require("please-upgrade-node")(pkg, { + message: function (requiredVersion) { + return ( + "Eleventy " + + pkg.version + + " requires Node " + + requiredVersion + + ". You will need to upgrade Node to use Eleventy!" + ); + }, +}); + +const minimist = require("minimist"); +const debug = require("debug")("Eleventy:cmd"); + +(async function () { + const { EleventyErrorHandler } = await import("./src/Errors/EleventyErrorHandler.js"); + + class SimpleError extends Error { + constructor(...args) { + super(...args); + this.skipOriginalStack = true; + } + } + + try { + const argv = minimist(process.argv.slice(2), { + string: ["input", "output", "formats", "config", "pathprefix", "port", "to", "incremental", "loader"], + boolean: [ + "quiet", + "version", + "watch", + "dryrun", + "help", + "serve", + "ignore-initial", + ], + default: { + quiet: null, + "ignore-initial": false, + "to": "fs", + }, + unknown: function (unknownArgument) { + throw new Error( + `We don’t know what '${unknownArgument}' is. Use --help to see the list of supported commands.`, + ); + }, + }); + + debug("command: eleventy %o", argv); + const { Eleventy } = await import("./src/Eleventy.js"); + + let ErrorHandler = new EleventyErrorHandler(); + + process.on("unhandledRejection", (error, promise) => { + ErrorHandler.fatal(error, "Unhandled rejection in promise"); + }); + process.on("uncaughtException", (error) => { + ErrorHandler.fatal(error, "Uncaught exception"); + }); + process.on("rejectionHandled", (promise) => { + ErrorHandler.warn(promise, "A promise rejection was handled asynchronously"); + }); + + if (argv.version) { + console.log(Eleventy.getVersion()); + return; + } else if (argv.help) { + console.log(Eleventy.getHelp()); + return; + } + + let elev = new Eleventy(argv.input, argv.output, { + source: "cli", + // --quiet and --quiet=true both resolve to true + quietMode: argv.quiet, + configPath: argv.config, + pathPrefix: argv.pathprefix, + runMode: argv.serve ? "serve" : argv.watch ? "watch" : "build", + dryRun: argv.dryrun, + loader: argv.loader, + }); + + // reuse ErrorHandler instance in Eleventy + ErrorHandler = elev.errorHandler; + + // Before init + elev.setFormats(argv.formats); + + // careful, we can’t use async/await here to error properly + // with old node versions in `please-upgrade-node` above. + elev + .init() + .then(() => { + if (argv.to === "json" || argv.to === "ndjson") { + // override logging output + elev.setIsVerbose(false); + } + + // Only relevant for watch/serve + elev.setIgnoreInitial(argv["ignore-initial"]); + + if(argv.incremental) { + elev.setIncrementalFile(argv.incremental); + } else if(argv.incremental !== undefined) { + elev.setIncrementalBuild(argv.incremental === "" || argv.incremental); + } + + if (argv.serve || argv.watch) { + if(argv.to === "json" || argv.to === "ndjson") { + throw new SimpleError("--to=json and --to=ndjson are not compatible with --serve or --watch."); + } + + elev + .watch() + .then(() => { + if (argv.serve) { + elev.serve(argv.port); + } + }, error => { + // A build error occurred and we aren’t going to --serve + ErrorHandler.once("error", error, "Eleventy Error (Watch CLI)"); + }); + + process.on("SIGINT", async () => { + await elev.stopWatch(); + process.exitCode = 0; + }); + } else { + if (!argv.to || argv.to === "fs") { + elev.write().catch(error => { + ErrorHandler.once("fatal", error, "Eleventy Error (FS CLI)"); + }); + } else if (argv.to === "json") { + elev.toJSON().then(function (result) { + console.log(JSON.stringify(result, null, 2)); + }, error => { + ErrorHandler.once("fatal", error, "Eleventy Error (JSON CLI)"); + }); + } else if (argv.to === "ndjson") { + elev.toNDJSON().then(function (stream) { + stream.pipe(process.stdout); + }, error => { + ErrorHandler.once("fatal", error, "Eleventy Error (JSON CLI)"); + }); + } else { + throw new SimpleError( + `Invalid --to value: ${argv.to}. Supported values: \`fs\` (default), \`json\`, and \`ndjson\`.`, + ); + } + } + }).catch(error => { + ErrorHandler.fatal(error, "Eleventy Error (CLI)"); + }); + } catch (error) { + let ErrorHandler = new EleventyErrorHandler(); + ErrorHandler.fatal(error, "Eleventy Fatal Error (CLI)"); + } +})(); diff --git a/node_modules/@11ty/eleventy/package.json b/node_modules/@11ty/eleventy/package.json new file mode 100644 index 0000000..0dcd732 --- /dev/null +++ b/node_modules/@11ty/eleventy/package.json @@ -0,0 +1,155 @@ +{ + "name": "@11ty/eleventy", + "version": "3.0.0", + "description": "A simpler static site generator.", + "publishConfig": { + "access": "public", + "provenance": true + }, + "type": "module", + "main": "./src/Eleventy.js", + "exports": { + "import": "./src/Eleventy.js", + "require": "./src/EleventyCommonJs.cjs" + }, + "bin": { + "eleventy": "cmd.cjs" + }, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + }, + "keywords": [ + "static-site-generator", + "static-site", + "ssg", + "documentation", + "website", + "jekyll", + "blog", + "templates", + "generator", + "framework", + "eleventy", + "11ty", + "html", + "markdown", + "liquid", + "nunjucks" + ], + "scripts": { + "default": "npm run test", + "test": "npm run test:node && npm run test:ava", + "test:ava": "ava --verbose --timeout 20s", + "test:node": "node --test test_node/tests.js", + "format": "prettier . --write", + "check": "eslint src", + "check-types": "tsc", + "lint-staged": "lint-staged", + "coverage": "npx c8 ava && npx c8 report --reporter=json-summary && cp coverage/coverage-summary.json docs/_data/coverage.json && node cmd.cjs --config=docs/eleventy.coverage.js", + "prepare": "husky" + }, + "author": "Zach Leatherman (https://zachleat.com/)", + "repository": { + "type": "git", + "url": "git://github.com/11ty/eleventy.git" + }, + "bugs": "https://github.com/11ty/eleventy/issues", + "homepage": "https://www.11ty.dev/", + "ava": { + "environmentVariables": {}, + "failFast": true, + "files": [ + "./test/*.js", + "./test/_issues/**/*test.js" + ], + "watchMode": { + "ignoreChanges": [ + "./test/stubs*/**/*", + ".cache" + ] + } + }, + "lint-staged": { + "*.{js,css,md}": [ + "prettier --write" + ] + }, + "devDependencies": { + "@11ty/eleventy-img": "5.0.0-beta.10", + "@11ty/eleventy-plugin-rss": "^2.0.2", + "@11ty/eleventy-plugin-syntaxhighlight": "^5.0.0", + "@eslint/eslintrc": "^3.1.0", + "@eslint/js": "^9.11.1", + "@iarna/toml": "^2.2.5", + "@mdx-js/node-loader": "^3.0.1", + "@types/node": "^22.7.4", + "@vue/server-renderer": "^3.5.10", + "@zachleat/noop": "^1.0.4", + "ava": "^6.1.3", + "c8": "^10.1.2", + "cross-env": "^7.0.3", + "eslint": "^9.11.1", + "eslint-config-prettier": "^9.1.0", + "globals": "^15.10.0", + "husky": "^9.1.6", + "lint-staged": "^15.2.10", + "markdown-it-emoji": "^3.0.0", + "marked": "^14.1.2", + "prettier": "^3.3.3", + "pretty": "^2.0.0", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "rimraf": "^6.0.1", + "sass": "^1.79.4", + "tsx": "^4.19.1", + "typescript": "^5.6.2", + "vue": "^3.5.10", + "zod": "^3.23.8", + "zod-validation-error": "^3.4.0" + }, + "dependencies": { + "@11ty/dependency-tree": "^3.0.1", + "@11ty/dependency-tree-esm": "^1.0.0", + "@11ty/eleventy-dev-server": "^2.0.4", + "@11ty/eleventy-plugin-bundle": "^3.0.0", + "@11ty/eleventy-utils": "^1.0.3", + "@11ty/lodash-custom": "^4.17.21", + "@11ty/posthtml-urls": "^1.0.0", + "@11ty/recursive-copy": "^3.0.0", + "@sindresorhus/slugify": "^2.2.1", + "bcp-47-normalize": "^2.3.0", + "chardet": "^2.0.0", + "chokidar": "^3.6.0", + "cross-spawn": "^7.0.3", + "debug": "^4.3.7", + "dependency-graph": "^1.0.0", + "entities": "^5.0.0", + "fast-glob": "^3.3.2", + "filesize": "^10.1.6", + "graceful-fs": "^4.2.11", + "gray-matter": "^4.0.3", + "is-glob": "^4.0.3", + "iso-639-1": "^3.1.3", + "js-yaml": "^4.1.0", + "kleur": "^4.1.5", + "liquidjs": "^10.17.0", + "luxon": "^3.5.0", + "markdown-it": "^14.1.0", + "micromatch": "^4.0.8", + "minimist": "^1.2.8", + "moo": "^0.5.2", + "node-retrieve-globals": "^6.0.0", + "normalize-path": "^3.0.0", + "nunjucks": "^3.2.4", + "please-upgrade-node": "^3.2.0", + "posthtml": "^0.16.6", + "posthtml-match-helper": "^2.0.2", + "semver": "^7.6.3", + "slugify": "^1.6.6" + } +} diff --git a/node_modules/@11ty/eleventy/src/Benchmark/Benchmark.js b/node_modules/@11ty/eleventy/src/Benchmark/Benchmark.js new file mode 100644 index 0000000..df6dea7 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Benchmark/Benchmark.js @@ -0,0 +1,55 @@ +import { performance } from "node:perf_hooks"; + +class Benchmark { + constructor() { + // TypeScript slop + this.timeSpent = 0; + this.timesCalled = 0; + this.beforeTimers = []; + } + + reset() { + this.timeSpent = 0; + this.timesCalled = 0; + this.beforeTimers = []; + } + + getNewTimestamp() { + if (performance) { + return performance.now(); + } + return new Date().getTime(); + } + + incrementCount() { + this.timesCalled++; + } + + // TODO(slightlyoff): + // disable all of these hrtime requests when not benchmarking + before() { + this.timesCalled++; + this.beforeTimers.push(this.getNewTimestamp()); + } + + after() { + if (!this.beforeTimers.length) { + throw new Error("You called Benchmark after() without a before()."); + } + + let before = this.beforeTimers.pop(); + if (!this.beforeTimers.length) { + this.timeSpent += this.getNewTimestamp() - before; + } + } + + getTimesCalled() { + return this.timesCalled; + } + + getTotal() { + return this.timeSpent; + } +} + +export default Benchmark; diff --git a/node_modules/@11ty/eleventy/src/Benchmark/BenchmarkGroup.js b/node_modules/@11ty/eleventy/src/Benchmark/BenchmarkGroup.js new file mode 100644 index 0000000..ee82f6b --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Benchmark/BenchmarkGroup.js @@ -0,0 +1,135 @@ +import debugUtil from "debug"; + +import ConsoleLogger from "../Util/ConsoleLogger.js"; +import isAsyncFunction from "../Util/IsAsyncFunction.js"; +import Benchmark from "./Benchmark.js"; + +const debugBenchmark = debugUtil("Eleventy:Benchmark"); + +class BenchmarkGroup { + constructor() { + this.benchmarks = {}; + // Warning: aggregate benchmarks automatically default to false via BenchmarkManager->getBenchmarkGroup + this.isVerbose = true; + this.logger = new ConsoleLogger(); + this.minimumThresholdMs = 50; + this.minimumThresholdPercent = 8; + } + + setIsVerbose(isVerbose) { + this.isVerbose = isVerbose; + this.logger.isVerbose = isVerbose; + } + + reset() { + for (var type in this.benchmarks) { + this.benchmarks[type].reset(); + } + } + + // TODO use addAsync everywhere instead + add(type, callback) { + let benchmark = (this.benchmarks[type] = new Benchmark()); + + /** @this {any} */ + let fn = function (...args) { + benchmark.before(); + let ret = callback.call(this, ...args); + benchmark.after(); + return ret; + }; + + Object.defineProperty(fn, "__eleventyInternal", { + value: { + type: isAsyncFunction(callback) ? "async" : "sync", + callback, + }, + }); + + return fn; + } + + // callback must return a promise + // async addAsync(type, callback) { + // let benchmark = (this.benchmarks[type] = new Benchmark()); + + // benchmark.before(); + // // don’t await here. + // let promise = callback.call(this); + // promise.then(function() { + // benchmark.after(); + // }); + // return promise; + // } + + setMinimumThresholdMs(minimumThresholdMs) { + let val = parseInt(minimumThresholdMs, 10); + if (isNaN(val)) { + throw new Error("`setMinimumThresholdMs` expects a number argument."); + } + this.minimumThresholdMs = val; + } + + setMinimumThresholdPercent(minimumThresholdPercent) { + let val = parseInt(minimumThresholdPercent, 10); + if (isNaN(val)) { + throw new Error("`setMinimumThresholdPercent` expects a number argument."); + } + this.minimumThresholdPercent = val; + } + + has(type) { + return !!this.benchmarks[type]; + } + + get(type) { + if (!this.benchmarks[type]) { + this.benchmarks[type] = new Benchmark(); + } + return this.benchmarks[type]; + } + + padNumber(num, length) { + if (("" + num).length >= length) { + return num; + } + + let prefix = new Array(length + 1).join(" "); + return (prefix + num).slice(-1 * length); + } + + finish(label, totalTimeSpent) { + for (var type in this.benchmarks) { + let bench = this.benchmarks[type]; + let isAbsoluteMinimumComparison = this.minimumThresholdMs > 0; + let totalForBenchmark = bench.getTotal(); + let percent = Math.round((totalForBenchmark * 100) / totalTimeSpent); + let callCount = bench.getTimesCalled(); + + let output = { + ms: this.padNumber(totalForBenchmark.toFixed(0), 6), + percent: this.padNumber(percent, 3), + calls: this.padNumber(callCount, 5), + }; + let str = `Benchmark ${output.ms}ms ${output.percent}% ${output.calls}× (${label}) ${type}`; + + if ( + isAbsoluteMinimumComparison && + totalForBenchmark >= this.minimumThresholdMs && + percent > this.minimumThresholdPercent + ) { + this.logger.warn(str); + } + + // Opt out of logging if low count (1× or 2×) or 0ms / 1% + if ( + callCount > 1 || // called more than once + Math.round(totalForBenchmark) > 0 // more than 0.5ms + ) { + debugBenchmark(str); + } + } + } +} + +export default BenchmarkGroup; diff --git a/node_modules/@11ty/eleventy/src/Benchmark/BenchmarkManager.js b/node_modules/@11ty/eleventy/src/Benchmark/BenchmarkManager.js new file mode 100644 index 0000000..d7a8f61 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Benchmark/BenchmarkManager.js @@ -0,0 +1,73 @@ +import { performance } from "node:perf_hooks"; + +import BenchmarkGroup from "./BenchmarkGroup.js"; + +// TODO this should not be a singleton, it belongs in the config or somewhere on the Eleventy instance. + +class BenchmarkManager { + constructor() { + this.benchmarkGroups = {}; + this.isVerbose = true; + this.start = this.getNewTimestamp(); + } + + reset() { + this.start = this.getNewTimestamp(); + + for (var j in this.benchmarkGroups) { + this.benchmarkGroups[j].reset(); + } + } + + getNewTimestamp() { + if (performance) { + return performance.now(); + } + return new Date().getTime(); + } + + setVerboseOutput(isVerbose) { + this.isVerbose = !!isVerbose; + } + + hasBenchmarkGroup(name) { + return name in this.benchmarkGroups; + } + + getBenchmarkGroup(name) { + if (!this.benchmarkGroups[name]) { + this.benchmarkGroups[name] = new BenchmarkGroup(); + + // Special behavior for aggregate benchmarks + // so they don’t console.log every time + if (name === "Aggregate") { + this.benchmarkGroups[name].setIsVerbose(false); + } else { + this.benchmarkGroups[name].setIsVerbose(this.isVerbose); + } + } + + return this.benchmarkGroups[name]; + } + + getAll() { + return this.benchmarkGroups; + } + + get(name) { + if (name) { + return this.getBenchmarkGroup(name); + } + + return this.getAll(); + } + + finish() { + let totalTimeSpentBenchmarking = this.getNewTimestamp() - this.start; + for (var j in this.benchmarkGroups) { + this.benchmarkGroups[j].finish(j, totalTimeSpentBenchmarking); + } + } +} + +export default BenchmarkManager; diff --git a/node_modules/@11ty/eleventy/src/Data/ComputedData.js b/node_modules/@11ty/eleventy/src/Data/ComputedData.js new file mode 100644 index 0000000..480f583 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Data/ComputedData.js @@ -0,0 +1,121 @@ +import lodash from "@11ty/lodash-custom"; +import debugUtil from "debug"; + +import ComputedDataQueue from "./ComputedDataQueue.js"; +import ComputedDataTemplateString from "./ComputedDataTemplateString.js"; +import ComputedDataProxy from "./ComputedDataProxy.js"; + +const { set: lodashSet, get: lodashGet } = lodash; +const debug = debugUtil("Eleventy:ComputedData"); + +class ComputedData { + constructor(config) { + this.computed = {}; + this.symbolParseFunctions = {}; + this.templateStringKeyLookup = {}; + this.computedKeys = new Set(); + this.declaredDependencies = {}; + this.queue = new ComputedDataQueue(); + this.config = config; + } + + add(key, renderFn, declaredDependencies = [], symbolParseFn, templateInstance) { + this.computedKeys.add(key); + this.declaredDependencies[key] = declaredDependencies; + + // bind config filters/JS functions + if (typeof renderFn === "function") { + let fns = {}; + // TODO bug? no access to non-universal config things? + if (this.config) { + fns = this.config.javascriptFunctions; + } + renderFn = renderFn.bind({ + ...fns, + tmpl: templateInstance, + }); + } + + lodashSet(this.computed, key, renderFn); + + if (symbolParseFn) { + lodashSet(this.symbolParseFunctions, key, symbolParseFn); + } + } + + addTemplateString(key, renderFn, declaredDependencies = [], symbolParseFn, templateInstance) { + this.add(key, renderFn, declaredDependencies, symbolParseFn, templateInstance); + this.templateStringKeyLookup[key] = true; + } + + async resolveVarOrder(data) { + let proxyByTemplateString = new ComputedDataTemplateString(this.computedKeys); + let proxyByProxy = new ComputedDataProxy(this.computedKeys); + + for (let key of this.computedKeys) { + let computed = lodashGet(this.computed, key); + + if (typeof computed !== "function") { + // add nodes for non functions (primitives like booleans, etc) + // This will not handle template strings, as they are normalized to functions + this.queue.addNode(key); + } else { + this.queue.uses(key, this.declaredDependencies[key]); + + let symbolParseFn = lodashGet(this.symbolParseFunctions, key); + let varsUsed = []; + if (symbolParseFn) { + // use the parseForSymbols function in the TemplateEngine + varsUsed = symbolParseFn(); + } else if (symbolParseFn !== false) { + // skip resolution is this is false (just use declaredDependencies) + let isTemplateString = !!this.templateStringKeyLookup[key]; + let proxy = isTemplateString ? proxyByTemplateString : proxyByProxy; + varsUsed = await proxy.findVarsUsed(computed, data); + } + + debug("%o accesses %o variables", key, varsUsed); + let filteredVarsUsed = varsUsed.filter((varUsed) => { + return ( + (varUsed !== key && this.computedKeys.has(varUsed)) || + varUsed.startsWith("collections.") + ); + }); + this.queue.uses(key, filteredVarsUsed); + } + } + } + + async _setupDataEntry(data, order) { + debug("Computed data order of execution: %o", order); + for (let key of order) { + let computed = lodashGet(this.computed, key); + + if (typeof computed === "function") { + let ret = await computed(data); + lodashSet(data, key, ret); + } else if (computed !== undefined) { + lodashSet(data, key, computed); + } + } + } + + async setupData(data, orderFilter) { + await this.resolveVarOrder(data); + + await this.processRemainingData(data, orderFilter); + } + + async processRemainingData(data, orderFilter) { + // process all variables + let order = this.queue.getOrder(); + if (orderFilter && typeof orderFilter === "function") { + order = order.filter(orderFilter.bind(this.queue)); + } + + await this._setupDataEntry(data, order); + this.queue.markComputed(order); + } +} + +export default ComputedData; diff --git a/node_modules/@11ty/eleventy/src/Data/ComputedDataProxy.js b/node_modules/@11ty/eleventy/src/Data/ComputedDataProxy.js new file mode 100644 index 0000000..2415355 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Data/ComputedDataProxy.js @@ -0,0 +1,131 @@ +import lodash from "@11ty/lodash-custom"; +import { isPlainObject } from "@11ty/eleventy-utils"; + +const { set: lodashSet, get: lodashGet } = lodash; + +/* Calculates computed data using Proxies */ +class ComputedDataProxy { + constructor(computedKeys) { + if (Array.isArray(computedKeys)) { + this.computedKeys = new Set(computedKeys); + } else { + this.computedKeys = computedKeys; + } + } + + isArrayOrPlainObject(data) { + return Array.isArray(data) || isPlainObject(data); + } + + getProxyData(data, keyRef) { + // WARNING: SIDE EFFECTS + // Set defaults for keys not already set on parent data + + // TODO should make another effort to get rid of this, + // See the ProxyWrap util for more proxy handlers that will likely fix this + let undefinedValue = "__11TY_UNDEFINED__"; + if (this.computedKeys) { + for (let key of this.computedKeys) { + if (lodashGet(data, key, undefinedValue) === undefinedValue) { + lodashSet(data, key, ""); + } + } + } + + let proxyData = this._getProxyData(data, keyRef); + return proxyData; + } + + _getProxyForObject(dataObj, keyRef, parentKey = "") { + return new Proxy( + {}, + { + get: (obj, key) => { + if (typeof key !== "string") { + return obj[key]; + } + + let newKey = `${parentKey ? `${parentKey}.` : ""}${key}`; + + // Issue #1137 + // Special case for Collections, always return an Array for collection keys + // so they it works fine with Array methods like `filter`, `map`, etc + if (newKey === "collections") { + keyRef.add(newKey); + return new Proxy( + {}, + { + get: (target, key) => { + if (typeof key === "string") { + keyRef.add(`collections.${key}`); + return []; + } + return target[key]; + }, + }, + ); + } + + let newData = this._getProxyData(dataObj[key], keyRef, newKey); + if (!this.isArrayOrPlainObject(newData)) { + keyRef.add(newKey); + } + return newData; + }, + }, + ); + } + + _getProxyForArray(dataArr, keyRef, parentKey = "") { + return new Proxy(new Array(dataArr.length), { + get: (obj, key) => { + if (Array.prototype.hasOwnProperty(key)) { + // remove `filter`, `constructor`, `map`, etc + keyRef.add(parentKey); + return obj[key]; + } + + // Hm, this needs to be better + if (key === "then") { + keyRef.add(parentKey); + return; + } + + let newKey = `${parentKey}[${key}]`; + let newData = this._getProxyData(dataArr[key], keyRef, newKey); + if (!this.isArrayOrPlainObject(newData)) { + keyRef.add(newKey); + } + return newData; + }, + }); + } + + _getProxyData(data, keyRef, parentKey = "") { + if (isPlainObject(data)) { + return this._getProxyForObject(data, keyRef, parentKey); + } else if (Array.isArray(data)) { + return this._getProxyForArray(data, keyRef, parentKey); + } + + // everything else! + return data; + } + + async findVarsUsed(fn, data = {}) { + let keyRef = new Set(); + + // careful, logging proxyData will mess with test results! + let proxyData = this.getProxyData(data, keyRef); + + // squelch console logs for this fake proxy data pass 😅 + // let savedLog = console.log; + // console.log = () => {}; + await fn(proxyData); + // console.log = savedLog; + + return Array.from(keyRef); + } +} + +export default ComputedDataProxy; diff --git a/node_modules/@11ty/eleventy/src/Data/ComputedDataQueue.js b/node_modules/@11ty/eleventy/src/Data/ComputedDataQueue.js new file mode 100644 index 0000000..628b911 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Data/ComputedDataQueue.js @@ -0,0 +1,64 @@ +import { DepGraph as DependencyGraph } from "dependency-graph"; + +/* Keeps track of the dependency graph between computed data variables + * Removes keys from the graph when they are computed. + */ +class ComputedDataQueue { + constructor() { + this.graph = new DependencyGraph(); + } + + getOrder() { + return this.graph.overallOrder(); + } + + getOrderFor(name) { + return this.graph.dependenciesOf(name); + } + + getDependsOn(name) { + return this.graph.dependantsOf(name); + } + + isUsesStartsWith(name, prefix) { + if (name.startsWith(prefix)) { + return true; + } + return ( + this.graph.dependenciesOf(name).filter((entry) => { + return entry.startsWith(prefix); + }).length > 0 + ); + } + + addNode(name) { + if (!this.graph.hasNode(name)) { + this.graph.addNode(name); + } + } + + _uses(graph, name, varsUsed = []) { + if (!graph.hasNode(name)) { + graph.addNode(name); + } + + for (let varUsed of varsUsed) { + if (!graph.hasNode(varUsed)) { + graph.addNode(varUsed); + } + graph.addDependency(name, varUsed); + } + } + + uses(name, varsUsed = []) { + this._uses(this.graph, name, varsUsed); + } + + markComputed(varsComputed = []) { + for (let varComputed of varsComputed) { + this.graph.removeNode(varComputed); + } + } +} + +export default ComputedDataQueue; diff --git a/node_modules/@11ty/eleventy/src/Data/ComputedDataTemplateString.js b/node_modules/@11ty/eleventy/src/Data/ComputedDataTemplateString.js new file mode 100644 index 0000000..d5241b2 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Data/ComputedDataTemplateString.js @@ -0,0 +1,70 @@ +import lodash from "@11ty/lodash-custom"; +import debugUtil from "debug"; + +const { set: lodashSet } = lodash; +const debug = debugUtil("Eleventy:ComputedDataTemplateString"); + +/* Calculates computed data in Template Strings. + * Ideally we would use the Proxy approach but it doesn’t work + * in some template languages that visit all available data even if + * it isn’t used in the template (Nunjucks) + */ +class ComputedDataTemplateString { + constructor(computedKeys) { + if (Array.isArray(computedKeys)) { + this.computedKeys = new Set(computedKeys); + } else { + this.computedKeys = computedKeys; + } + + // is this ¯\_(lisp)_/¯ + // must be strings that won’t be escaped by template languages + this.prefix = "(((11ty((("; + this.suffix = ")))11ty)))"; + } + + getProxyData() { + let proxyData = {}; + + // use these special strings as a workaround to check the rendered output + // can’t use proxies here as some template languages trigger proxy for all + // keys in data + for (let key of this.computedKeys) { + // TODO don’t allow to set eleventyComputed.page? other disallowed computed things? + lodashSet(proxyData, key, this.prefix + key + this.suffix); + } + + return proxyData; + } + + findVarsInOutput(output = "") { + let vars = new Set(); + let splits = output.split(this.prefix); + for (let split of splits) { + let varName = split.slice(0, split.indexOf(this.suffix) < 0 ? 0 : split.indexOf(this.suffix)); + if (varName) { + vars.add(varName); + } + } + return Array.from(vars); + } + + async findVarsUsed(fn) { + let proxyData = this.getProxyData(); + let output; + // Mitigation for #1061, errors with filters in the first pass shouldn’t fail the whole thing. + try { + output = await fn(proxyData); + } catch (e) { + debug("Computed Data first pass data resolution error: %o", e); + } + + // page.outputPath on serverless urls returns false. + if (typeof output === "string") { + return this.findVarsInOutput(output); + } + return []; + } +} + +export default ComputedDataTemplateString; diff --git a/node_modules/@11ty/eleventy/src/Data/TemplateData.js b/node_modules/@11ty/eleventy/src/Data/TemplateData.js new file mode 100644 index 0000000..273fbf0 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Data/TemplateData.js @@ -0,0 +1,737 @@ +import path from "node:path"; +import semver from "semver"; + +import lodash from "@11ty/lodash-custom"; +import { Merge, TemplatePath, isPlainObject } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import unique from "../Util/Objects/Unique.js"; +import TemplateGlob from "../TemplateGlob.js"; +import EleventyExtensionMap from "../EleventyExtensionMap.js"; +import EleventyBaseError from "../Errors/EleventyBaseError.js"; +import TemplateDataInitialGlobalData from "./TemplateDataInitialGlobalData.js"; +import { getEleventyPackageJson, getWorkingProjectPackageJson } from "../Util/ImportJsonSync.js"; +import { EleventyImport, EleventyLoadContent } from "../Util/Require.js"; +import { DeepFreeze } from "../Util/Objects/DeepFreeze.js"; + +const { set: lodashSet, get: lodashGet } = lodash; + +const debugWarn = debugUtil("Eleventy:Warnings"); +const debug = debugUtil("Eleventy:TemplateData"); +const debugDev = debugUtil("Dev:Eleventy:TemplateData"); + +class TemplateDataConfigError extends EleventyBaseError {} +class TemplateDataParseError extends EleventyBaseError {} + +class TemplateData { + constructor(eleventyConfig) { + if (!eleventyConfig) { + throw new TemplateDataConfigError("Missing `config`."); + } + this.eleventyConfig = eleventyConfig; + this.config = this.eleventyConfig.getConfig(); + + this.benchmarks = { + data: this.config.benchmarkManager.get("Data"), + aggregate: this.config.benchmarkManager.get("Aggregate"), + }; + + this.rawImports = {}; + this.globalData = null; + this.templateDirectoryData = {}; + this.isEsm = false; + + this.initialGlobalData = new TemplateDataInitialGlobalData(this.eleventyConfig); + } + + get dirs() { + return this.eleventyConfig.directories; + } + + get inputDir() { + return this.dirs.input; + } + + // if this was set but `falsy` we would fallback to inputDir + get dataDir() { + return this.dirs.data; + } + + // This was async in 2.0 and prior but doesn’t need to be any more. + getInputDir() { + return this.dirs.input; + } + + getDataDir() { + return this.dataDir; + } + + get _fsExistsCache() { + // It's common for data files not to exist, so we avoid going to the FS to + // re-check if they do via a quick-and-dirty cache. + return this.eleventyConfig.existsCache; + } + + setFileSystemSearch(fileSystemSearch) { + this.fileSystemSearch = fileSystemSearch; + } + + setProjectUsingEsm(isEsmProject) { + this.isEsm = !!isEsmProject; + } + + get extensionMap() { + if (!this._extensionMap) { + this._extensionMap = new EleventyExtensionMap(this.eleventyConfig); + this._extensionMap.setFormats([]); + } + return this._extensionMap; + } + + set extensionMap(map) { + this._extensionMap = map; + } + + get environmentVariables() { + return this._env; + } + + set environmentVariables(env) { + this._env = env; + } + + /* Used by tests */ + _setConfig(config) { + this.config = config; + } + + getRawImports() { + if (!this.config.keys.package) { + debug( + "Opted-out of package.json assignment for global data with falsy value for `keys.package` configuration.", + ); + return this.rawImports; + } else if (Object.keys(this.rawImports).length > 0) { + return this.rawImports; + } + + try { + let pkgJson = getWorkingProjectPackageJson(); + this.rawImports[this.config.keys.package] = pkgJson; + + if (this.config.freezeReservedData) { + DeepFreeze(this.rawImports); + } + } catch (e) { + debug("Could not find or require package.json import for global data."); + } + + return this.rawImports; + } + + clearData() { + this.globalData = null; + this.configApiGlobalData = null; + this.templateDirectoryData = {}; + } + + _getGlobalDataGlobByExtension(extension) { + return TemplateGlob.normalizePath(this.dataDir, `/**/*.${extension}`); + } + + // This is a backwards compatibility helper with the old `jsDataFileSuffix` configuration API + getDataFileSuffixes() { + // New API + if (Array.isArray(this.config.dataFileSuffixes)) { + return this.config.dataFileSuffixes; + } + + // Backwards compatibility + if (this.config.jsDataFileSuffix) { + let suffixes = []; + suffixes.push(this.config.jsDataFileSuffix); // e.g. filename.11tydata.json + suffixes.push(""); // suffix-less for free with old API, e.g. filename.json + return suffixes; + } + return []; // if both of these entries are set to false, use no files + } + + // This is used exclusively for --watch and --serve chokidar targets + async getTemplateDataFileGlob() { + let suffixes = this.getDataFileSuffixes(); + let globSuffixesWithLeadingDot = new Set(); + globSuffixesWithLeadingDot.add("json"); // covers .11tydata.json too + let globSuffixesWithoutLeadingDot = new Set(); + + // Typically using [ '.11tydata', '' ] suffixes to find data files + for (let suffix of suffixes) { + // TODO the `suffix` truthiness check is purely for backwards compat? + if (suffix && typeof suffix === "string") { + if (suffix.startsWith(".")) { + // .suffix.js + globSuffixesWithLeadingDot.add(`${suffix.slice(1)}.mjs`); + globSuffixesWithLeadingDot.add(`${suffix.slice(1)}.cjs`); + globSuffixesWithLeadingDot.add(`${suffix.slice(1)}.js`); + } else { + // "suffix.js" without leading dot + globSuffixesWithoutLeadingDot.add(`${suffix || ""}.mjs`); + globSuffixesWithoutLeadingDot.add(`${suffix || ""}.cjs`); + globSuffixesWithoutLeadingDot.add(`${suffix || ""}.js`); + } + } + } + + // Configuration Data Extensions e.g. yaml + if (this.hasUserDataExtensions()) { + for (let extension of this.getUserDataExtensions()) { + globSuffixesWithLeadingDot.add(extension); // covers .11tydata.{extension} too + } + } + + let paths = []; + if (globSuffixesWithLeadingDot.size > 0) { + paths.push(`${this.inputDir}**/*.{${Array.from(globSuffixesWithLeadingDot).join(",")}}`); + } + if (globSuffixesWithoutLeadingDot.size > 0) { + paths.push(`${this.inputDir}**/*{${Array.from(globSuffixesWithoutLeadingDot).join(",")}}`); + } + + return TemplatePath.addLeadingDotSlashArray(paths); + } + + // For spidering dependencies + // TODO Can we reuse getTemplateDataFileGlob instead? Maybe just filter off the .json files before scanning for dependencies + getTemplateJavaScriptDataFileGlob() { + let paths = []; + let suffixes = this.getDataFileSuffixes(); + for (let suffix of suffixes) { + if (suffix) { + // TODO this check is purely for backwards compat and I kinda feel like it shouldn’t be here + // paths.push(`${this.inputDir}/**/*${suffix || ""}.cjs`); // Same as above + paths.push(`${this.inputDir}**/*${suffix || ""}.js`); + } + } + + return TemplatePath.addLeadingDotSlashArray(paths); + } + + getGlobalDataGlob() { + let extGlob = this.getGlobalDataExtensionPriorities().join(","); + return [this._getGlobalDataGlobByExtension("{" + extGlob + "}")]; + } + + getWatchPathCache() { + return this.pathCache; + } + + getGlobalDataExtensionPriorities() { + return this.getUserDataExtensions().concat(["json", "mjs", "cjs", "js"]); + } + + static calculateExtensionPriority(path, priorities) { + for (let i = 0; i < priorities.length; i++) { + let ext = priorities[i]; + if (path.endsWith(ext)) { + return i; + } + } + return priorities.length; + } + + async getGlobalDataFiles() { + let priorities = this.getGlobalDataExtensionPriorities(); + + let fsBench = this.benchmarks.aggregate.get("Searching the file system (data)"); + fsBench.before(); + let globs = this.getGlobalDataGlob(); + let paths = await this.fileSystemSearch.search("global-data", globs); + fsBench.after(); + + // sort paths according to extension priorities + // here we use reverse ordering, because paths with bigger index in array will override the first ones + // example [path/file.json, path/file.js] here js will override json + paths = paths.sort((first, second) => { + let p1 = TemplateData.calculateExtensionPriority(first, priorities); + let p2 = TemplateData.calculateExtensionPriority(second, priorities); + if (p1 < p2) { + return -1; + } + if (p1 > p2) { + return 1; + } + return 0; + }); + + this.pathCache = paths; + return paths; + } + + getObjectPathForDataFile(dataFilePath) { + let reducedPath = TemplatePath.stripLeadingSubPath(dataFilePath, this.dataDir); + let parsed = path.parse(reducedPath); + let folders = parsed.dir ? parsed.dir.split("/") : []; + folders.push(parsed.name); + + return folders; + } + + async getAllGlobalData() { + let globalData = {}; + let files = TemplatePath.addLeadingDotSlashArray(await this.getGlobalDataFiles()); + + this.config.events.emit("eleventy.globalDataFiles", files); + + let dataFileConflicts = {}; + + for (let j = 0, k = files.length; j < k; j++) { + let data = await this.getDataValue(files[j]); + let objectPathTarget = this.getObjectPathForDataFile(files[j]); + + // Since we're joining directory paths and an array is not usable as an objectkey since two identical arrays are not double equal, + // we can just join the array by a forbidden character ("/"" is chosen here, since it works on Linux, Mac and Windows). + // If at some point this isn't enough anymore, it would be possible to just use JSON.stringify(objectPathTarget) since that + // is guaranteed to work but is signifivcantly slower. + let objectPathTargetString = objectPathTarget.join(path.sep); + + // if two global files have the same path (but different extensions) + // and conflict, let’s merge them. + if (dataFileConflicts[objectPathTargetString]) { + debugWarn( + `merging global data from ${files[j]} with an already existing global data file (${dataFileConflicts[objectPathTargetString]}). Overriding existing keys.`, + ); + + let oldData = lodashGet(globalData, objectPathTarget); + data = TemplateData.mergeDeep(this.config.dataDeepMerge, oldData, data); + } + + dataFileConflicts[objectPathTargetString] = files[j]; + debug(`Found global data file ${files[j]} and adding as: ${objectPathTarget}`); + lodashSet(globalData, objectPathTarget, data); + } + + return globalData; + } + + async #getInitialGlobalData() { + let globalData = await this.initialGlobalData.getData(); + + if (!("eleventy" in globalData)) { + globalData.eleventy = {}; + } + + // #2293 for meta[name=generator] + const pkg = getEleventyPackageJson(); + globalData.eleventy.version = semver.coerce(pkg.version).toString(); + globalData.eleventy.generator = `Eleventy v${globalData.eleventy.version}`; + + if (this.environmentVariables) { + if (!("env" in globalData.eleventy)) { + globalData.eleventy.env = {}; + } + + Object.assign(globalData.eleventy.env, this.environmentVariables); + } + + if (this.dirs) { + if (!("directories" in globalData.eleventy)) { + globalData.eleventy.directories = {}; + } + + Object.assign(globalData.eleventy.directories, this.dirs.getUserspaceInstance()); + } + + // Reserved + if (this.config.freezeReservedData) { + DeepFreeze(globalData.eleventy); + } + + return globalData; + } + + async getInitialGlobalData() { + if (!this.configApiGlobalData) { + this.configApiGlobalData = this.#getInitialGlobalData(); + } + + return this.configApiGlobalData; + } + + async #getGlobalData() { + let rawImports = this.getRawImports(); + let configApiGlobalData = await this.getInitialGlobalData(); + + let globalJson = await this.getAllGlobalData(); + let mergedGlobalData = Merge(globalJson, configApiGlobalData); + + // OK: Shallow merge when combining rawImports (pkg) with global data files + return Object.assign({}, mergedGlobalData, rawImports); + } + + async getGlobalData() { + if (!this.globalData) { + this.globalData = this.#getGlobalData(); + } + + return this.globalData; + } + + /* Template and Directory data files */ + async combineLocalData(localDataPaths) { + let localData = {}; + if (!Array.isArray(localDataPaths)) { + localDataPaths = [localDataPaths]; + } + + // Filter out files we know don't exist to avoid overhead for checking + const dataPaths = await Promise.all( + localDataPaths.map((path) => { + if (this._fsExistsCache.exists(path)) { + return path; + } + return false; + }), + ); + + localDataPaths = dataPaths.filter((pathOrFalse) => { + return pathOrFalse === false ? false : true; + }); + + this.config.events.emit("eleventy.dataFiles", localDataPaths); + + if (!localDataPaths.length) { + return localData; + } + + let dataSource = {}; + for (let path of localDataPaths) { + let dataForPath = await this.getDataValue(path); + if (!isPlainObject(dataForPath)) { + debug( + "Warning: Template and Directory data files expect an object to be returned, instead `%o` returned `%o`", + path, + dataForPath, + ); + } else { + // clean up data for template/directory data files only. + let cleanedDataForPath = TemplateData.cleanupData(dataForPath); + for (let key in cleanedDataForPath) { + if (Object.prototype.hasOwnProperty.call(dataSource, key)) { + debugWarn( + "Local data files have conflicting data. Overwriting '%s' with data from '%s'. Previous data location was from '%s'", + key, + path, + dataSource[key], + ); + } + dataSource[key] = path; + } + TemplateData.mergeDeep(this.config.dataDeepMerge, localData, cleanedDataForPath); + } + } + return localData; + } + + async getTemplateDirectoryData(templatePath) { + if (!this.templateDirectoryData[templatePath]) { + let localDataPaths = await this.getLocalDataPaths(templatePath); + let importedData = await this.combineLocalData(localDataPaths); + + this.templateDirectoryData[templatePath] = Object.assign({}, importedData); + } + return this.templateDirectoryData[templatePath]; + } + + getUserDataExtensions() { + if (!this.config.dataExtensions) { + return []; + } + + // returning extensions in reverse order to create proper extension order + // later added formats will override first ones + return Array.from(this.config.dataExtensions.keys()).reverse(); + } + + getUserDataParser(extension) { + return this.config.dataExtensions.get(extension); + } + + isUserDataExtension(extension) { + return this.config.dataExtensions && this.config.dataExtensions.has(extension); + } + + hasUserDataExtensions() { + return this.config.dataExtensions && this.config.dataExtensions.size > 0; + } + + async _parseDataFile(path, parser, options = {}) { + let readFile = !("read" in options) || options.read === true; + let rawInput; + + if (readFile) { + rawInput = EleventyLoadContent(path, options); + } + + if (readFile && !rawInput) { + return {}; + } + + try { + if (readFile) { + return parser(rawInput, path); + } else { + // path as a first argument is when `read: false` + // path as a second argument is for consistency with `read: true` API + return parser(path, path); + } + } catch (e) { + throw new TemplateDataParseError(`Having trouble parsing data file ${path}`, e); + } + } + + // ignoreProcessing = false for global data files + // ignoreProcessing = true for local data files + async getDataValue(path) { + let extension = TemplatePath.getExtension(path); + + if (extension === "js" || extension === "cjs" || extension === "mjs") { + // JS data file or require’d JSON (no preprocessing needed) + let localPath = TemplatePath.absolutePath(path); + let exists = this._fsExistsCache.exists(localPath); + // Make sure that relative lookups benefit from cache + this._fsExistsCache.markExists(path, exists); + + if (!exists) { + return {}; + } + + let aggregateDataBench = this.benchmarks.aggregate.get("Data File"); + aggregateDataBench.before(); + let dataBench = this.benchmarks.data.get(`\`${path}\``); + dataBench.before(); + + let type = "cjs"; + if (extension === "mjs" || (extension === "js" && this.isEsm)) { + type = "esm"; + } + + // We always need to use `import()`, as `require` isn’t available in ESM. + let returnValue = await EleventyImport(localPath, type); + + // TODO special exception for Global data `permalink.js` + // module.exports = (data) => `${data.page.filePathStem}/`; // Does not work + // module.exports = () => ((data) => `${data.page.filePathStem}/`); // Works + if (typeof returnValue === "function") { + let configApiGlobalData = await this.getInitialGlobalData(); + returnValue = await returnValue(configApiGlobalData || {}); + } + + dataBench.after(); + aggregateDataBench.after(); + + return returnValue; + } else if (this.isUserDataExtension(extension)) { + // Other extensions + let { parser, options } = this.getUserDataParser(extension); + + return this._parseDataFile(path, parser, options); + } else if (extension === "json") { + // File to string, parse with JSON (preprocess) + const parser = (content) => JSON.parse(content); + return this._parseDataFile(path, parser); + } else { + throw new TemplateDataParseError( + `Could not find an appropriate data parser for ${path}. Do you need to add a plugin to your config file?`, + ); + } + } + + _pushExtensionsToPaths(paths, curpath, extensions) { + for (let extension of extensions) { + paths.push(curpath + "." + extension); + } + } + + _addBaseToPaths(paths, base, extensions, nonEmptySuffixesOnly = false) { + let suffixes = this.getDataFileSuffixes(); + + for (let suffix of suffixes) { + suffix = suffix || ""; + + if (nonEmptySuffixesOnly && suffix === "") { + continue; + } + + // data suffix + if (suffix) { + paths.push(base + suffix + ".js"); + paths.push(base + suffix + ".cjs"); + paths.push(base + suffix + ".mjs"); + } + paths.push(base + suffix + ".json"); // default: .11tydata.json + + // inject user extensions + this._pushExtensionsToPaths(paths, base + suffix, extensions); + } + } + + async getLocalDataPaths(templatePath) { + let paths = []; + let parsed = path.parse(templatePath); + let inputDir = this.inputDir; + + debugDev("getLocalDataPaths(%o)", templatePath); + debugDev("parsed.dir: %o", parsed.dir); + + let userExtensions = this.getUserDataExtensions(); + + if (parsed.dir) { + let fileNameNoExt = this.extensionMap.removeTemplateExtension(parsed.base); + + // default dataSuffix: .11tydata, is appended in _addBaseToPaths + debug("Using %o suffixes to find data files.", this.getDataFileSuffixes()); + + // Template data file paths + let filePathNoExt = parsed.dir + "/" + fileNameNoExt; + this._addBaseToPaths(paths, filePathNoExt, userExtensions); + + // Directory data file paths + let allDirs = TemplatePath.getAllDirs(parsed.dir); + + debugDev("allDirs: %o", allDirs); + for (let dir of allDirs) { + let lastDir = TemplatePath.getLastPathSegment(dir); + let dirPathNoExt = dir + "/" + lastDir; + + if (inputDir) { + debugDev("dirStr: %o; inputDir: %o", dir, inputDir); + } + if (!inputDir || (dir.startsWith(inputDir) && dir !== inputDir)) { + if (this.config.dataFileDirBaseNameOverride) { + let indexDataFile = dir + "/" + this.config.dataFileDirBaseNameOverride; + this._addBaseToPaths(paths, indexDataFile, userExtensions, true); + } else { + this._addBaseToPaths(paths, dirPathNoExt, userExtensions); + } + } + } + + // 0.11.0+ include root input dir files + // if using `docs/` as input dir, looks for docs/docs.json et al + if (inputDir) { + let lastInputDir = TemplatePath.addLeadingDotSlash( + TemplatePath.join(inputDir, TemplatePath.getLastPathSegment(inputDir)), + ); + + // in root input dir, search for index.11tydata.json et al + if (this.config.dataFileDirBaseNameOverride) { + let indexDataFile = + TemplatePath.getDirFromFilePath(lastInputDir) + + "/" + + this.config.dataFileDirBaseNameOverride; + this._addBaseToPaths(paths, indexDataFile, userExtensions, true); + } else if (lastInputDir !== "./") { + this._addBaseToPaths(paths, lastInputDir, userExtensions); + } + } + } + + debug("getLocalDataPaths(%o): %o", templatePath, paths); + return unique(paths).reverse(); + } + + static mergeDeep(deepMerge, target, ...source) { + if (!deepMerge && deepMerge !== undefined) { + return Object.assign(target, ...source); + } else { + return TemplateData.merge(target, ...source); + } + } + + static merge(target, ...source) { + return Merge(target, ...source); + } + + /* Like cleanupData() but does not mutate */ + static getCleanedTagsImmutable(data) { + let tags = []; + + if (isPlainObject(data) && data.tags) { + if (typeof data.tags === "string") { + tags = (data.tags || "").split(","); + } else if (Array.isArray(data.tags)) { + tags = data.tags; + } + + // Deduplicate tags + return [...new Set(tags)]; + } + + return tags; + } + + static cleanupData(data) { + if (isPlainObject(data) && "tags" in data) { + if (typeof data.tags === "string") { + data.tags = data.tags ? [data.tags] : []; + } else if (data.tags === null) { + data.tags = []; + } + + // Deduplicate tags + data.tags = [...new Set(data.tags)]; + } + + return data; + } + + static getNormalizedExcludedCollections(data) { + let excludes = []; + let key = "eleventyExcludeFromCollections"; + + if (data?.[key] !== true) { + if (Array.isArray(data[key])) { + excludes = data[key]; + } else if (typeof data[key] === "string") { + excludes = (data[key] || "").split(","); + } + } + + return { + excludes, + excludeAll: data?.eleventyExcludeFromCollections === true, + }; + } + + /* Same as getIncludedTagNames() but may also include "all" */ + static getIncludedCollectionNames(data) { + let tags = TemplateData.getCleanedTagsImmutable(data); + + if (tags.length > 0) { + let { excludes, excludeAll } = TemplateData.getNormalizedExcludedCollections(data); + if (excludeAll) { + return []; + } else { + return ["all", ...tags].filter((tag) => !excludes.includes(tag)); + } + } else { + return ["all"]; + } + } + + static getIncludedTagNames(data) { + let tags = TemplateData.getCleanedTagsImmutable(data); + + if (tags.length > 0) { + let { excludes, excludeAll } = TemplateData.getNormalizedExcludedCollections(data); + if (excludeAll) { + return []; + } else { + return tags.filter((tag) => !excludes.includes(tag)); + } + } else { + return []; + } + } +} + +export default TemplateData; diff --git a/node_modules/@11ty/eleventy/src/Data/TemplateDataInitialGlobalData.js b/node_modules/@11ty/eleventy/src/Data/TemplateDataInitialGlobalData.js new file mode 100644 index 0000000..7e2a7ee --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Data/TemplateDataInitialGlobalData.js @@ -0,0 +1,40 @@ +import lodash from "@11ty/lodash-custom"; + +import EleventyBaseError from "../Errors/EleventyBaseError.js"; + +const { set: lodashSet } = lodash; + +class TemplateDataConfigError extends EleventyBaseError {} + +class TemplateDataInitialGlobalData { + constructor(templateConfig) { + if (!templateConfig || templateConfig.constructor.name !== "TemplateConfig") { + throw new TemplateDataConfigError("Missing or invalid `templateConfig` (via Render plugin)."); + } + this.templateConfig = templateConfig; + this.config = this.templateConfig.getConfig(); + } + + async getData() { + let globalData = {}; + + // via eleventyConfig.addGlobalData + if (this.config.globalData) { + let keys = Object.keys(this.config.globalData); + for (let key of keys) { + let returnValue = this.config.globalData[key]; + + // This section is problematic when used with eleventyComputed #3389 + if (typeof returnValue === "function") { + returnValue = await returnValue(); + } + + lodashSet(globalData, key, returnValue); + } + } + + return globalData; + } +} + +export default TemplateDataInitialGlobalData; diff --git a/node_modules/@11ty/eleventy/src/Eleventy.js b/node_modules/@11ty/eleventy/src/Eleventy.js new file mode 100644 index 0000000..f918ab7 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Eleventy.js @@ -0,0 +1,1472 @@ +import chalk from "kleur"; +import { performance } from "node:perf_hooks"; +import debugUtil from "debug"; +import { filesize } from "filesize"; + +import { TemplatePath } from "@11ty/eleventy-utils"; +import BundlePlugin from "@11ty/eleventy-plugin-bundle"; + +import TemplateData from "./Data/TemplateData.js"; +import TemplateWriter from "./TemplateWriter.js"; +import EleventyExtensionMap from "./EleventyExtensionMap.js"; +import { EleventyErrorHandler } from "./Errors/EleventyErrorHandler.js"; +import EleventyBaseError from "./Errors/EleventyBaseError.js"; +import EleventyServe from "./EleventyServe.js"; +import EleventyWatch from "./EleventyWatch.js"; +import EleventyWatchTargets from "./EleventyWatchTargets.js"; +import EleventyFiles from "./EleventyFiles.js"; +import ConsoleLogger from "./Util/ConsoleLogger.js"; +import PathPrefixer from "./Util/PathPrefixer.js"; +import TemplateConfig from "./TemplateConfig.js"; +import FileSystemSearch from "./FileSystemSearch.js"; +import ProjectDirectories from "./Util/ProjectDirectories.js"; +import PathNormalizer from "./Util/PathNormalizer.js"; +import { isGlobMatch } from "./Util/GlobMatcher.js"; + +import simplePlural from "./Util/Pluralize.js"; +import checkPassthroughCopyBehavior from "./Util/PassthroughCopyBehaviorCheck.js"; +import eventBus from "./EventBus.js"; +import { getEleventyPackageJson, getWorkingProjectPackageJson } from "./Util/ImportJsonSync.js"; +import { EleventyImport } from "./Util/Require.js"; +import RenderPlugin, * as RenderPluginExtras from "./Plugins/RenderPlugin.js"; +import I18nPlugin, * as I18nPluginExtras from "./Plugins/I18nPlugin.js"; +import HtmlBasePlugin, * as HtmlBasePluginExtras from "./Plugins/HtmlBasePlugin.js"; +import { TransformPlugin as InputPathToUrlTransformPlugin } from "./Plugins/InputPathToUrl.js"; +import { IdAttributePlugin } from "./Plugins/IdAttributePlugin.js"; +import ProjectTemplateFormats from "./Util/ProjectTemplateFormats.js"; +import EventBusUtil from "./Util/EventBusUtil.js"; + +const pkg = getEleventyPackageJson(); +const debug = debugUtil("Eleventy"); + +/** + * Eleventy’s programmatic API + * @module 11ty/eleventy/Eleventy + * + * This line is required for IDE autocomplete in config files + * @typedef {import('./UserConfig.js').default} UserConfig + */ + +class Eleventy { + /** + * Userspace package.json file contents + * @type {object|undefined} + */ + #projectPackageJson; + /** @type {ProjectTemplateFormats|undefined} */ + #templateFormats; + /** @type {ConsoleLogger|undefined} */ + #logger; + /** @type {ProjectDirectories|undefined} */ + #directories; + /** @type {boolean|undefined} */ + #verboseOverride; + /** @type {boolean} */ + #isVerboseMode = true; + /** @type {boolean|undefined} */ + #preInitVerbose; + /** @type {boolean} */ + #hasConfigInitialized = false; + /** @type {boolean} */ + #needsInit = true; + /** @type {Promise|undefined} */ + #initPromise; + /** @type {EleventyErrorHandler|undefined} */ + #errorHandler; + /** @type {Map} */ + #privateCaches = new Map(); + /** @type {boolean} */ + #isStopping = false; + /** @type {boolean|undefined} */ + #isEsm; + + /** + * @typedef {object} EleventyOptions + * @property {'cli'|'script'=} source + * @property {'build'|'serve'|'watch'=} runMode + * @property {boolean=} dryRun + * @property {string=} configPath + * @property {string=} pathPrefix + * @property {boolean=} quietMode + * @property {Function=} config + * @property {string=} inputDir + + * @param {string} [input] - Directory or filename for input/sources files. + * @param {string} [output] - Directory serving as the target for writing the output files. + * @param {EleventyOptions} [options={}] + * @param {TemplateConfig} [eleventyConfig] + */ + constructor(input, output, options = {}, eleventyConfig = null) { + /** + * @type {string|undefined} + * @description Holds the path to the input (might be a file or folder) + */ + this.rawInput = input || undefined; + + /** + * @type {string|undefined} + * @description holds the path to the output directory + */ + this.rawOutput = output || undefined; + + /** + * @type {module:11ty/eleventy/TemplateConfig} + * @description Override the config instance (for centralized config re-use) + */ + this.eleventyConfig = eleventyConfig; + + /** + * @type {EleventyOptions} + * @description Options object passed to the Eleventy constructor + * @default {} + */ + this.options = options; + + /** + * @type {'cli'|'script'} + * @description Called via CLI (`cli`) or Programmatically (`script`) + * @default "script" + */ + this.source = options.source || "script"; + + /** + * @type {string} + * @description One of build, serve, or watch + * @default "build" + */ + this.runMode = options.runMode || "build"; + + /** + * @type {boolean} + * @description Is Eleventy running in dry mode? + * @default false + */ + this.isDryRun = options.dryRun ?? false; + + /** + * @type {boolean} + * @description Is this an incremental build? (only operates on a subset of input files) + * @default false + */ + this.isIncremental = false; + + /** + * @type {string|undefined} + * @description If an incremental build, this is the file we’re operating on. + * @default null + */ + this.programmaticApiIncrementalFile = undefined; + + /** + * @type {boolean} + * @description Should we process files on first run? (The --ignore-initial feature) + * @default true + */ + this.isRunInitialBuild = true; + + /** + * @type {Number} + * @description Number of builds run on this instance. + * @default 0 + */ + this.buildCount = 0; + + /** + * @member {String} - Force ESM or CJS mode instead of detecting from package.json. Either cjs, esm, or auto. + * @default "auto" + */ + this.loader = this.options.loader ?? "auto"; + + /** + * @type {Number} + * @description The timestamp of Eleventy start. + */ + this.start = this.getNewTimestamp(); + } + + /** + * @type {string|undefined} + * @description An override of Eleventy's default config file paths + * @default undefined + */ + get configPath() { + return this.options.configPath; + } + + /** + * @type {string} + * @description The top level directory the site pretends to reside in + * @default "/" + */ + get pathPrefix() { + return this.options.pathPrefix || "/"; + } + + async initializeConfig(initOverrides) { + if (!this.eleventyConfig) { + this.eleventyConfig = new TemplateConfig(null, this.configPath); + } else if (this.configPath) { + await this.eleventyConfig.setProjectConfigPath(this.configPath); + } + + this.eleventyConfig.setRunMode(this.runMode); + this.eleventyConfig.setProjectUsingEsm(this.isEsm); + this.eleventyConfig.setLogger(this.logger); + this.eleventyConfig.setDirectories(this.directories); + this.eleventyConfig.setTemplateFormats(this.templateFormats); + + if (this.pathPrefix || this.pathPrefix === "") { + this.eleventyConfig.setPathPrefix(this.pathPrefix); + } + + // Debug mode should always run quiet (all output goes to debug logger) + if (process.env.DEBUG) { + this.#verboseOverride = false; + } else if (this.options.quietMode === true || this.options.quietMode === false) { + this.#verboseOverride = !this.options.quietMode; + } + + // Moved before config merges: https://github.com/11ty/eleventy/issues/3316 + if (this.#verboseOverride === true || this.#verboseOverride === false) { + this.eleventyConfig.userConfig._setQuietModeOverride(!this.#verboseOverride); + } + + this.eleventyConfig.userConfig.directories = this.directories; + + /* Programmatic API config */ + if (this.options.config && typeof this.options.config === "function") { + debug("Running options.config configuration callback (passed to Eleventy constructor)"); + // TODO use return object here? + await this.options.config(this.eleventyConfig.userConfig); + } + + /** + * @type {object} + * @description Initialize Eleventy environment variables + * @default null + */ + // this.runMode need to be set before this + this.env = this.getEnvironmentVariableValues(); + this.initializeEnvironmentVariables(this.env); + + // Async initialization of configuration + await this.eleventyConfig.init(initOverrides); + + /** + * @type {object} + * @description Initialize Eleventy’s configuration, including the user config file + */ + this.config = this.eleventyConfig.getConfig(); + + /** + * @type {object} + * @description Singleton BenchmarkManager instance + */ + this.bench = this.config.benchmarkManager; + + if (performance) { + debug("Eleventy warm up time: %o (ms)", performance.now()); + } + + /** @type {object} */ + this.eleventyServe = new EleventyServe(); + this.eleventyServe.eleventyConfig = this.eleventyConfig; + + /** @type {object} */ + this.watchManager = new EleventyWatch(); + + /** @type {object} */ + this.watchTargets = new EleventyWatchTargets(this.eleventyConfig); + this.watchTargets.addAndMakeGlob(this.config.additionalWatchTargets); + + /** @type {object} */ + this.fileSystemSearch = new FileSystemSearch(); + + this.#hasConfigInitialized = true; + + this.setIsVerbose(this.#preInitVerbose ?? !this.config.quietMode); + } + + getNewTimestamp() { + if (performance) { + return performance.now(); + } + return new Date().getTime(); + } + + /** @type {ProjectDirectories} */ + get directories() { + if (!this.#directories) { + this.#directories = new ProjectDirectories(); + this.#directories.setInput(this.rawInput, this.options.inputDir); + this.#directories.setOutput(this.rawOutput); + + if (this.source == "cli" && (this.rawInput !== undefined || this.rawOutput !== undefined)) { + this.#directories.freeze(); + } + } + + return this.#directories; + } + + /** @type {string} */ + get input() { + return this.directories.inputFile || this.directories.input || this.config.dir.input; + } + + /** @type {string} */ + get inputFile() { + return this.directories.inputFile; + } + + /** @type {string} */ + get inputDir() { + return this.directories.input; + } + + // Not used internally, removed in 3.0. + setInputDir() { + throw new Error( + "Eleventy->setInputDir was removed in 3.0. Use the inputDir option to the constructor", + ); + } + + /** @type {string} */ + get outputDir() { + return this.directories.output || this.config.dir.output; + } + + /** + * Updates the dry-run mode of Eleventy. + * + * @param {boolean} isDryRun - Shall Eleventy run in dry mode? + */ + setDryRun(isDryRun) { + this.isDryRun = !!isDryRun; + } + + /** + * Sets the incremental build mode. + * + * @param {boolean} isIncremental - Shall Eleventy run in incremental build mode and only write the files that trigger watch updates + */ + setIncrementalBuild(isIncremental) { + this.isIncremental = !!isIncremental; + + if (this.watchManager) { + this.watchManager.incremental = !!isIncremental; + } + if (this.writer) { + this.writer.setIncrementalBuild(this.isIncremental); + } + } + + /** + * Set whether or not to do an initial build + * + * @param {boolean} ignoreInitialBuild - Shall Eleventy ignore the default initial build before watching in watch/serve mode? + * @default true + */ + setIgnoreInitial(ignoreInitialBuild) { + this.isRunInitialBuild = !ignoreInitialBuild; + + if (this.writer) { + this.writer.setRunInitialBuild(this.isRunInitialBuild); + } + } + + /** + * Updates the path prefix used in the config. + * + * @param {string} pathPrefix - The new path prefix. + */ + setPathPrefix(pathPrefix) { + if (pathPrefix || pathPrefix === "") { + this.eleventyConfig.setPathPrefix(pathPrefix); + // TODO reset config + // this.config = this.eleventyConfig.getConfig(); + } + } + + /** + * Restarts Eleventy. + */ + async restart() { + debug("Restarting"); + this.start = this.getNewTimestamp(); + + this.bench.reset(); + this.eleventyFiles.restart(); + this.extensionMap.reset(); + } + + /** + * Logs some statistics after a complete run of Eleventy. + * + * @returns {string} ret - The log message. + */ + logFinished() { + if (!this.writer) { + throw new Error( + "Did you call Eleventy.init to create the TemplateWriter instance? Hint: you probably didn’t.", + ); + } + + let ret = []; + + // files that render (costly) but do not write to disk + // let renderCount = this.writer.getRenderCount(); + let writeCount = this.writer.getWriteCount(); + let skippedCount = this.writer.getSkippedCount(); + let copyCount = this.writer.getCopyCount(); + + let slashRet = []; + + if (copyCount) { + debug("Total passthrough copy aggregate size: %o", filesize(this.writer.getCopySize())); + slashRet.push(`Copied ${chalk.bold(copyCount)}`); + } + + slashRet.push( + `Wrote ${chalk.bold(writeCount)} ${simplePlural(writeCount, "file", "files")}${ + skippedCount ? ` (skipped ${skippedCount})` : "" + }`, + ); + + if (slashRet.length) { + ret.push(slashRet.join(" ")); + } + + let time = (this.getNewTimestamp() - this.start) / 1000; + ret.push( + `in ${chalk.bold(time.toFixed(2))} ${simplePlural(time.toFixed(2), "second", "seconds")}`, + ); + + // More than 1 second total, show estimate of per-template time + if (time >= 1 && writeCount > 0) { + ret.push(`(${((time * 1000) / writeCount).toFixed(1)}ms each, v${pkg.version})`); + } else { + ret.push(`(v${pkg.version})`); + } + + return ret.join(" "); + } + + #cache(key, inst) { + if (!("caches" in inst)) { + throw new Error("To use #cache you need a `caches` getter object"); + } + + // Restore from cache + if (this.#privateCaches.has(key)) { + let c = this.#privateCaches.get(key); + for (let cacheKey in c) { + inst[cacheKey] = c[cacheKey]; + } + } else { + // Set cache + let c = {}; + for (let cacheKey of inst.caches || []) { + c[cacheKey] = inst[cacheKey]; + } + this.#privateCaches.set(key, c); + } + } + + /** + * Starts Eleventy. + */ + async init(options = {}) { + options = Object.assign({ viaConfigReset: false }, options); + + if (!this.#hasConfigInitialized) { + await this.initializeConfig(); + } + + await this.config.events.emit("eleventy.config", this.eleventyConfig); + + if (this.env) { + await this.config.events.emit("eleventy.env", this.env); + } + + let formats = this.templateFormats.getTemplateFormats(); + + this.extensionMap = new EleventyExtensionMap(this.eleventyConfig); + this.extensionMap.setFormats(formats); + await this.config.events.emit("eleventy.extensionmap", this.extensionMap); + + // eleventyServe is always available, even when not in --serve mode + // TODO directorynorm + this.eleventyServe.setOutputDir(this.outputDir); + + // TODO + // this.eleventyServe.setWatcherOptions(this.getChokidarConfig()); + + this.templateData = new TemplateData(this.eleventyConfig); + this.templateData.setProjectUsingEsm(this.isEsm); + this.templateData.extensionMap = this.extensionMap; + if (this.env) { + this.templateData.environmentVariables = this.env; + } + this.templateData.setFileSystemSearch(this.fileSystemSearch); + + this.eleventyFiles = new EleventyFiles(formats, this.eleventyConfig); + this.eleventyFiles.setFileSystemSearch(this.fileSystemSearch); + this.eleventyFiles.setRunMode(this.runMode); + this.eleventyFiles.extensionMap = this.extensionMap; + // This needs to be set before init or it’ll construct a new one + this.eleventyFiles.templateData = this.templateData; + this.eleventyFiles.init(); + + if (checkPassthroughCopyBehavior(this.config, this.runMode)) { + this.eleventyServe.watchPassthroughCopy( + this.eleventyFiles.getGlobWatcherFilesForPassthroughCopy(), + ); + } + + // Note these directories are all project root relative + this.config.events.emit("eleventy.directories", this.directories.getUserspaceInstance()); + + this.writer = new TemplateWriter(formats, this.templateData, this.eleventyConfig); + + if (!options.viaConfigReset) { + // set or restore cache + this.#cache("TemplateWriter", this.writer); + } + + this.writer.logger = this.logger; + this.writer.extensionMap = this.extensionMap; + this.writer.setEleventyFiles(this.eleventyFiles); + + this.writer.setRunInitialBuild(this.isRunInitialBuild); + this.writer.setIncrementalBuild(this.isIncremental); + + let debugStr = `Directories: + Input: + Directory: ${this.directories.input} + File: ${this.directories.inputFile || false} + Glob: ${this.directories.inputGlob || false} + Data: ${this.directories.data} + Includes: ${this.directories.includes} + Layouts: ${this.directories.layouts || false} + Output: ${this.directories.output} +Template Formats: ${formats.join(",")} +Verbose Output: ${this.verboseMode}`; + debug(debugStr); + + this.writer.setVerboseOutput(this.verboseMode); + this.writer.setDryRun(this.isDryRun); + + this.#needsInit = false; + } + + // These are all set as initial global data under eleventy.env.* (see TemplateData->environmentVariables) + getEnvironmentVariableValues() { + let values = { + source: this.source, + runMode: this.runMode, + }; + + let configPath = this.eleventyConfig.getLocalProjectConfigFile(); + if (configPath) { + let absolutePathToConfig = TemplatePath.absolutePath(configPath); + values.config = absolutePathToConfig; + + // TODO(zachleat): if config is not in root (e.g. using --config=) + let root = TemplatePath.getDirFromFilePath(absolutePathToConfig); + values.root = root; + } + + values.source = this.source; + + // Backwards compatibility + Object.defineProperty(values, "isServerless", { + enumerable: false, + value: false, + }); + + return values; + } + + /** + * Set process.ENV variables for use in Eleventy projects + * + * @method + */ + initializeEnvironmentVariables(env) { + // Recognize that global data `eleventy.version` is coerced to remove prerelease tags + // and this is the raw version (3.0.0 versus 3.0.0-alpha.6). + // `eleventy.env.version` does not yet exist (unnecessary) + process.env.ELEVENTY_VERSION = Eleventy.getVersion(); + + process.env.ELEVENTY_ROOT = env.root; + debug("Setting process.env.ELEVENTY_ROOT: %o", env.root); + + process.env.ELEVENTY_SOURCE = env.source; + process.env.ELEVENTY_RUN_MODE = env.runMode; + } + + /** @param {boolean} value */ + set verboseMode(value) { + this.setIsVerbose(value); + } + + /** @type {boolean} */ + get verboseMode() { + return this.#isVerboseMode; + } + + /** @type {ConsoleLogger} */ + get logger() { + if (!this.#logger) { + this.#logger = new ConsoleLogger(); + this.#logger.isVerbose = this.verboseMode; + } + + return this.#logger; + } + + /** @param {ConsoleLogger} logger */ + set logger(logger) { + this.eleventyConfig.setLogger(logger); + this.#logger = logger; + } + + disableLogger() { + this.logger.overrideLogger(false); + } + + /** @type {EleventyErrorHandler} */ + get errorHandler() { + if (!this.#errorHandler) { + this.#errorHandler = new EleventyErrorHandler(); + this.#errorHandler.isVerbose = this.verboseMode; + this.#errorHandler.logger = this.logger; + } + + return this.#errorHandler; + } + + /** + * Updates the verbose mode of Eleventy. + * + * @method + * @param {boolean} isVerbose - Shall Eleventy run in verbose mode? + */ + setIsVerbose(isVerbose) { + if (!this.#hasConfigInitialized) { + this.#preInitVerbose = !!isVerbose; + return; + } + + // always defer to --quiet if override happened + isVerbose = this.#verboseOverride ?? !!isVerbose; + + this.#isVerboseMode = isVerbose; + + if (this.logger) { + this.logger.isVerbose = isVerbose; + } + + this.bench.setVerboseOutput(isVerbose); + + if (this.writer) { + this.writer.setVerboseOutput(isVerbose); + } + + if (this.errorHandler) { + this.errorHandler.isVerbose = isVerbose; + } + + // Set verbose mode in config file + this.eleventyConfig.verbose = isVerbose; + } + + get templateFormats() { + if (!this.#templateFormats) { + let tf = new ProjectTemplateFormats(); + this.#templateFormats = tf; + } + + return this.#templateFormats; + } + + /** + * Updates the template formats of Eleventy. + * + * @method + * @param {string} formats - The new template formats. + */ + setFormats(formats) { + this.templateFormats.setViaCommandLine(formats); + } + + /** + * Updates the run mode of Eleventy. + * + * @method + * @param {string} runMode - One of "build", "watch", or "serve" + */ + setRunMode(runMode) { + this.runMode = runMode; + } + + /** + * Set the file that needs to be rendered/compiled/written for an incremental build. + * This method is also wired up to the CLI --incremental=incrementalFile + * + * @method + * @param {string} incrementalFile - File path (added or modified in a project) + */ + setIncrementalFile(incrementalFile) { + if (incrementalFile) { + // This used to also setIgnoreInitial(true) but was changed in 3.0.0-alpha.14 + this.setIncrementalBuild(true); + + this.programmaticApiIncrementalFile = TemplatePath.addLeadingDotSlash(incrementalFile); + } + } + + unsetIncrementalFile() { + // only applies to initial build, no re-runs (--watch/--serve) + if (this.programmaticApiIncrementalFile) { + // this.setIgnoreInitial(false); + this.programmaticApiIncrementalFile = undefined; + } + + // reset back to false + this.setIgnoreInitial(false); + } + + /** + * Reads the version of Eleventy. + * + * @static + * @returns {string} - The version of Eleventy. + */ + static getVersion() { + return pkg.version; + } + + /** + * @deprecated since 1.0.1, use static Eleventy.getVersion() + */ + getVersion() { + return Eleventy.getVersion(); + } + + /** + * Shows a help message including usage. + * + * @static + * @returns {string} - The help message. + */ + static getHelp() { + return `Usage: eleventy + eleventy --input=. --output=./_site + eleventy --serve + +Arguments: + + --version + + --input=. + Input template files (default: \`.\`) + + --output=_site + Write HTML output to this folder (default: \`_site\`) + + --serve + Run web server on --port (default 8080) and watch them too + + --port + Run the --serve web server on this port (default 8080) + + --watch + Wait for files to change and automatically rewrite (no web server) + + --incremental + Only build the files that have changed. Best with watch/serve. + + --incremental=filename.md + Does not require watch/serve. Run an incremental build targeting a single file. + + --ignore-initial + Start without a build; build when files change. Works best with watch/serve/incremental. + + --formats=liquid,md + Allow only certain template types (default: \`*\`) + + --quiet + Don’t print all written files (off by default) + + --config=filename.js + Override the eleventy config file path (default: \`.eleventy.js\`) + + --pathprefix='/' + Change all url template filters to use this subdirectory. + + --dryrun + Don’t write any files. Useful in DEBUG mode, for example: \`DEBUG=Eleventy* npx @11ty/eleventy --dryrun\` + + --loader + Set to "esm" to force ESM mode, "cjs" to force CommonJS mode, or "auto" (default) to infer it from package.json. + + --to=json + --to=ndjson + Change the output to JSON or NDJSON (default: \`fs\`) + + --help`; + } + + /** + * @deprecated since 1.0.1, use static Eleventy.getHelp() + */ + getHelp() { + return Eleventy.getHelp(); + } + + /** + * Resets the config of Eleventy. + * + * @method + */ + async resetConfig() { + this.env = this.getEnvironmentVariableValues(); + this.initializeEnvironmentVariables(this.env); + + await this.eleventyConfig.reset(); + + this.config = this.eleventyConfig.getConfig(); + this.eleventyServe.eleventyConfig = this.eleventyConfig; + + this.setIsVerbose(!this.config.quietMode); + + EventBusUtil.resetForConfig(); + } + + /** + * @param {string} changedFilePath - File that triggered a re-run (added or modified) + * @param {boolean} [isResetConfig] - are we doing a config reset + */ + async #addFileToWatchQueue(changedFilePath, isResetConfig) { + // Currently this is only for 11ty.js deps but should be extended with usesGraph + let usedByDependants = []; + if (this.watchTargets) { + usedByDependants = this.watchTargets.getDependantsOf( + TemplatePath.addLeadingDotSlash(changedFilePath), + ); + } + + let relevantLayouts = this.eleventyConfig.usesGraph.getLayoutsUsedBy(changedFilePath); + // Note: these are sync events! + // `templateModified` is an alias for resourceModified but all listeners for this are cleared out when the config is reset. + eventBus.emit("eleventy.templateModified", changedFilePath, { + usedByDependants, + relevantLayouts, + }); + eventBus.emit("eleventy.resourceModified", changedFilePath, usedByDependants, { + viaConfigReset: isResetConfig, + relevantLayouts, + }); + + this.watchManager.addToPendingQueue(changedFilePath); + } + + shouldTriggerConfigReset(changedFiles) { + let configFilePaths = new Set(this.eleventyConfig.getLocalProjectConfigFiles()); + let resetConfigGlobs = EleventyWatchTargets.normalizeToGlobs( + Array.from(this.eleventyConfig.userConfig.watchTargetsConfigReset), + ); + for (let filePath of changedFiles) { + if (configFilePaths.has(filePath)) { + return true; + } + if (isGlobMatch(filePath, resetConfigGlobs)) { + return true; + } + } + + for (const configFilePath of configFilePaths) { + // Any dependencies of the config file changed + let configFileDependencies = new Set(this.watchTargets.getDependenciesOf(configFilePath)); + + for (let filePath of changedFiles) { + if (configFileDependencies.has(filePath)) { + return true; + } + } + } + + return false; + } + + // Checks the build queue to see if any configuration related files have changed + #shouldResetConfig(activeQueue = []) { + if (!activeQueue.length) { + return false; + } + + return this.shouldTriggerConfigReset( + activeQueue.map((path) => { + return PathNormalizer.normalizeSeperator(TemplatePath.addLeadingDotSlash(path)); + }), + ); + } + + async #watch(isResetConfig = false) { + if (this.watchManager.isBuildRunning()) { + return; + } + + this.watchManager.setBuildRunning(); + + let queue = this.watchManager.getActiveQueue(); + + await this.config.events.emit("beforeWatch", queue); + await this.config.events.emit("eleventy.beforeWatch", queue); + + // Clear `import` cache for all files that triggered the rebuild (sync event) + this.watchTargets.clearImportCacheFor(queue); + + // reset and reload global configuration + if (isResetConfig) { + // important: run this before config resets otherwise the handlers will disappear. + await this.config.events.emit("eleventy.reset"); + + await this.resetConfig(); + } + + await this.restart(); + await this.init({ viaConfigReset: isResetConfig }); + + try { + let [, /*passthroughCopyResults*/ templateResults] = await this.write(); + + this.watchTargets.reset(); + + await this.#initWatchDependencies(); + + // Add new deps to chokidar + this.watcher.add(this.watchTargets.getNewTargetsSinceLastReset()); + + // Is a CSS input file and is not in the includes folder + // TODO check output path file extension of this template (not input path) + // TODO add additional API for this, maybe a config callback? + let onlyCssChanges = this.watchManager.hasAllQueueFiles((path) => { + return ( + path.endsWith(".css") && + // TODO how to make this work with relative includes? + !TemplatePath.startsWithSubPath(path, this.eleventyFiles.getIncludesDir()) + ); + }); + + let normalizedPathPrefix = PathPrefixer.normalizePathPrefix(this.config.pathPrefix); + await this.eleventyServe.reload({ + files: this.watchManager.getActiveQueue(), + subtype: onlyCssChanges ? "css" : undefined, + build: { + templates: templateResults + .flat() + .filter((entry) => !!entry) + .map((entry) => { + entry.url = PathPrefixer.joinUrlParts(normalizedPathPrefix, entry.url); + return entry; + }), + }, + }); + } catch (error) { + this.eleventyServe.sendError({ + error, + }); + } + + this.watchManager.setBuildFinished(); + + let queueSize = this.watchManager.getPendingQueueSize(); + if (queueSize > 0) { + this.logger.log( + `You saved while Eleventy was running, let’s run again. (${queueSize} change${ + queueSize !== 1 ? "s" : "" + })`, + ); + await this.#watch(); + } else { + this.logger.log("Watching…"); + } + } + + /** + * @returns {module:11ty/eleventy/src/Benchmark/BenchmarkGroup~BenchmarkGroup} + */ + get watcherBench() { + return this.bench.get("Watcher"); + } + + /** + * Set up watchers and benchmarks. + * + * @async + * @method + */ + async initWatch() { + this.watchManager = new EleventyWatch(); + this.watchManager.incremental = this.isIncremental; + + this.watchTargets.add(["./package.json"]); + this.watchTargets.add(this.eleventyFiles.getGlobWatcherFiles()); + this.watchTargets.add(this.eleventyFiles.getIgnoreFiles()); + + // Watch the local project config file + this.watchTargets.add(this.eleventyConfig.getLocalProjectConfigFiles()); + + // Template and Directory Data Files + this.watchTargets.add(await this.eleventyFiles.getGlobWatcherTemplateDataFiles()); + + let benchmark = this.watcherBench.get( + "Watching JavaScript Dependencies (disable with `eleventyConfig.setWatchJavaScriptDependencies(false)`)", + ); + benchmark.before(); + await this.#initWatchDependencies(); + benchmark.after(); + } + + // fetch from project’s package.json + get projectPackageJson() { + if (!this.#projectPackageJson) { + this.#projectPackageJson = getWorkingProjectPackageJson(); + } + return this.#projectPackageJson; + } + + get isEsm() { + if (this.#isEsm !== undefined) { + return this.#isEsm; + } + if (this.loader == "esm") { + this.#isEsm = true; + } else if (this.loader == "cjs") { + this.#isEsm = false; + } else if (this.loader == "auto") { + try { + this.#isEsm = this.projectPackageJson?.type === "module"; + } catch (e) { + debug("Could not find a project package.json for project’s ES Modules check: %O", e); + this.#isEsm = false; + } + } else { + throw new Error("The 'loader' option must be one of 'esm', 'cjs', or 'auto'"); + } + return this.#isEsm; + } + + /** + * Starts watching dependencies. + */ + async #initWatchDependencies() { + if (!this.eleventyConfig.shouldSpiderJavaScriptDependencies()) { + return; + } + + let dataDir = TemplatePath.stripLeadingDotSlash(this.templateData.getDataDir()); + function filterOutGlobalDataFiles(path) { + return !dataDir || !TemplatePath.stripLeadingDotSlash(path).startsWith(dataDir); + } + + // Lazy resolve isEsm only for --watch + this.watchTargets.setProjectUsingEsm(this.isEsm); + + // Template files .11ty.js + let templateFiles = await this.eleventyFiles.getWatchPathCache(); + await this.watchTargets.addDependencies(templateFiles); + + // Config file dependencies + await this.watchTargets.addDependencies( + this.eleventyConfig.getLocalProjectConfigFiles(), + filterOutGlobalDataFiles, + ); + + // Deps from Global Data (that aren’t in the global data directory, everything is watched there) + let globalDataDeps = this.templateData.getWatchPathCache(); + await this.watchTargets.addDependencies(globalDataDeps, filterOutGlobalDataFiles); + + await this.watchTargets.addDependencies( + await this.eleventyFiles.getWatcherTemplateJavaScriptDataFiles(), + ); + } + + /** + * Returns all watched files. + * + * @async + * @method + * @returns {Promise} targets - The watched files. + */ + async getWatchedFiles() { + return this.watchTargets.getTargets(); + } + + getChokidarConfig() { + let ignores = this.eleventyFiles.getGlobWatcherIgnores(); + debug("Ignoring watcher changes to: %o", ignores); + + let configOptions = this.config.chokidarConfig; + + // can’t override these yet + // TODO maybe if array, merge the array? + delete configOptions.ignored; + + return Object.assign( + { + ignored: ignores, + ignoreInitial: true, + awaitWriteFinish: { + stabilityThreshold: 150, + pollInterval: 25, + }, + }, + configOptions, + ); + } + + /** + * Start the watching of files + * + * @async + * @method + */ + async watch() { + this.watcherBench.setMinimumThresholdMs(500); + this.watcherBench.reset(); + + // We use a string module name and try/catch here to hide this from the zisi and esbuild serverless bundlers + let chokidar; + // eslint-disable-next-line no-useless-catch + try { + let moduleName = "chokidar"; + let chokidarImport = await import(moduleName); + chokidar = chokidarImport.default; + } catch (e) { + throw e; + } + + // Note that watching indirectly depends on this for fetching dependencies from JS files + // See: TemplateWriter:pathCache and EleventyWatchTargets + await this.write(); + + let initWatchBench = this.watcherBench.get("Start up --watch"); + initWatchBench.before(); + + await this.initWatch(); + + // TODO improve unwatching if JS dependencies are removed (or files are deleted) + let rawFiles = await this.getWatchedFiles(); + debug("Watching for changes to: %o", rawFiles); + + let watcher = chokidar.watch(rawFiles, this.getChokidarConfig()); + + initWatchBench.after(); + + this.watcherBench.finish("Watch"); + + this.logger.forceLog("Watching…"); + + this.watcher = watcher; + + let watchDelay; + let watchRun = async (path) => { + path = TemplatePath.normalize(path); + try { + let isResetConfig = this.#shouldResetConfig([path]); + this.#addFileToWatchQueue(path, isResetConfig); + + clearTimeout(watchDelay); + + await new Promise((resolve, reject) => { + watchDelay = setTimeout(async () => { + this.#watch(isResetConfig).then(resolve, reject); + }, this.config.watchThrottleWaitTime); + }); + } catch (e) { + if (e instanceof EleventyBaseError) { + this.errorHandler.error(e, "Eleventy watch error"); + this.watchManager.setBuildFinished(); + } else { + this.errorHandler.fatal(e, "Eleventy fatal watch error"); + await this.stopWatch(); + } + } + }; + + watcher.on("change", async (path) => { + // Emulated passthrough copy logs from the server + if (!this.eleventyServe.isEmulatedPassthroughCopyMatch(path)) { + this.logger.forceLog(`File changed: ${path}`); + } + + await watchRun(path); + }); + + watcher.on("add", async (path) => { + // Emulated passthrough copy logs from the server + if (!this.eleventyServe.isEmulatedPassthroughCopyMatch(path)) { + this.logger.forceLog(`File added: ${path}`); + } + + this.fileSystemSearch.add(path); + await watchRun(path); + }); + + watcher.on("unlink", (path) => { + // this.logger.forceLog(`File removed: ${path}`); + this.fileSystemSearch.delete(path); + }); + } + + async stopWatch() { + // Prevent multiple invocations. + if (this.#isStopping) { + return; + } + this.#isStopping = true; + + debug("Cleaning up chokidar and server instances, if they exist."); + await this.eleventyServe.close(); + await this.watcher?.close(); + } + + /** + * Serve Eleventy on this port. + * + * @param {Number} port - The HTTP port to serve Eleventy from. + */ + async serve(port) { + // Port is optional and in this case likely via --port on the command line + // May defer to configuration API options `port` property + return this.eleventyServe.serve(port); + } + + /** + * Writes templates to the file system. + * + * @async + * @method + * @returns {Promise<{Array}>} + */ + async write() { + return this.executeBuild("fs"); + } + + /** + * Renders templates to a JSON object. + * + * @async + * @method + * @returns {Promise<{Array}>} + */ + async toJSON() { + return this.executeBuild("json"); + } + + /** + * Returns a stream of new line delimited (NDJSON) objects + * + * @async + * @method + * @returns {Promise<{ReadableStream}>} + */ + async toNDJSON() { + return this.executeBuild("ndjson"); + } + + /** + * tbd. + * + * @async + * @method + * @returns {Promise<{Array,ReadableStream}>} ret - tbd. + */ + async executeBuild(to = "fs") { + if (this.#needsInit) { + if (!this.#initPromise) { + this.#initPromise = this.init(); + } + await this.#initPromise; + this.#needsInit = false; + } + + if (!this.writer) { + throw new Error( + "Internal error: Eleventy didn’t run init() properly and wasn’t able to create a TemplateWriter.", + ); + } + + let incrementalFile = + this.programmaticApiIncrementalFile || this.watchManager?.getIncrementalFile(); + if (incrementalFile) { + this.writer.setIncrementalFile(incrementalFile); + } + + let returnObj; + let hasError = false; + + try { + let directories = this.directories.getUserspaceInstance(); + let eventsArg = { + directories, + + // v3.0.0-alpha.6, changed to use `directories` instead (this was only used by serverless plugin) + inputDir: directories.input, + + // Deprecated (not normalized) use `directories` instead. + dir: this.config.dir, + + runMode: this.runMode, + outputMode: to, + incremental: this.isIncremental, + }; + + await this.config.events.emit("beforeBuild", eventsArg); + await this.config.events.emit("eleventy.before", eventsArg); + + let promise; + if (to === "fs") { + promise = this.writer.write(); + } else if (to === "json") { + promise = this.writer.getJSON("json"); + } else if (to === "ndjson") { + promise = this.writer.getJSON("ndjson"); + } else { + throw new Error( + `Invalid argument for \`Eleventy->executeBuild(${to})\`, expected "json", "ndjson", or "fs".`, + ); + } + + let resolved = await promise; + + // Passing the processed output to the eleventy.after event (2.0+) + eventsArg.results = resolved.templates; + + if (to === "ndjson") { + // return a stream + // TODO this outputs all ndjson rows after all the templates have been written to the stream + returnObj = this.logger.closeStream(); + } else if (to === "json") { + // Backwards compat + returnObj = resolved.templates; + } else { + // Backwards compat + returnObj = [resolved.passthroughCopy, resolved.templates]; + } + + this.unsetIncrementalFile(); + this.writer.resetIncrementalFile(); + + eventsArg.uses = this.eleventyConfig.usesGraph.map; + await this.config.events.emit("afterBuild", eventsArg); + await this.config.events.emit("eleventy.after", eventsArg); + + this.buildCount++; + } catch (error) { + hasError = true; + + // Issue #2405: Don’t change the exit code for programmatic scripts + let errorSeverity = this.source === "script" ? "error" : "fatal"; + this.errorHandler.once(errorSeverity, error, "Problem writing Eleventy templates"); + + // TODO ndjson should stream the error but https://github.com/11ty/eleventy/issues/3382 + throw error; + } finally { + this.bench.finish(); + + if (to === "fs") { + this.logger.logWithOptions({ + message: this.logFinished(), + color: hasError ? "red" : "green", + force: true, + }); + } + + debug("Finished."); + + debug(` +Have a suggestion/feature request/feedback? Feeling frustrated? I want to hear it! +Open an issue: https://github.com/11ty/eleventy/issues/new`); + } + + return returnObj; + } +} + +export default Eleventy; + +// extend for exporting to CJS +Object.assign(RenderPlugin, RenderPluginExtras); +Object.assign(I18nPlugin, I18nPluginExtras); +Object.assign(HtmlBasePlugin, HtmlBasePluginExtras); + +// Removed plugins + +const EleventyServerlessBundlerPlugin = function () { + throw new Error( + "Following feedback from our Community Survey, low interest in this plugin prompted its removal from Eleventy core in 3.0 as we refocus on static sites. Learn more: https://v3.11ty.dev/docs/plugins/serverless/", + ); +}; + +const EleventyEdgePlugin = function () { + throw new Error( + "Following feedback from our Community Survey, low interest in this plugin prompted its removal from Eleventy core in 3.0 as we refocus on static sites. Learn more: https://v3.11ty.dev/docs/plugins/edge/", + ); +}; + +export { + Eleventy, + EleventyImport as ImportFile, + + // Error messages for removed plugins + EleventyServerlessBundlerPlugin as EleventyServerless, + EleventyServerlessBundlerPlugin, + EleventyEdgePlugin, + + /** + * @type {module:11ty/eleventy/Plugins/RenderPlugin} + */ + RenderPlugin as EleventyRenderPlugin, // legacy name + /** + * @type {module:11ty/eleventy/Plugins/RenderPlugin} + */ + RenderPlugin, + + /** + * @type {module:11ty/eleventy/Plugins/I18nPlugin} + */ + I18nPlugin as EleventyI18nPlugin, // legacy name + /** + * @type {module:11ty/eleventy/Plugins/I18nPlugin} + */ + I18nPlugin, + + /** + * @type {module:11ty/eleventy/Plugins/HtmlBasePlugin} + */ + HtmlBasePlugin as EleventyHtmlBasePlugin, // legacy name + /** + * @type {module:11ty/eleventy/Plugins/HtmlBasePlugin} + */ + HtmlBasePlugin, + + /** + * @type {module:11ty/eleventy/Plugins/InputPathToUrlTransformPlugin} + */ + InputPathToUrlTransformPlugin, + + /** + * @type {module:11ty/eleventy-plugin-bundle} + */ + BundlePlugin, + + /** + * @type {module:11ty/eleventy/Plugins/IdAttributePlugin} + */ + IdAttributePlugin, +}; diff --git a/node_modules/@11ty/eleventy/src/EleventyCommonJs.cjs b/node_modules/@11ty/eleventy/src/EleventyCommonJs.cjs new file mode 100644 index 0000000..14ca89a --- /dev/null +++ b/node_modules/@11ty/eleventy/src/EleventyCommonJs.cjs @@ -0,0 +1,43 @@ +function canRequireModules() { + // via --experimental-require-module or newer than Node 22 support when this flag is no longer necessary + try { + require("./Util/Objects/SampleModule.mjs"); + return true; + } catch(e) { + if(e.code === "ERR_REQUIRE_ESM") { + return false; + } + + // Rethrow if not an ESM require error. + throw e; + } +} + +if(!canRequireModules()) { + let error = new Error(`\`require("@11ty/eleventy")\` is incompatible with Eleventy v3 and this version of Node. You have a few options: + 1. (Easiest) Change the \`require\` to use a dynamic import inside of an asynchronous CommonJS configuration + callback, for example: + + module.exports = async function { + const {EleventyRenderPlugin, EleventyI18nPlugin, EleventyHtmlBasePlugin} = await import("@11ty/eleventy"); + } + + 2. (Easier) Update the JavaScript syntax in your configuration file from CommonJS to ESM (change \`require\` + to use \`import\` and rename the file to have an \`.mjs\` file extension). + + 3. (More work) Change your project to use ESM-first by adding \`"type": "module"\` to your package.json. Any + \`.js\` will need to be ported to use ESM syntax (or renamed to \`.cjs\`.) + + 4. (Short term workaround) Use the --experimental-require-module flag to enable this behavior. Read + more: https://nodejs.org/api/modules.html#loading-ecmascript-modules-using-require It is possible that the + newest version of Node has this enabled by default—you can try upgrading your version of Node.js.`); + + error.skipOriginalStack = true; + + throw error; +} + +// If we made it here require(ESM) works fine (via --experimental-require-module or newer Node.js defaults) +let mod = require("./Eleventy.js"); + +module.exports = mod; diff --git a/node_modules/@11ty/eleventy/src/EleventyExtensionMap.js b/node_modules/@11ty/eleventy/src/EleventyExtensionMap.js new file mode 100644 index 0000000..1662822 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/EleventyExtensionMap.js @@ -0,0 +1,284 @@ +import { TemplatePath } from "@11ty/eleventy-utils"; + +import TemplateEngineManager from "./Engines/TemplateEngineManager.js"; +import EleventyBaseError from "./Errors/EleventyBaseError.js"; + +class EleventyExtensionMapConfigError extends EleventyBaseError {} + +class EleventyExtensionMap { + constructor(config) { + this.config = config; + this._spiderJsDepsCache = {}; + + /** @type {Array} */ + this.validTemplateLanguageKeys; + } + + setFormats(formatKeys = []) { + // raw + this.formatKeys = formatKeys; + + this.unfilteredFormatKeys = formatKeys.map(function (key) { + return key.trim().toLowerCase(); + }); + + this.validTemplateLanguageKeys = this.unfilteredFormatKeys.filter((key) => + this.hasExtension(key), + ); + + this.passthroughCopyKeys = this.unfilteredFormatKeys.filter((key) => !this.hasExtension(key)); + } + + set config(cfg) { + if (!cfg || cfg.constructor.name !== "TemplateConfig") { + throw new EleventyExtensionMapConfigError( + "Missing or invalid `config` argument (via setter).", + ); + } + this.eleventyConfig = cfg; + } + + get config() { + return this.eleventyConfig.getConfig(); + } + + get engineManager() { + if (!this._engineManager) { + this._engineManager = new TemplateEngineManager(this.eleventyConfig); + } + + return this._engineManager; + } + + reset() { + this.engineManager.reset(); + } + + /* Used for layout path resolution */ + getFileList(path, dir) { + if (!path) { + return []; + } + + let files = []; + this.validTemplateLanguageKeys.forEach((key) => { + this.getExtensionsFromKey(key).forEach(function (extension) { + files.push((dir ? dir + "/" : "") + path + "." + extension); + }); + }); + + return files; + } + + // Warning: this would false positive on an include, but is only used + // on paths found from the file system glob search. + // TODO: Method name might just need to be renamed to something more accurate. + isFullTemplateFilePath(path) { + for (let extension of this.validTemplateLanguageKeys) { + if (path.endsWith(`.${extension}`)) { + return true; + } + } + return false; + } + + getCustomExtensionEntry(extension) { + if (!this.config.extensionMap) { + return; + } + + for (let entry of this.config.extensionMap) { + if (entry.extension === extension) { + return entry; + } + } + } + + getValidExtensionsForPath(path) { + let extensions = new Set(); + for (let extension in this.extensionToKeyMap) { + if (path.endsWith(`.${extension}`)) { + extensions.add(extension); + } + } + + // if multiple extensions are valid, sort from longest to shortest + // e.g. .11ty.js and .js + let sorted = Array.from(extensions) + .filter((extension) => this.validTemplateLanguageKeys.includes(extension)) + .sort((a, b) => b.length - a.length); + + return sorted; + } + + async shouldSpiderJavaScriptDependencies(path) { + let extensions = this.getValidExtensionsForPath(path); + for (let extension of extensions) { + if (extension in this._spiderJsDepsCache) { + return this._spiderJsDepsCache[extension]; + } + + let cls = await this.engineManager.getEngineClassByExtension(extension); + if (cls) { + let entry = this.getCustomExtensionEntry(extension); + let shouldSpider = cls.shouldSpiderJavaScriptDependencies(entry); + this._spiderJsDepsCache[extension] = shouldSpider; + return shouldSpider; + } + } + + return false; + } + + getPassthroughCopyGlobs(inputDir) { + return this._getGlobs(this.passthroughCopyKeys, inputDir); + } + + getValidGlobs(inputDir) { + return this._getGlobs(this.validTemplateLanguageKeys, inputDir); + } + + getGlobs(inputDir) { + return this._getGlobs(this.unfilteredFormatKeys, inputDir); + } + + _getGlobs(formatKeys, inputDir) { + let dir = TemplatePath.convertToRecursiveGlobSync(inputDir); + let extensions = new Set(); + + for (let key of formatKeys) { + if (this.hasExtension(key)) { + for (let extension of this.getExtensionsFromKey(key)) { + extensions.add(extension); + } + } else { + extensions.add(key); + } + } + + if (extensions.size === 1) { + return [`${dir}/*.${Array.from(extensions)[0]}`]; + } else if (extensions.size > 1) { + return [ + // extra curly brackets /*.{cjs,txt} + `${dir}/*.{${Array.from(extensions).join(",")}}`, + ]; + } + + return []; + } + + hasExtension(key) { + for (let extension in this.extensionToKeyMap) { + if ( + this.extensionToKeyMap[extension].key === key || + this.extensionToKeyMap[extension].aliasKey === key + ) { + return true; + } + } + + return false; + } + + getExtensionsFromKey(key) { + let extensions = new Set(); + for (let extension in this.extensionToKeyMap) { + if (this.extensionToKeyMap[extension].aliasKey) { + // only add aliased extension if explicitly referenced in formats + // overrides will not have an aliasKey (md => md) + if (this.extensionToKeyMap[extension].aliasKey === key) { + extensions.add(extension); + } + } else if (this.extensionToKeyMap[extension].key === key) { + extensions.add(extension); + } + } + + return Array.from(extensions); + } + + // Only `addExtension` configuration API extensions + getExtensionEntriesFromKey(key) { + let entries = new Set(); + if ("extensionMap" in this.config) { + for (let entry of this.config.extensionMap) { + if (entry.key === key) { + entries.add(entry); + } + } + } + return Array.from(entries); + } + + // Determines whether a path is a passthrough copy file or a template (via TemplateWriter) + hasEngine(pathOrKey) { + return !!this.getKey(pathOrKey); + } + + getKey(pathOrKey) { + pathOrKey = (pathOrKey || "").toLowerCase(); + for (let extension in this.extensionToKeyMap) { + if (pathOrKey === extension || pathOrKey.endsWith("." + extension)) { + let key = + this.extensionToKeyMap[extension].aliasKey || this.extensionToKeyMap[extension].key; + // must be a valid format key passed (e.g. via --formats) + if (this.validTemplateLanguageKeys.includes(key)) { + return key; + } + } + } + } + + getExtensionEntry(pathOrKey) { + pathOrKey = (pathOrKey || "").toLowerCase(); + for (let extension in this.extensionToKeyMap) { + if (pathOrKey === extension || pathOrKey.endsWith("." + extension)) { + return this.extensionToKeyMap[extension]; + } + } + } + + removeTemplateExtension(path) { + for (let extension in this.extensionToKeyMap) { + if (path === extension || path.endsWith("." + extension)) { + return path.slice( + 0, + path.length - 1 - extension.length < 0 ? 0 : path.length - 1 - extension.length, + ); + } + } + return path; + } + + // keys are file extensions + // values are template language keys + get extensionToKeyMap() { + if (!this._extensionToKeyMap) { + this._extensionToKeyMap = { + md: { key: "md", extension: "md" }, + html: { key: "html", extension: "html" }, + njk: { key: "njk", extension: "njk" }, + liquid: { key: "liquid", extension: "liquid" }, + "11ty.js": { key: "11ty.js", extension: "11ty.js" }, + "11ty.cjs": { key: "11ty.js", extension: "11ty.cjs" }, + "11ty.mjs": { key: "11ty.js", extension: "11ty.mjs" }, + }; + + if ("extensionMap" in this.config) { + for (let entry of this.config.extensionMap) { + // extension and key are only different when aliasing. + this._extensionToKeyMap[entry.extension] = entry; + } + } + } + + return this._extensionToKeyMap; + } + + getReadableFileExtensions() { + return Object.keys(this.extensionToKeyMap).join(" "); + } +} + +export default EleventyExtensionMap; diff --git a/node_modules/@11ty/eleventy/src/EleventyFiles.js b/node_modules/@11ty/eleventy/src/EleventyFiles.js new file mode 100644 index 0000000..f7745b7 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/EleventyFiles.js @@ -0,0 +1,517 @@ +import fs from "node:fs"; + +import { TemplatePath, isPlainObject } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import EleventyExtensionMap from "./EleventyExtensionMap.js"; +import TemplateData from "./Data/TemplateData.js"; +import TemplateGlob from "./TemplateGlob.js"; +import TemplatePassthroughManager from "./TemplatePassthroughManager.js"; +import EleventyBaseError from "./Errors/EleventyBaseError.js"; +import checkPassthroughCopyBehavior from "./Util/PassthroughCopyBehaviorCheck.js"; + +const debug = debugUtil("Eleventy:EleventyFiles"); + +class EleventyFilesError extends EleventyBaseError {} + +class EleventyFiles { + constructor(formats, eleventyConfig) { + if (!eleventyConfig) { + throw new EleventyFilesError("Missing `eleventyConfig`` argument."); + } + + this.eleventyConfig = eleventyConfig; + this.config = eleventyConfig.getConfig(); + this.aggregateBench = this.config.benchmarkManager.get("Aggregate"); + + this.formats = formats; + this.eleventyIgnoreContent = false; + } + + get dirs() { + return this.eleventyConfig.directories; + } + + get inputDir() { + return this.dirs.input; + } + + get outputDir() { + return this.dirs.output; + } + + get includesDir() { + return this.dirs.includes; + } + + get layoutsDir() { + return this.dirs.layouts; + } + + get dataDir() { + return this.dirs.data; + } + + // Backwards compat + getDataDir() { + return this.dataDir; + } + + setFileSystemSearch(fileSystemSearch) { + this.fileSystemSearch = fileSystemSearch; + } + + init() { + if (this.dirs.inputFile || this.dirs.inputGlob) { + this.templateGlobs = TemplateGlob.map([this.dirs.inputFile || this.dirs.inputGlob]); + } else { + // Input is a directory + this.templateGlobs = this.extensionMap.getGlobs(this.inputDir); + } + + this.initPassthroughManager(); + this.setupGlobs(); + } + + get validTemplateGlobs() { + if (!this._validTemplateGlobs) { + let globs; + // Input is a file + if (this.inputFile) { + globs = this.templateGlobs; + } else { + // input is a directory + globs = this.extensionMap.getValidGlobs(this.inputDir); + } + this._validTemplateGlobs = globs; + } + return this._validTemplateGlobs; + } + + get passthroughGlobs() { + let paths = new Set(); + // stuff added in addPassthroughCopy() + for (let path of this.passthroughManager.getConfigPathGlobs()) { + paths.add(path); + } + // non-template language extensions + for (let path of this.extensionMap.getPassthroughCopyGlobs(this.inputDir)) { + paths.add(path); + } + return Array.from(paths); + } + + restart() { + this.passthroughManager.reset(); + this.setupGlobs(); + this._glob = null; + } + + /* For testing */ + _setConfig(config) { + if (!config.ignores) { + config.ignores = new Set(); + config.ignores.add("**/node_modules/**"); + } + + this.config = config; + } + + /* Set command root for local project paths */ + // This is only used by tests + _setLocalPathRoot(dir) { + this.localPathRoot = dir; + } + + set extensionMap(extensionMap) { + this._extensionMap = extensionMap; + } + + get extensionMap() { + // for tests + if (!this._extensionMap) { + this._extensionMap = new EleventyExtensionMap(this.eleventyConfig); + this._extensionMap.setFormats(this.formats); + this._extensionMap.config = this.eleventyConfig; + } + return this._extensionMap; + } + + setRunMode(runMode) { + this.runMode = runMode; + } + + initPassthroughManager() { + let mgr = new TemplatePassthroughManager(this.eleventyConfig); + mgr.setRunMode(this.runMode); + mgr.extensionMap = this.extensionMap; + mgr.setFileSystemSearch(this.fileSystemSearch); + this.passthroughManager = mgr; + } + + getPassthroughManager() { + return this.passthroughManager; + } + + setPassthroughManager(mgr) { + mgr.extensionMap = this.extensionMap; + this.passthroughManager = mgr; + } + + set templateData(templateData) { + this._templateData = templateData; + } + + get templateData() { + if (!this._templateData) { + this._templateData = new TemplateData(this.eleventyConfig); + } + + return this._templateData; + } + + setupGlobs() { + this.fileIgnores = this.getIgnores(); + this.extraIgnores = this._getIncludesAndDataDirs(); + this.uniqueIgnores = this.getIgnoreGlobs(); + + // Conditional added for tests that don’t have a config + if (this.config?.events) { + this.config.events.emit("eleventy.ignores", this.uniqueIgnores); + } + + this.normalizedTemplateGlobs = this.templateGlobs; + } + + getIgnoreGlobs() { + let uniqueIgnores = new Set(); + for (let ignore of this.fileIgnores) { + uniqueIgnores.add(ignore); + } + for (let ignore of this.extraIgnores) { + uniqueIgnores.add(ignore); + } + // Placing the config ignores last here is important to the tests + for (let ignore of this.config.ignores) { + uniqueIgnores.add(TemplateGlob.normalizePath(this.localPathRoot || ".", ignore)); + } + return Array.from(uniqueIgnores); + } + + static getFileIgnores(ignoreFiles) { + if (!Array.isArray(ignoreFiles)) { + ignoreFiles = [ignoreFiles]; + } + + let ignores = []; + for (let ignorePath of ignoreFiles) { + ignorePath = TemplatePath.normalize(ignorePath); + + let dir = TemplatePath.getDirFromFilePath(ignorePath); + + if (fs.existsSync(ignorePath) && fs.statSync(ignorePath).size > 0) { + let ignoreContent = fs.readFileSync(ignorePath, "utf8"); + + ignores = ignores.concat(EleventyFiles.normalizeIgnoreContent(dir, ignoreContent)); + } + } + + ignores.forEach((path) => debug(`${ignoreFiles} ignoring: ${path}`)); + + return ignores; + } + + static normalizeIgnoreContent(dir, ignoreContent) { + let ignores = []; + + if (ignoreContent) { + ignores = ignoreContent + .split("\n") + .map((line) => { + return line.trim(); + }) + .filter((line) => { + if (line.charAt(0) === "!") { + debug( + ">>> When processing .gitignore/.eleventyignore, Eleventy does not currently support negative patterns but encountered one:", + ); + debug(">>>", line); + debug("Follow along at https://github.com/11ty/eleventy/issues/693 to track support."); + } + + // empty lines or comments get filtered out + return line.length > 0 && line.charAt(0) !== "#" && line.charAt(0) !== "!"; + }) + .map((line) => { + let path = TemplateGlob.normalizePath(dir, "/", line); + path = TemplatePath.addLeadingDotSlash(TemplatePath.relativePath(path)); + + try { + // Note these folders must exist to get /** suffix + let stat = fs.statSync(path); + if (stat.isDirectory()) { + return path + "/**"; + } + return path; + } catch (e) { + return path; + } + }); + } + + return ignores; + } + + setEleventyIgnoreContent(content) { + this.eleventyIgnoreContent = content; + } + + getIgnores() { + let files = new Set(); + + for (let ignore of EleventyFiles.getFileIgnores(this.getIgnoreFiles())) { + files.add(ignore); + } + + // testing API + if (this.eleventyIgnoreContent !== false) { + files.add(this.eleventyIgnoreContent); + } + + // ignore output dir (unless this excludes all input) + // input: . and output: . (skip) + // input: ./content and output . (skip) + // input: . and output: ./_site (add) + if (!this.inputDir.startsWith(this.outputDir)) { + // both are already normalized in 3.0 + files.add(TemplateGlob.map(this.outputDir + "/**")); + } + + return Array.from(files); + } + + getIgnoreFiles() { + let ignoreFiles = new Set(); + let rootDirectory = this.localPathRoot || "."; + + if (this.config.useGitIgnore) { + ignoreFiles.add(TemplatePath.join(rootDirectory, ".gitignore")); + } + + if (this.eleventyIgnoreContent === false) { + let absoluteInputDir = TemplatePath.absolutePath(this.inputDir); + ignoreFiles.add(TemplatePath.join(rootDirectory, ".eleventyignore")); + if (rootDirectory !== absoluteInputDir) { + ignoreFiles.add(TemplatePath.join(this.inputDir, ".eleventyignore")); + } + } + + return Array.from(ignoreFiles); + } + + /* Backwards compat */ + getIncludesDir() { + return this.includesDir; + } + + /* Backwards compat */ + getLayoutsDir() { + return this.layoutsDir; + } + + getFileGlobs() { + return this.normalizedTemplateGlobs; + } + + getRawFiles() { + return this.templateGlobs; + } + + async getWatchPathCache() { + // Issue #1325: make sure passthrough copy files are not included here + if (!this.pathCache) { + throw new Error("Watching requires `.getFiles()` to be called first in EleventyFiles"); + } + + let ret = []; + // Filter out the passthrough copy paths. + for (let path of this.pathCache) { + if ( + this.extensionMap.isFullTemplateFilePath(path) && + (await this.extensionMap.shouldSpiderJavaScriptDependencies(path)) + ) { + ret.push(path); + } + } + return ret; + } + + _globSearch() { + let globs = this.getFileGlobs(); + + // returns a promise + debug("Searching for: %o", globs); + return this.fileSystemSearch.search("templates", globs, { + ignore: this.uniqueIgnores, + }); + } + + getPathsWithVirtualTemplates(paths) { + // Support for virtual templates added in 3.0 + if (this.config.virtualTemplates && isPlainObject(this.config.virtualTemplates)) { + let virtualTemplates = Object.keys(this.config.virtualTemplates) + .filter((path) => { + // Filter out includes/layouts + return this.dirs.isTemplateFile(path); + }) + .map((path) => { + let fullVirtualPath = this.dirs.getInputPath(path); + if (!this.extensionMap.getKey(fullVirtualPath)) { + this.eleventyConfig.logger.warn( + `The virtual template at ${fullVirtualPath} is using a template format that’s not valid for your project. Your project is using: "${this.formats}". Read more about formats: https://v3.11ty.dev/docs/config/#template-formats`, + ); + } + return fullVirtualPath; + }); + + paths = paths.concat(virtualTemplates); + + // Virtual templates can not live at the same place as files on the file system! + if (paths.length !== new Set(paths).size) { + let conflicts = {}; + for (let path of paths) { + if (conflicts[path]) { + throw new Error( + `A virtual template had the same path as a file on the file system: "${path}"`, + ); + } + + conflicts[path] = true; + } + } + } + + return paths; + } + + async getFiles() { + let bench = this.aggregateBench.get("Searching the file system (templates)"); + bench.before(); + let globResults = await this._globSearch(); + let paths = TemplatePath.addLeadingDotSlashArray(globResults); + bench.after(); + + // Note 2.0.0-canary.19 removed a `filter` option for custom template syntax here that was unpublished and unused. + + paths = this.getPathsWithVirtualTemplates(paths); + + this.pathCache = paths; + return paths; + } + + getFileShape(paths, filePath) { + if (!filePath) { + return; + } + if (this.isPassthroughCopyFile(paths, filePath)) { + return "copy"; + } + if (this.isFullTemplateFile(paths, filePath)) { + return "template"; + } + // include/layout/unknown + } + + isPassthroughCopyFile(paths, filePath) { + return this.passthroughManager.isPassthroughCopyFile(paths, filePath); + } + + // Assumption here that filePath is not a passthrough copy file + isFullTemplateFile(paths, filePath) { + if (!filePath) { + return false; + } + + for (let path of paths) { + if (path === filePath) { + return true; + } + } + + return false; + } + + /* For `eleventy --watch` */ + getGlobWatcherFiles() { + // TODO improvement: tie the includes and data to specific file extensions (currently using `**`) + let directoryGlobs = this._getIncludesAndDataDirs(); + + if (checkPassthroughCopyBehavior(this.config, this.runMode)) { + return this.validTemplateGlobs.concat(directoryGlobs); + } + + // Revert to old passthroughcopy copy files behavior + return this.validTemplateGlobs.concat(this.passthroughGlobs).concat(directoryGlobs); + } + + /* For `eleventy --watch` */ + getGlobWatcherFilesForPassthroughCopy() { + return this.passthroughGlobs; + } + + /* For `eleventy --watch` */ + async getGlobWatcherTemplateDataFiles() { + let templateData = this.templateData; + return await templateData.getTemplateDataFileGlob(); + } + + /* For `eleventy --watch` */ + // TODO this isn’t great but reduces complexity avoiding using TemplateData:getLocalDataPaths for each template in the cache + async getWatcherTemplateJavaScriptDataFiles() { + let globs = this.templateData.getTemplateJavaScriptDataFileGlob(); + let bench = this.aggregateBench.get("Searching the file system (watching)"); + bench.before(); + let results = TemplatePath.addLeadingDotSlashArray( + await this.fileSystemSearch.search("js-dependencies", globs, { + ignore: ["**/node_modules/**"], + }), + ); + bench.after(); + return results; + } + + /* Ignored by `eleventy --watch` */ + getGlobWatcherIgnores() { + // convert to format without ! since they are passed in as a separate argument to glob watcher + let entries = new Set( + this.fileIgnores.map((ignore) => TemplatePath.stripLeadingDotSlash(ignore)), + ); + + for (let ignore of this.config.watchIgnores) { + entries.add(TemplateGlob.normalizePath(this.localPathRoot || ".", ignore)); + } + + // de-duplicated + return Array.from(entries); + } + + _getIncludesAndDataDirs() { + let rawPaths = new Set(); + rawPaths.add(this.includesDir); + if (this.layoutsDir) { + rawPaths.add(this.layoutsDir); + } + rawPaths.add(this.dataDir); + + return Array.from(rawPaths) + .filter((entry) => { + // never ignore the input directory (even if config file returns "" for these) + return entry && entry !== this.inputDir; + }) + .map((entry) => { + return TemplateGlob.map(entry + "**"); + }); + } +} + +export default EleventyFiles; diff --git a/node_modules/@11ty/eleventy/src/EleventyServe.js b/node_modules/@11ty/eleventy/src/EleventyServe.js new file mode 100644 index 0000000..890f4bc --- /dev/null +++ b/node_modules/@11ty/eleventy/src/EleventyServe.js @@ -0,0 +1,305 @@ +import assert from "node:assert"; + +import debugUtil from "debug"; +import { Merge, DeepCopy, TemplatePath } from "@11ty/eleventy-utils"; +import EleventyDevServer from "@11ty/eleventy-dev-server"; + +import EleventyBaseError from "./Errors/EleventyBaseError.js"; +import ConsoleLogger from "./Util/ConsoleLogger.js"; +import PathPrefixer from "./Util/PathPrefixer.js"; +import checkPassthroughCopyBehavior from "./Util/PassthroughCopyBehaviorCheck.js"; +import { getModulePackageJson } from "./Util/ImportJsonSync.js"; +import { EleventyImport } from "./Util/Require.js"; +import { isGlobMatch } from "./Util/GlobMatcher.js"; + +const debug = debugUtil("Eleventy:EleventyServe"); + +class EleventyServeConfigError extends EleventyBaseError {} + +const DEFAULT_SERVER_OPTIONS = { + module: "@11ty/eleventy-dev-server", + port: 8080, + // pathPrefix: "/", + // setup: function() {}, + // logger: { info: function() {}, error: function() {} } +}; + +class EleventyServe { + constructor() { + this.logger = new ConsoleLogger(); + this._initOptionsFetched = false; + this._aliases = undefined; + this._watchedFiles = new Set(); + } + + get config() { + if (!this.eleventyConfig) { + throw new EleventyServeConfigError( + "You need to set the eleventyConfig property on EleventyServe.", + ); + } + + return this.eleventyConfig.getConfig(); + } + + set config(config) { + throw new Error("It’s not allowed to set config on EleventyServe. Set eleventyConfig instead."); + } + + setAliases(aliases) { + this._aliases = aliases; + + if (this._server && "setAliases" in this._server) { + this._server.setAliases(aliases); + } + } + + get eleventyConfig() { + if (!this._eleventyConfig) { + throw new EleventyServeConfigError( + "You need to set the eleventyConfig property on EleventyServe.", + ); + } + + return this._eleventyConfig; + } + + set eleventyConfig(config) { + this._eleventyConfig = config; + if (checkPassthroughCopyBehavior(this._eleventyConfig.userConfig, "serve")) { + this._eleventyConfig.userConfig.events.on("eleventy.passthrough", ({ map }) => { + // for-free passthrough copy + this.setAliases(map); + }); + } + } + + // TODO directorynorm + setOutputDir(outputDir) { + // TODO check if this is different and if so, restart server (if already running) + // This applies if you change the output directory in your config file during watch/serve + this.outputDir = outputDir; + } + + async getServerModule(name) { + try { + if (!name || name === DEFAULT_SERVER_OPTIONS.module) { + return EleventyDevServer; + } + + // Look for peer dep in local project + let projectNodeModulesPath = TemplatePath.absolutePath("./node_modules/"); + let serverPath = TemplatePath.absolutePath(projectNodeModulesPath, name); + // No references outside of the project node_modules are allowed + if (!serverPath.startsWith(projectNodeModulesPath)) { + throw new Error("Invalid node_modules name for Eleventy server instance, received:" + name); + } + + let serverPackageJson = getModulePackageJson(serverPath); + // Normalize with `main` entry from + if (TemplatePath.isDirectorySync(serverPath)) { + if (serverPackageJson.main) { + serverPath = TemplatePath.absolutePath( + projectNodeModulesPath, + name, + serverPackageJson.main, + ); + } else { + throw new Error( + `Eleventy server ${name} is missing a \`main\` entry in its package.json file. Traversed up from ${serverPath}.`, + ); + } + } + + let module = await EleventyImport(serverPath); + + if (!("getServer" in module)) { + throw new Error( + `Eleventy server module requires a \`getServer\` static method. Could not find one on module: \`${name}\``, + ); + } + + if (serverPackageJson["11ty"]?.compatibility) { + try { + this.eleventyConfig.userConfig.versionCheck(serverPackageJson["11ty"].compatibility); + } catch (e) { + this.logger.warn(`Warning: \`${name}\` Plugin Compatibility: ${e.message}`); + } + } + + return module; + } catch (e) { + this.logger.error( + "There was an error with your custom Eleventy server. We’re using the default server instead.\n" + + e.message, + ); + debug("Eleventy server error %o", e); + return EleventyDevServer; + } + } + + get options() { + if (this._options) { + return this._options; + } + + this._options = Object.assign( + { + pathPrefix: PathPrefixer.normalizePathPrefix(this.config.pathPrefix), + logger: this.logger, + }, + DEFAULT_SERVER_OPTIONS, + this.config.serverOptions, + ); + + this._savedConfigOptions = DeepCopy({}, this.config.serverOptions); + + if (!this._initOptionsFetched && this.getSetupCallback()) { + throw new Error( + "Init options have not yet been fetched in the setup callback. This probably means that `init()` has not yet been called.", + ); + } + + return this._options; + } + + get server() { + if (!this._server) { + throw new Error("Missing server instance. Did you call .initServerInstance?"); + } + + return this._server; + } + + async initServerInstance() { + if (this._server) { + return; + } + + let serverModule = await this.getServerModule(this.options.module); + + // Static method `getServer` was already checked in `getServerModule` + this._server = serverModule.getServer("eleventy-server", this.outputDir, this.options); + + this.setAliases(this._aliases); + + if (this._globsNeedWatching) { + this._server.watchFiles(this._watchedFiles); + this._globsNeedWatching = false; + } + } + + getSetupCallback() { + let setupCallback = this.config.serverOptions.setup; + if (setupCallback && typeof setupCallback === "function") { + return setupCallback; + } + } + + async #init() { + let setupCallback = this.getSetupCallback(); + if (setupCallback) { + let opts = await setupCallback(); + this._initOptionsFetched = true; + + if (opts) { + Merge(this.options, opts); + } + } + } + + async init() { + if (!this._initPromise) { + this._initPromise = this.#init(); + } + + return this._initPromise; + } + + // Port comes in here from --port on the command line + async serve(port) { + this._commandLinePort = port; + + await this.init(); + await this.initServerInstance(); + + this.server.serve(port || this.options.port); + } + + async close() { + if (this._server) { + await this._server.close(); + + this._server = undefined; + } + } + + async sendError({ error }) { + if (this._server) { + await this.server.sendError({ + error, + }); + } + } + + // Restart the server entirely + // We don’t want to use a native `restart` method (e.g. restart() in Vite) so that + // we can correctly handle a `module` property change (changing the server type) + async restart() { + // Blow away cached options + delete this._options; + + await this.close(); + + // saved --port in `serve()` + await this.serve(this._commandLinePort); + + // rewatch the saved watched files (passthrough copy) + if ("watchFiles" in this.server) { + this.server.watchFiles(this._watchedFiles); + } + } + + // checkPassthroughCopyBehavior check is called upstream in Eleventy.js + // TODO globs are not removed from watcher + watchPassthroughCopy(globs) { + this._watchedFiles = globs; + + if (this._server && "watchFiles" in this.server) { + this.server.watchFiles(globs); + this._globsNeedWatching = false; + } else { + this._globsNeedWatching = true; + } + } + + isEmulatedPassthroughCopyMatch(filepath) { + return isGlobMatch(filepath, this._watchedFiles); + } + + hasOptionsChanged() { + try { + assert.deepStrictEqual(this.config.serverOptions, this._savedConfigOptions); + return false; + } catch (e) { + return true; + } + } + + // Live reload the server + async reload(reloadEvent = {}) { + if (!this._server) { + return; + } + + // Restart the server if the options have changed + if (this.hasOptionsChanged()) { + debug("Server options changed, we’re restarting the server"); + await this.restart(); + } else { + await this.server.reload(reloadEvent); + } + } +} + +export default EleventyServe; diff --git a/node_modules/@11ty/eleventy/src/EleventyWatch.js b/node_modules/@11ty/eleventy/src/EleventyWatch.js new file mode 100755 index 0000000..22dffbe --- /dev/null +++ b/node_modules/@11ty/eleventy/src/EleventyWatch.js @@ -0,0 +1,131 @@ +import { TemplatePath } from "@11ty/eleventy-utils"; + +import PathNormalizer from "./Util/PathNormalizer.js"; + +/* Decides when to watch and in what mode to watch + * Incremental builds don’t batch changes, they queue. + * Nonincremental builds batch. + */ + +class EleventyWatch { + constructor() { + this.incremental = false; + this.isActive = false; + this.activeQueue = []; + } + + isBuildRunning() { + return this.isActive; + } + + setBuildRunning() { + this.isActive = true; + + // pop waiting queue into the active queue + this.activeQueue = this.popNextActiveQueue(); + } + + setBuildFinished() { + this.isActive = false; + this.activeQueue = []; + } + + getIncrementalFile() { + if (this.incremental) { + return this.activeQueue.length ? this.activeQueue[0] : false; + } + + return false; + } + + /* Returns the changed files currently being operated on in the current `watch` build + * Works with or without incremental (though in incremental only one file per time will be processed) + */ + getActiveQueue() { + if (!this.isActive) { + return []; + } else if (this.incremental && this.activeQueue.length === 0) { + return []; + } else if (this.incremental) { + return [this.activeQueue[0]]; + } + + return this.activeQueue; + } + + _queueMatches(file) { + let filterCallback; + if (typeof file === "function") { + filterCallback = file; + } else { + filterCallback = (path) => path === file; + } + + return this.activeQueue.filter(filterCallback); + } + + hasAllQueueFiles(file) { + return ( + this.activeQueue.length > 0 && this.activeQueue.length === this._queueMatches(file).length + ); + } + + hasQueuedFile(file) { + if (file) { + return this._queueMatches(file).length > 0; + } + return false; + } + + hasQueuedFiles(files) { + for (const file of files) { + if (this.hasQueuedFile(file)) { + return true; + } + } + return false; + } + + get pendingQueue() { + if (!this._queue) { + this._queue = []; + } + return this._queue; + } + + set pendingQueue(value) { + this._queue = value; + } + + addToPendingQueue(path) { + if (path) { + path = PathNormalizer.normalizeSeperator(TemplatePath.addLeadingDotSlash(path)); + this.pendingQueue.push(path); + } + } + + getPendingQueueSize() { + return this.pendingQueue.length; + } + + getPendingQueue() { + return this.pendingQueue; + } + + getActiveQueueSize() { + return this.activeQueue.length; + } + + // returns array + popNextActiveQueue() { + if (this.incremental) { + return this.pendingQueue.length ? [this.pendingQueue.shift()] : []; + } + + let ret = this.pendingQueue.slice(); + this.pendingQueue = []; + return ret; + } +} + +export default EleventyWatch; diff --git a/node_modules/@11ty/eleventy/src/EleventyWatchTargets.js b/node_modules/@11ty/eleventy/src/EleventyWatchTargets.js new file mode 100644 index 0000000..aec2036 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/EleventyWatchTargets.js @@ -0,0 +1,164 @@ +import { TemplatePath } from "@11ty/eleventy-utils"; +import { DepGraph } from "dependency-graph"; + +import JavaScriptDependencies from "./Util/JavaScriptDependencies.js"; +import eventBus from "./EventBus.js"; + +class EleventyWatchTargets { + #templateConfig; + + constructor(templateConfig) { + this.targets = new Set(); + this.dependencies = new Set(); + this.newTargets = new Set(); + this.isEsm = false; + + this.graph = new DepGraph(); + this.#templateConfig = templateConfig; + } + + setProjectUsingEsm(isEsmProject) { + this.isEsm = !!isEsmProject; + } + + isJavaScriptDependency(path) { + return this.dependencies.has(path); + } + + reset() { + this.newTargets = new Set(); + } + + isWatched(target) { + return this.targets.has(target); + } + + addToDependencyGraph(parent, deps) { + if (!this.graph.hasNode(parent)) { + this.graph.addNode(parent); + } + for (let dep of deps) { + if (!this.graph.hasNode(dep)) { + this.graph.addNode(dep); + } + this.graph.addDependency(parent, dep); + } + } + + uses(parent, dep) { + return this.getDependenciesOf(parent).includes(dep); + } + + getDependenciesOf(parent) { + if (!this.graph.hasNode(parent)) { + return []; + } + return this.graph.dependenciesOf(parent); + } + + getDependantsOf(child) { + if (!this.graph.hasNode(child)) { + return []; + } + return this.graph.dependantsOf(child); + } + + addRaw(targets, isDependency) { + for (let target of targets) { + let path = TemplatePath.addLeadingDotSlash(target); + if (!this.isWatched(path)) { + this.newTargets.add(path); + } + + this.targets.add(path); + + if (isDependency) { + this.dependencies.add(path); + } + } + } + + static normalize(targets) { + if (!targets) { + return []; + } else if (Array.isArray(targets)) { + return targets; + } + + return [targets]; + } + + // add only a target + add(targets) { + this.addRaw(EleventyWatchTargets.normalize(targets)); + } + + static normalizeToGlobs(targets) { + return EleventyWatchTargets.normalize(targets).map((entry) => + TemplatePath.convertToRecursiveGlobSync(entry), + ); + } + + addAndMakeGlob(targets) { + this.addRaw(EleventyWatchTargets.normalizeToGlobs(targets)); + } + + // add only a target’s dependencies + async addDependencies(targets, filterCallback) { + if (this.#templateConfig && !this.#templateConfig.shouldSpiderJavaScriptDependencies()) { + return; + } + + targets = EleventyWatchTargets.normalize(targets); + let deps = await JavaScriptDependencies.getDependencies(targets, this.isEsm); + if (filterCallback) { + deps = deps.filter(filterCallback); + } + + for (let target of targets) { + this.addToDependencyGraph(target, deps); + } + this.addRaw(deps, true); + } + + setWriter(templateWriter) { + this.writer = templateWriter; + } + + clearImportCacheFor(filePathArray) { + let paths = new Set(); + for (const filePath of filePathArray) { + paths.add(filePath); + + // Delete from require cache so that updates to the module are re-required + let importsTheChangedFile = this.getDependantsOf(filePath); + for (let dep of importsTheChangedFile) { + paths.add(dep); + } + + let isImportedInTheChangedFile = this.getDependenciesOf(filePath); + for (let dep of isImportedInTheChangedFile) { + paths.add(dep); + } + + // Use GlobalDependencyMap + if (this.#templateConfig) { + for (let dep of this.#templateConfig.usesGraph.getDependantsFor(filePath)) { + paths.add(dep); + } + } + } + + eventBus.emit("eleventy.importCacheReset", paths); + } + + getNewTargetsSinceLastReset() { + return Array.from(this.newTargets); + } + + getTargets() { + return Array.from(this.targets); + } +} + +export default EleventyWatchTargets; diff --git a/node_modules/@11ty/eleventy/src/Engines/Custom.js b/node_modules/@11ty/eleventy/src/Engines/Custom.js new file mode 100644 index 0000000..e5d9be2 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Engines/Custom.js @@ -0,0 +1,338 @@ +import TemplateEngine from "./TemplateEngine.js"; +import getJavaScriptData from "../Util/GetJavaScriptData.js"; +import eventBus from "../EventBus.js"; + +let lastModifiedFile = undefined; +eventBus.on("eleventy.resourceModified", (path) => { + lastModifiedFile = path; +}); + +class CustomEngine extends TemplateEngine { + constructor(name, eleventyConfig) { + super(name, eleventyConfig); + + this.entry = this.getExtensionMapEntry(); + this.needsInit = "init" in this.entry && typeof this.entry.init === "function"; + + this._defaultEngine = undefined; + + // Enable cacheability for this template + if (this.entry?.compileOptions?.cache) { + this.cacheable = this.entry.compileOptions.cache; + } else if (this.needsToReadFileContents()) { + this.cacheable = true; + } + } + + getExtensionMapEntry() { + if ("extensionMap" in this.config) { + let name = this.name.toLowerCase(); + // Iterates over only the user config `addExtension` entries + for (let entry of this.config.extensionMap) { + let entryKey = (entry.aliasKey || entry.key || "").toLowerCase(); + if (entryKey === name) { + return entry; + } + } + } + + throw Error( + `Could not find a custom extension for ${this.name}. Did you add it to your config file?`, + ); + } + + setDefaultEngine(defaultEngine) { + this._defaultEngine = defaultEngine; + } + + async getInstanceFromInputPath(inputPath) { + if ( + "getInstanceFromInputPath" in this.entry && + typeof this.entry.getInstanceFromInputPath === "function" + ) { + // returns Promise + return this.entry.getInstanceFromInputPath(inputPath); + } + + // aliased upstream type + if ( + this._defaultEngine && + "getInstanceFromInputPath" in this._defaultEngine && + typeof this._defaultEngine.getInstanceFromInputPath === "function" + ) { + // returns Promise + return this._defaultEngine.getInstanceFromInputPath(inputPath); + } + + return false; + } + + /** + * Whether to use the module loader directly + * + * @override + */ + useJavaScriptImport() { + if ("useJavaScriptImport" in this.entry) { + return this.entry.useJavaScriptImport; + } + + if ( + this._defaultEngine && + "useJavaScriptImport" in this._defaultEngine && + typeof this._defaultEngine.useJavaScriptImport === "function" + ) { + return this._defaultEngine.useJavaScriptImport(); + } + + return false; + } + + /** + * @override + */ + needsToReadFileContents() { + if ("read" in this.entry) { + return this.entry.read; + } + + // Handle aliases to `11ty.js` templates, avoid reading files in the alias, see #2279 + // Here, we are short circuiting fallback to defaultRenderer, does not account for compile + // functions that call defaultRenderer explicitly + if (this._defaultEngine && "needsToReadFileContents" in this._defaultEngine) { + return this._defaultEngine.needsToReadFileContents(); + } + + return true; + } + + // If we init from multiple places, wait for the first init to finish before continuing on. + async _runningInit() { + if (this.needsInit) { + if (!this._initing) { + this._initBench = this.benchmarks.aggregate.get(`Engine (${this.name}) Init`); + this._initBench.before(); + this._initing = this.entry.init.bind({ + config: this.config, + bench: this.benchmarks.aggregate, + })(); + } + await this._initing; + this.needsInit = false; + + if (this._initBench) { + this._initBench.after(); + this._initBench = undefined; + } + } + } + + async getExtraDataFromFile(inputPath) { + if (this.entry.getData === false) { + return; + } + + if (!("getData" in this.entry)) { + // Handle aliases to `11ty.js` templates, use upstream default engine data fetch, see #2279 + if (this._defaultEngine && "getExtraDataFromFile" in this._defaultEngine) { + return this._defaultEngine.getExtraDataFromFile(inputPath); + } + + return; + } + + await this._runningInit(); + + if (typeof this.entry.getData === "function") { + let dataBench = this.benchmarks.aggregate.get( + `Engine (${this.name}) Get Data From File (Function)`, + ); + dataBench.before(); + let data = this.entry.getData(inputPath); + dataBench.after(); + return data; + } + + let keys = new Set(); + if (this.entry.getData === true) { + keys.add("data"); + } else if (Array.isArray(this.entry.getData)) { + for (let key of this.entry.getData) { + keys.add(key); + } + } + + let dataBench = this.benchmarks.aggregate.get(`Engine (${this.name}) Get Data From File`); + dataBench.before(); + + let inst = await this.getInstanceFromInputPath(inputPath); + + if (inst === false) { + dataBench.after(); + + return Promise.reject( + new Error( + `\`getInstanceFromInputPath\` callback missing from '${this.name}' template engine plugin. It is required when \`getData\` is in use. You can set \`getData: false\` to opt-out of this.`, + ), + ); + } + + // override keys set at the plugin level in the individual template + if (inst.eleventyDataKey) { + keys = new Set(inst.eleventyDataKey); + } + + let mixins; + if (this.config) { + // Object.assign usage: see TemplateRenderCustomTest.js: `JavaScript functions should not be mutable but not *that* mutable` + mixins = Object.assign({}, this.config.javascriptFunctions); + } + + let promises = []; + for (let key of keys) { + promises.push( + getJavaScriptData(inst, inputPath, key, { + mixins, + isObjectRequired: key === "data", + }), + ); + } + + let results = await Promise.all(promises); + let data = {}; + for (let result of results) { + Object.assign(data, result); + } + dataBench.after(); + + return data; + } + + async compile(str, inputPath, ...args) { + await this._runningInit(); + let defaultCompilationFn; + if (this._defaultEngine) { + defaultCompilationFn = async (data) => { + const renderFn = await this._defaultEngine.compile(str, inputPath, ...args); + return renderFn(data); + }; + } + + // Fall back to default compiler if the user does not provide their own + if (!this.entry.compile) { + if (defaultCompilationFn) { + return defaultCompilationFn; + } else { + throw new Error( + `Missing \`compile\` property for custom template syntax definition eleventyConfig.addExtension("${this.name}"). This is not necessary when aliasing to an existing template syntax.`, + ); + } + } + + // TODO generalize this (look at JavaScript.js) + let fn = this.entry.compile.bind({ + config: this.config, + addDependencies: (from, toArray = []) => { + this.config.uses.addDependency(from, toArray); + }, + defaultRenderer: defaultCompilationFn, // bind defaultRenderer to compile function + })(str, inputPath); + + // Support `undefined` to skip compile/render + if (fn) { + // Bind defaultRenderer to render function + if ("then" in fn && typeof fn.then === "function") { + // Promise, wait to bind + return fn.then((fn) => { + if (typeof fn === "function") { + return fn.bind({ + defaultRenderer: defaultCompilationFn, + }); + } + return fn; + }); + } else if ("bind" in fn && typeof fn.bind === "function") { + return fn.bind({ + defaultRenderer: defaultCompilationFn, + }); + } + } + + return fn; + } + + get defaultTemplateFileExtension() { + return this.entry.outputFileExtension ?? "html"; + } + + // Whether or not to wrap in Eleventy layouts + useLayouts() { + // TODO future change fallback to `this.defaultTemplateFileExtension === "html"` + return this.entry.useLayouts ?? true; + } + + hasDependencies(inputPath) { + if (this.config.uses.getDependencies(inputPath) === false) { + return false; + } + return true; + } + + isFileRelevantTo(inputPath, comparisonFile, includeLayouts) { + return this.config.uses.isFileRelevantTo(inputPath, comparisonFile, includeLayouts); + } + + getCompileCacheKey(str, inputPath) { + // Return this separately so we know whether or not to use the cached version + // but still return a key to cache this new render for next time + let useCache = !this.isFileRelevantTo(inputPath, lastModifiedFile, false); + + if (this.entry.compileOptions && "getCacheKey" in this.entry.compileOptions) { + if (typeof this.entry.compileOptions.getCacheKey !== "function") { + throw new Error( + `\`compileOptions.getCacheKey\` must be a function in addExtension for the ${this.name} type`, + ); + } + + return { + useCache, + key: this.entry.compileOptions.getCacheKey(str, inputPath), + }; + } + + let { key } = super.getCompileCacheKey(str, inputPath); + return { + useCache, + key, + }; + } + + permalinkNeedsCompilation(/*str*/) { + if (this.entry.compileOptions && "permalink" in this.entry.compileOptions) { + let p = this.entry.compileOptions.permalink; + if (p === "raw") { + return false; + } + + // permalink: false is aliased to permalink: () => false + if (p === false) { + return () => false; + } + + return this.entry.compileOptions.permalink; + } + + // Breaking: default changed from `true` to `false` in 3.0.0-alpha.13 + return false; + } + + static shouldSpiderJavaScriptDependencies(entry) { + if (entry.compileOptions && "spiderJavaScriptDependencies" in entry.compileOptions) { + return entry.compileOptions.spiderJavaScriptDependencies; + } + + return false; + } +} + +export default CustomEngine; diff --git a/node_modules/@11ty/eleventy/src/Engines/FrontMatter/JavaScript.js b/node_modules/@11ty/eleventy/src/Engines/FrontMatter/JavaScript.js new file mode 100644 index 0000000..b91ba36 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Engines/FrontMatter/JavaScript.js @@ -0,0 +1,34 @@ +import { RetrieveGlobals } from "node-retrieve-globals"; + +// `javascript` Front Matter Type +export default function (frontMatterCode, context = {}) { + let { filePath } = context; + + // context.language would be nice as a guard, but was unreliable + if (frontMatterCode.trimStart().startsWith("{")) { + return context.engines.jsLegacy.parse(frontMatterCode, context); + } + + let vm = new RetrieveGlobals(frontMatterCode, { + filePath, + // ignored if vm.Module is stable (or --experimental-vm-modules) + transformEsmImports: true, + }); + + // Future warning until vm.Module is stable: + // If the frontMatterCode uses `import` this uses the `experimentalModuleApi` + // option in node-retrieve-globals to workaround https://github.com/zachleat/node-retrieve-globals/issues/2 + let data = { + page: { + // Theoretically fileSlug and filePathStem could be added here but require extensionMap + inputPath: filePath, + }, + }; + + // this is async, but it’s handled in Eleventy upstream. + return vm.getGlobalContext(data, { + reuseGlobal: true, + dynamicImport: true, + // addRequire: true, + }); +} diff --git a/node_modules/@11ty/eleventy/src/Engines/Html.js b/node_modules/@11ty/eleventy/src/Engines/Html.js new file mode 100644 index 0000000..cab206b --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Engines/Html.js @@ -0,0 +1,28 @@ +import TemplateEngine from "./TemplateEngine.js"; + +class Html extends TemplateEngine { + constructor(name, eleventyConfig) { + super(name, eleventyConfig); + this.cacheable = true; + } + + async compile(str, inputPath, preTemplateEngine) { + if (preTemplateEngine) { + let engine = await this.engineManager.getEngine(preTemplateEngine, this.extensionMap); + let fnReady = engine.compile(str, inputPath); + + return async function (data) { + let fn = await fnReady; + + return fn(data); + }; + } + + return function () { + // do nothing with data if parseHtmlWith is falsy + return str; + }; + } +} + +export default Html; diff --git a/node_modules/@11ty/eleventy/src/Engines/JavaScript.js b/node_modules/@11ty/eleventy/src/Engines/JavaScript.js new file mode 100644 index 0000000..5ef27df --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Engines/JavaScript.js @@ -0,0 +1,237 @@ +import { TemplatePath, isPlainObject } from "@11ty/eleventy-utils"; + +import TemplateEngine from "./TemplateEngine.js"; +import EleventyBaseError from "../Errors/EleventyBaseError.js"; +import getJavaScriptData from "../Util/GetJavaScriptData.js"; +import EventBusUtil from "../Util/EventBusUtil.js"; +import { EleventyImport } from "../Util/Require.js"; +import { augmentFunction, augmentObject } from "./Util/ContextAugmenter.js"; + +class JavaScriptTemplateNotDefined extends EleventyBaseError {} + +class JavaScript extends TemplateEngine { + constructor(name, templateConfig) { + super(name, templateConfig); + this.instances = {}; + + this.cacheable = false; + EventBusUtil.soloOn("eleventy.templateModified", (inputPath, metadata = {}) => { + let { usedByDependants, relevantLayouts } = metadata; + // Remove from cached instances when modified + let instancesToDelete = [ + inputPath, + ...(usedByDependants || []), + ...(relevantLayouts || []), + ].map((entry) => TemplatePath.addLeadingDotSlash(entry)); + for (let inputPath of instancesToDelete) { + if (inputPath in this.instances) { + delete this.instances[inputPath]; + } + } + }); + } + + normalize(result) { + if (Buffer.isBuffer(result)) { + return result.toString(); + } + + return result; + } + + // String, Buffer, Promise + // Function, Class + // Object + // Module + _getInstance(mod) { + let noop = function () { + return ""; + }; + + let originalModData = mod?.data; + + if (typeof mod === "object" && mod.default && this.eleventyConfig.getIsProjectUsingEsm()) { + mod = mod.default; + } + + if (typeof mod === "string" || mod instanceof Buffer || mod.then) { + return { render: () => mod }; + } else if (typeof mod === "function") { + if (mod.prototype?.data || mod.prototype?.render) { + if (!("render" in mod.prototype)) { + mod.prototype.render = noop; + } + + if (!("data" in mod.prototype) && !mod.data && originalModData) { + mod.prototype.data = originalModData; + } + + return new mod(); + } else { + return { + ...(originalModData ? { data: originalModData } : undefined), + render: mod, + }; + } + } else if ("data" in mod || "render" in mod) { + if (!mod.render) { + mod.render = noop; + } + if (!mod.data && originalModData) { + mod.data = originalModData; + } + return mod; + } + } + + async #getInstanceFromInputPath(inputPath) { + let mod; + let relativeInputPath = + this.eleventyConfig.directories.getInputPathRelativeToInputDirectory(inputPath); + if (this.eleventyConfig.userConfig.isVirtualTemplate(relativeInputPath)) { + mod = this.eleventyConfig.userConfig.virtualTemplates[relativeInputPath].content; + } else { + let isEsm = this.eleventyConfig.getIsProjectUsingEsm(); + mod = await EleventyImport(inputPath, isEsm ? "esm" : "cjs"); + } + + let inst = this._getInstance(mod); + if (inst) { + this.instances[inputPath] = inst; + } else { + throw new JavaScriptTemplateNotDefined( + `No JavaScript template returned from ${inputPath}. Did you assign module.exports (CommonJS) or export (ESM)?`, + ); + } + return inst; + } + + async getInstanceFromInputPath(inputPath) { + if (!this.instances[inputPath]) { + this.instances[inputPath] = this.#getInstanceFromInputPath(inputPath); + } + + return this.instances[inputPath]; + } + + /** + * JavaScript files defer to the module loader rather than read the files to strings + * + * @override + */ + needsToReadFileContents() { + return false; + } + + /** + * Use the module loader directly + * + * @override + */ + useJavaScriptImport() { + return true; + } + + async getExtraDataFromFile(inputPath) { + let inst = await this.getInstanceFromInputPath(inputPath); + return getJavaScriptData(inst, inputPath); + } + + getJavaScriptFunctions(inst) { + let fns = {}; + let configFns = this.config.javascriptFunctions; + + for (let key in configFns) { + // prefer pre-existing `page` javascriptFunction, if one exists + fns[key] = augmentFunction(configFns[key], { + source: inst, + overwrite: false, + }); + } + return fns; + } + + // Backwards compat + static wrapJavaScriptFunction(inst, fn) { + return augmentFunction(fn, { + source: inst, + }); + } + + addExportsToBundles(inst, url) { + let cfg = this.eleventyConfig.userConfig; + if (!("getBundleManagers" in cfg)) { + return; + } + + let managers = cfg.getBundleManagers(); + for (let name in managers) { + let mgr = managers[name]; + let key = mgr.getBundleExportKey(); + if (!key) { + continue; + } + + if (typeof inst[key] === "string") { + // export const css = ``; + mgr.addToPage(url, inst[key]); + } else if (isPlainObject(inst[key])) { + if (typeof inst[key][name] === "string") { + // Object with bundle names: + // export const bundle = { + // css: `` + // }; + mgr.addToPage(url, inst[key][name]); + } else if (isPlainObject(inst[key][name])) { + // Object with bucket names: + // export const bundle = { + // css: { + // default: `` + // } + // }; + for (let bucketName in inst[key][name]) { + mgr.addToPage(url, inst[key][name][bucketName], bucketName); + } + } + } + } + } + + async compile(str, inputPath) { + let inst; + if (str) { + // When str has a value, it's being used for permalinks in data + inst = this._getInstance(str); + } else { + // For normal templates, str will be falsy. + inst = await this.getInstanceFromInputPath(inputPath); + } + + if (inst?.render) { + return function (data = {}) { + // TODO does this do anything meaningful for non-classes? + // `inst` should have a normalized `render` function from _getInstance + + // Map exports to bundles + if (data.page?.url) { + this.addExportsToBundles(inst, data.page.url); + } + + augmentObject(inst, { + source: data, + overwrite: false, + }); + + Object.assign(inst, this.getJavaScriptFunctions(inst)); + + return this.normalize(inst.render.call(inst, data)); + }.bind(this); + } + } + + static shouldSpiderJavaScriptDependencies() { + return true; + } +} + +export default JavaScript; diff --git a/node_modules/@11ty/eleventy/src/Engines/Liquid.js b/node_modules/@11ty/eleventy/src/Engines/Liquid.js new file mode 100644 index 0000000..4e94226 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Engines/Liquid.js @@ -0,0 +1,326 @@ +import moo from "moo"; +import { Tokenizer, TokenKind, evalToken, Liquid as LiquidJs } from "liquidjs"; +import { TemplatePath } from "@11ty/eleventy-utils"; +// import debugUtil from "debug"; + +import TemplateEngine from "./TemplateEngine.js"; +import { augmentObject } from "./Util/ContextAugmenter.js"; + +// const debug = debugUtil("Eleventy:Liquid"); + +class Liquid extends TemplateEngine { + static argumentLexerOptions = { + number: /[0-9]+\.*[0-9]*/, + doubleQuoteString: /"(?:\\["\\]|[^\n"\\])*"/, + singleQuoteString: /'(?:\\['\\]|[^\n'\\])*'/, + keyword: /[a-zA-Z0-9.\-_]+/, + "ignore:whitespace": /[, \t]+/, // includes comma separator + }; + + constructor(name, eleventyConfig) { + super(name, eleventyConfig); + + this.liquidOptions = this.config.liquidOptions || {}; + + this.setLibrary(this.config.libraryOverrides.liquid); + + this.argLexer = moo.compile(Liquid.argumentLexerOptions); + this.cacheable = true; + } + + setLibrary(override) { + // warning, the include syntax supported here does not exactly match what Jekyll uses. + this.liquidLib = override || new LiquidJs(this.getLiquidOptions()); + this.setEngineLib(this.liquidLib); + + this.addFilters(this.config.liquidFilters); + + // TODO these all go to the same place (addTag), add warnings for overwrites + this.addCustomTags(this.config.liquidTags); + this.addAllShortcodes(this.config.liquidShortcodes); + this.addAllPairedShortcodes(this.config.liquidPairedShortcodes); + } + + getLiquidOptions() { + let defaults = { + root: [this.dirs.includes, this.dirs.input], // supplemented in compile with inputPath below + extname: ".liquid", + strictFilters: true, + // TODO? + // cache: true, + }; + + let options = Object.assign(defaults, this.liquidOptions || {}); + // debug("Liquid constructor options: %o", options); + + return options; + } + + static wrapFilter(name, fn) { + /** + * @this {object} + */ + return function (...args) { + // Set this.eleventy and this.page + if (typeof this.context?.get === "function") { + augmentObject(this, { + source: this.context, + getter: (key, context) => context.get([key]), + + lazy: this.context.strictVariables, + }); + } + + // We *don’t* wrap this in an EleventyFilterError because Liquid has a better error message with line/column information in the template + return fn.call(this, ...args); + }; + } + + // Shortcodes + static normalizeScope(context) { + let obj = {}; + if (context) { + obj.ctx = context; // Full context available on `ctx` + + // Set this.eleventy and this.page + augmentObject(obj, { + source: context, + getter: (key, context) => context.get([key]), + lazy: context.strictVariables, + }); + } + + return obj; + } + + addCustomTags(tags) { + for (let name in tags) { + this.addTag(name, tags[name]); + } + } + + addFilters(filters) { + for (let name in filters) { + this.addFilter(name, filters[name]); + } + } + + addFilter(name, filter) { + this.liquidLib.registerFilter(name, Liquid.wrapFilter(name, filter)); + } + + addTag(name, tagFn) { + let tagObj; + if (typeof tagFn === "function") { + tagObj = tagFn(this.liquidLib); + } else { + throw new Error( + "Liquid.addTag expects a callback function to be passed in: addTag(name, function(liquidEngine) { return { parse: …, render: … } })", + ); + } + this.liquidLib.registerTag(name, tagObj); + } + + addAllShortcodes(shortcodes) { + for (let name in shortcodes) { + this.addShortcode(name, shortcodes[name]); + } + } + + addAllPairedShortcodes(shortcodes) { + for (let name in shortcodes) { + this.addPairedShortcode(name, shortcodes[name]); + } + } + + static parseArguments(lexer, str) { + let argArray = []; + + if (!lexer) { + lexer = moo.compile(Liquid.argumentLexerOptions); + } + + if (typeof str === "string") { + lexer.reset(str); + + let arg = lexer.next(); + while (arg) { + /*{ + type: 'doubleQuoteString', + value: '"test 2"', + text: '"test 2"', + toString: [Function: tokenToString], + offset: 0, + lineBreaks: 0, + line: 1, + col: 1 }*/ + if (arg.type.indexOf("ignore:") === -1) { + // Push the promise into an array instead of awaiting it here. + // This forces the promises to run in order with the correct scope value for each arg. + // Otherwise they run out of order and can lead to undefined values for arguments in layout template shortcodes. + // console.log( arg.value, scope, engine ); + argArray.push(arg.value); + } + arg = lexer.next(); + } + } + + return argArray; + } + + static parseArgumentsBuiltin(args) { + let tokenizer = new Tokenizer(args); + let parsedArgs = []; + + let value = tokenizer.readValue(); + while (value) { + parsedArgs.push(value); + tokenizer.skipBlank(); + if (tokenizer.peek() === ",") { + tokenizer.advance(); + } + value = tokenizer.readValue(); + } + tokenizer.end(); + + return parsedArgs; + } + + addShortcode(shortcodeName, shortcodeFn) { + let _t = this; + this.addTag(shortcodeName, function (liquidEngine) { + return { + parse(tagToken) { + this.name = tagToken.name; + if (_t.config.liquidParameterParsing === "builtin") { + this.orderedArgs = Liquid.parseArgumentsBuiltin(tagToken.args); + // note that Liquid does have a Hash class for name-based argument parsing but offers no easy to support both modes in one class + } else { + this.legacyArgs = tagToken.args; + } + }, + render: function* (ctx) { + let argArray = []; + + if (this.legacyArgs) { + let rawArgs = Liquid.parseArguments(_t.argLexer, this.legacyArgs); + for (let arg of rawArgs) { + let b = yield liquidEngine.evalValue(arg, ctx); + argArray.push(b); + } + } else if (this.orderedArgs) { + for (let arg of this.orderedArgs) { + let b = yield evalToken(arg, ctx); + argArray.push(b); + } + } + + let ret = yield shortcodeFn.call(Liquid.normalizeScope(ctx), ...argArray); + return ret; + }, + }; + }); + } + + addPairedShortcode(shortcodeName, shortcodeFn) { + let _t = this; + this.addTag(shortcodeName, function (liquidEngine) { + return { + parse(tagToken, remainTokens) { + this.name = tagToken.name; + + if (_t.config.liquidParameterParsing === "builtin") { + this.orderedArgs = Liquid.parseArgumentsBuiltin(tagToken.args); + // note that Liquid does have a Hash class for name-based argument parsing but offers no easy to support both modes in one class + } else { + this.legacyArgs = tagToken.args; + } + + this.templates = []; + + var stream = liquidEngine.parser + .parseStream(remainTokens) + .on("template", (tpl) => this.templates.push(tpl)) + .on("tag:end" + shortcodeName, () => stream.stop()) + .on("end", () => { + throw new Error(`tag ${tagToken.raw} not closed`); + }); + + stream.start(); + }, + render: function* (ctx /*, emitter*/) { + let argArray = []; + if (this.legacyArgs) { + let rawArgs = Liquid.parseArguments(_t.argLexer, this.legacyArgs); + for (let arg of rawArgs) { + let b = yield liquidEngine.evalValue(arg, ctx); + argArray.push(b); + } + } else if (this.orderedArgs) { + for (let arg of this.orderedArgs) { + let b = yield evalToken(arg, ctx); + argArray.push(b); + } + } + + const html = yield liquidEngine.renderer.renderTemplates(this.templates, ctx); + + let ret = yield shortcodeFn.call(Liquid.normalizeScope(ctx), html, ...argArray); + + return ret; + }, + }; + }); + } + + parseForSymbols(str) { + let tokenizer = new Tokenizer(str); + /** @type {Array} */ + let tokens = tokenizer.readTopLevelTokens(); + let symbols = tokens + .filter((token) => token.kind === TokenKind.Output) + .map((token) => { + // manually remove filters 😅 + return token.content.split("|").map((entry) => entry.trim())[0]; + }); + return symbols; + } + + // Don’t return a boolean if permalink is a function (see TemplateContent->renderPermalink) + /** @returns {boolean|undefined} */ + permalinkNeedsCompilation(str) { + if (typeof str === "string") { + return this.needsCompilation(str); + } + } + + needsCompilation(str) { + let options = this.liquidLib.options; + + return ( + str.indexOf(options.tagDelimiterLeft) !== -1 || + str.indexOf(options.outputDelimiterLeft) !== -1 + ); + } + + async compile(str, inputPath) { + let engine = this.liquidLib; + let tmplReady = engine.parse(str, inputPath); + + // Required for relative includes + let options = {}; + if (!inputPath || inputPath === "liquid" || inputPath === "md") { + // do nothing + } else { + options.root = [TemplatePath.getDirFromFilePath(inputPath)]; + } + + return async function (data) { + let tmpl = await tmplReady; + + return engine.render(tmpl, data, options); + }; + } +} + +export default Liquid; diff --git a/node_modules/@11ty/eleventy/src/Engines/Markdown.js b/node_modules/@11ty/eleventy/src/Engines/Markdown.js new file mode 100644 index 0000000..0e88c27 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Engines/Markdown.js @@ -0,0 +1,93 @@ +import markdownIt from "markdown-it"; + +import TemplateEngine from "./TemplateEngine.js"; + +class Markdown extends TemplateEngine { + constructor(name, eleventyConfig) { + super(name, eleventyConfig); + + this.markdownOptions = {}; + + this.setLibrary(this.config.libraryOverrides.md); + + this.cacheable = true; + } + + setLibrary(mdLib) { + this.mdLib = mdLib || markdownIt(this.getMarkdownOptions()); + + // Overrides a highlighter set in `markdownOptions` + // This is separate so devs can pass in a new mdLib and still use the official eleventy plugin for markdown highlighting + if (this.config.markdownHighlighter && typeof this.mdLib.set === "function") { + this.mdLib.set({ + highlight: this.config.markdownHighlighter, + }); + } + + if (typeof this.mdLib.disable === "function") { + // Disable indented code blocks by default (Issue #2438) + this.mdLib.disable("code"); + } + + this.setEngineLib(this.mdLib); + } + + setMarkdownOptions(options) { + this.markdownOptions = options; + } + + getMarkdownOptions() { + // work with "mode" presets https://github.com/markdown-it/markdown-it#init-with-presets-and-options + if (typeof this.markdownOptions === "string") { + return this.markdownOptions; + } + + return Object.assign( + { + html: true, + }, + this.markdownOptions || {}, + ); + } + + async compile(str, inputPath, preTemplateEngine, bypassMarkdown) { + let mdlib = this.mdLib; + + if (preTemplateEngine) { + let engine; + if (typeof preTemplateEngine === "string") { + engine = await this.engineManager.getEngine(preTemplateEngine, this.extensionMap); + } else { + engine = preTemplateEngine; + } + + let fnReady = engine.compile(str, inputPath); + + if (bypassMarkdown) { + return async function (data) { + let fn = await fnReady; + return fn(data); + }; + } else { + return async function (data) { + let fn = await fnReady; + let preTemplateEngineRender = await fn(data); + let finishedRender = mdlib.render(preTemplateEngineRender, data); + return finishedRender; + }; + } + } else { + if (bypassMarkdown) { + return function () { + return str; + }; + } else { + return function (data) { + return mdlib.render(str, data); + }; + } + } + } +} + +export default Markdown; diff --git a/node_modules/@11ty/eleventy/src/Engines/Nunjucks.js b/node_modules/@11ty/eleventy/src/Engines/Nunjucks.js new file mode 100755 index 0000000..2edd925 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Engines/Nunjucks.js @@ -0,0 +1,447 @@ +import NunjucksLib from "nunjucks"; +import { TemplatePath } from "@11ty/eleventy-utils"; + +import TemplateEngine from "./TemplateEngine.js"; +import EleventyBaseError from "../Errors/EleventyBaseError.js"; +import EventBusUtil from "../Util/EventBusUtil.js"; +import { augmentObject } from "./Util/ContextAugmenter.js"; + +class EleventyNunjucksError extends EleventyBaseError {} + +class Nunjucks extends TemplateEngine { + constructor(name, eleventyConfig) { + super(name, eleventyConfig); + + this.nunjucksEnvironmentOptions = this.config.nunjucksEnvironmentOptions || { dev: true }; + + this.nunjucksPrecompiledTemplates = this.config.nunjucksPrecompiledTemplates || {}; + this._usingPrecompiled = Object.keys(this.nunjucksPrecompiledTemplates).length > 0; + + this.setLibrary(this.config.libraryOverrides.njk); + + this.cacheable = true; + } + + _setEnv(override) { + if (override) { + this.njkEnv = override; + } else if (this._usingPrecompiled) { + // Precompiled templates to avoid eval! + const NodePrecompiledLoader = function () {}; + + NodePrecompiledLoader.prototype.getSource = (name) => { + // https://github.com/mozilla/nunjucks/blob/fd500902d7c88672470c87170796de52fc0f791a/nunjucks/src/precompiled-loader.js#L5 + return { + src: { + type: "code", + obj: this.nunjucksPrecompiledTemplates[name], + }, + // Maybe add this? + // path, + // noCache: true + }; + }; + + this.njkEnv = new NunjucksLib.Environment( + new NodePrecompiledLoader(), + this.nunjucksEnvironmentOptions, + ); + } else { + let paths = new Set(); + paths.add(super.getIncludesDir()); + paths.add(TemplatePath.getWorkingDir()); + + // Filter out undefined paths + let fsLoader = new NunjucksLib.FileSystemLoader(Array.from(paths).filter(Boolean)); + + this.njkEnv = new NunjucksLib.Environment(fsLoader, this.nunjucksEnvironmentOptions); + } + + this.config.events.emit("eleventy.engine.njk", { + nunjucks: NunjucksLib, + environment: this.njkEnv, + }); + } + + setLibrary(override) { + this._setEnv(override); + + // Correct, but overbroad. Better would be to evict more granularly, but + // resolution from paths isn't straightforward. + EventBusUtil.soloOn("eleventy.templateModified", (/*path*/) => { + this.njkEnv.invalidateCache(); + }); + + this.setEngineLib(this.njkEnv); + + this.addFilters(this.config.nunjucksFilters); + this.addFilters(this.config.nunjucksAsyncFilters, true); + + // TODO these all go to the same place (addTag), add warnings for overwrites + // TODO(zachleat): variableName should work with quotes or without quotes (same as {% set %}) + this.addPairedShortcode("setAsync", function (content, variableName) { + this.ctx[variableName] = content; + return ""; + }); + + this.addCustomTags(this.config.nunjucksTags); + this.addAllShortcodes(this.config.nunjucksShortcodes); + this.addAllShortcodes(this.config.nunjucksAsyncShortcodes, true); + this.addAllPairedShortcodes(this.config.nunjucksPairedShortcodes); + this.addAllPairedShortcodes(this.config.nunjucksAsyncPairedShortcodes, true); + this.addGlobals(this.config.nunjucksGlobals); + } + + addFilters(filters, isAsync) { + for (let name in filters) { + this.njkEnv.addFilter(name, Nunjucks.wrapFilter(name, filters[name]), isAsync); + } + } + + static wrapFilter(name, fn) { + return function (...args) { + try { + augmentObject(this, { + source: this.ctx, + lazy: false, // context.env?.opts.throwOnUndefined, + }); + + return fn.call(this, ...args); + } catch (e) { + throw new EleventyNunjucksError( + `Error in Nunjucks Filter \`${name}\`${this.page ? ` (${this.page.inputPath})` : ""}`, + e, + ); + } + }; + } + + // Shortcodes + static normalizeContext(context) { + let obj = {}; + if (context.ctx) { + obj.ctx = context.ctx; + obj.env = context.env; + + augmentObject(obj, { + source: context.ctx, + lazy: false, // context.env?.opts.throwOnUndefined, + }); + } + return obj; + } + + addCustomTags(tags) { + for (let name in tags) { + this.addTag(name, tags[name]); + } + } + + addTag(name, tagFn) { + let tagObj; + if (typeof tagFn === "function") { + tagObj = tagFn(NunjucksLib, this.njkEnv); + } else { + throw new Error( + "Nunjucks.addTag expects a callback function to be passed in: addTag(name, function(nunjucksEngine) {})", + ); + } + + this.njkEnv.addExtension(name, tagObj); + } + + addGlobals(globals) { + for (let name in globals) { + this.addGlobal(name, globals[name]); + } + } + + addGlobal(name, globalFn) { + this.njkEnv.addGlobal(name, globalFn); + } + + addAllShortcodes(shortcodes, isAsync = false) { + for (let name in shortcodes) { + this.addShortcode(name, shortcodes[name], isAsync); + } + } + + addAllPairedShortcodes(shortcodes, isAsync = false) { + for (let name in shortcodes) { + this.addPairedShortcode(name, shortcodes[name], isAsync); + } + } + + _getShortcodeFn(shortcodeName, shortcodeFn, isAsync = false) { + return function ShortcodeFunction() { + this.tags = [shortcodeName]; + + this.parse = function (parser, nodes) { + let args; + let tok = parser.nextToken(); + + args = parser.parseSignature(true, true); + + // Nunjucks bug with non-paired custom tags bug still exists even + // though this issue is closed. Works fine for paired. + // https://github.com/mozilla/nunjucks/issues/158 + if (args.children.length === 0) { + args.addChild(new nodes.Literal(0, 0, "")); + } + + parser.advanceAfterBlockEnd(tok.value); + if (isAsync) { + return new nodes.CallExtensionAsync(this, "run", args); + } + return new nodes.CallExtension(this, "run", args); + }; + + this.run = function (...args) { + let resolve; + if (isAsync) { + resolve = args.pop(); + } + + let [context, ...argArray] = args; + + if (isAsync) { + let ret = shortcodeFn.call(Nunjucks.normalizeContext(context), ...argArray); + + // #3286 error messaging when the shortcode is not a promise + if (!ret?.then) { + resolve( + new EleventyNunjucksError( + `Error with Nunjucks shortcode \`${shortcodeName}\`: it was defined as asynchronous but was actually synchronous. This is important for Nunjucks.`, + ), + ); + } + + ret.then( + function (returnValue) { + resolve(null, new NunjucksLib.runtime.SafeString("" + returnValue)); + }, + function (e) { + resolve( + new EleventyNunjucksError(`Error with Nunjucks shortcode \`${shortcodeName}\``, e), + ); + }, + ); + } else { + try { + let ret = shortcodeFn.call(Nunjucks.normalizeContext(context), ...argArray); + return new NunjucksLib.runtime.SafeString("" + ret); + } catch (e) { + throw new EleventyNunjucksError( + `Error with Nunjucks shortcode \`${shortcodeName}\``, + e, + ); + } + } + }; + }; + } + + _getPairedShortcodeFn(shortcodeName, shortcodeFn, isAsync = false) { + return function PairedShortcodeFunction() { + this.tags = [shortcodeName]; + + this.parse = function (parser, nodes) { + var tok = parser.nextToken(); + + var args = parser.parseSignature(true, true); + parser.advanceAfterBlockEnd(tok.value); + + var body = parser.parseUntilBlocks("end" + shortcodeName); + parser.advanceAfterBlockEnd(); + + return new nodes.CallExtensionAsync(this, "run", args, [body]); + }; + + this.run = function (...args) { + let resolve = args.pop(); + let body = args.pop(); + let [context, ...argArray] = args; + + body(function (e, bodyContent) { + if (e) { + resolve( + new EleventyNunjucksError( + `Error with Nunjucks paired shortcode \`${shortcodeName}\``, + e, + ), + ); + } + + if (isAsync) { + let ret = shortcodeFn.call( + Nunjucks.normalizeContext(context), + bodyContent, + ...argArray, + ); + + // #3286 error messaging when the shortcode is not a promise + if (!ret?.then) { + throw new EleventyNunjucksError( + `Error with Nunjucks shortcode \`${shortcodeName}\`: it was defined as asynchronous but was actually synchronous. This is important for Nunjucks.`, + ); + } + + ret.then( + function (returnValue) { + resolve(null, new NunjucksLib.runtime.SafeString(returnValue)); + }, + function (e) { + resolve( + new EleventyNunjucksError( + `Error with Nunjucks paired shortcode \`${shortcodeName}\``, + e, + ), + ); + }, + ); + } else { + try { + resolve( + null, + new NunjucksLib.runtime.SafeString( + shortcodeFn.call(Nunjucks.normalizeContext(context), bodyContent, ...argArray), + ), + ); + } catch (e) { + resolve( + new EleventyNunjucksError( + `Error with Nunjucks paired shortcode \`${shortcodeName}\``, + e, + ), + ); + } + } + }); + }; + }; + } + + addShortcode(shortcodeName, shortcodeFn, isAsync = false) { + let fn = this._getShortcodeFn(shortcodeName, shortcodeFn, isAsync); + this.njkEnv.addExtension(shortcodeName, new fn()); + } + + addPairedShortcode(shortcodeName, shortcodeFn, isAsync = false) { + let fn = this._getPairedShortcodeFn(shortcodeName, shortcodeFn, isAsync); + this.njkEnv.addExtension(shortcodeName, new fn()); + } + + // Don’t return a boolean if permalink is a function (see TemplateContent->renderPermalink) + permalinkNeedsCompilation(str) { + if (typeof str === "string") { + return this.needsCompilation(str); + } + } + + needsCompilation(str) { + // Defend against syntax customisations: + // https://mozilla.github.io/nunjucks/api.html#customizing-syntax + let optsTags = this.njkEnv.opts.tags || {}; + let blockStart = optsTags.blockStart || "{%"; + let variableStart = optsTags.variableStart || "{{"; + let commentStart = optsTags.variableStart || "{#"; + + return ( + str.indexOf(blockStart) !== -1 || + str.indexOf(variableStart) !== -1 || + str.indexOf(commentStart) !== -1 + ); + } + + _getParseExtensions() { + if (this._parseExtensions) { + return this._parseExtensions; + } + + // add extensions so the parser knows about our custom tags/blocks + let ext = []; + for (let name in this.config.nunjucksTags) { + let fn = this._getShortcodeFn(name, () => {}); + ext.push(new fn()); + } + for (let name in this.config.nunjucksShortcodes) { + let fn = this._getShortcodeFn(name, () => {}); + ext.push(new fn()); + } + for (let name in this.config.nunjucksAsyncShortcodes) { + let fn = this._getShortcodeFn(name, () => {}, true); + ext.push(new fn()); + } + for (let name in this.config.nunjucksPairedShortcodes) { + let fn = this._getPairedShortcodeFn(name, () => {}); + ext.push(new fn()); + } + for (let name in this.config.nunjucksAsyncPairedShortcodes) { + let fn = this._getPairedShortcodeFn(name, () => {}, true); + ext.push(new fn()); + } + + this._parseExtensions = ext; + return ext; + } + + /* Outputs an Array of lodash get selectors */ + parseForSymbols(str) { + const { parser, nodes } = NunjucksLib; + let obj = parser.parse(str, this._getParseExtensions()); + let linesplit = str.split("\n"); + let values = obj.findAll(nodes.Value); + let symbols = obj.findAll(nodes.Symbol).map((entry) => { + let name = [entry.value]; + let nestedIndex = -1; + for (let val of values) { + if (nestedIndex > -1) { + /* deep.object.syntax */ + if (linesplit[val.lineno].charAt(nestedIndex) === ".") { + name.push(val.value); + nestedIndex += val.value.length + 1; + } else { + nestedIndex = -1; + } + } else if ( + val.lineno === entry.lineno && + val.colno === entry.colno && + val.value === entry.value + ) { + nestedIndex = entry.colno + entry.value.length; + } + } + return name.join("."); + }); + + let uniqueSymbols = Array.from(new Set(symbols)); + return uniqueSymbols; + } + + async compile(str, inputPath) { + let tmpl; + + // *All* templates are precompiled to avoid runtime eval + if (this._usingPrecompiled) { + tmpl = this.njkEnv.getTemplate(str, true); + } else if (!inputPath || inputPath === "njk" || inputPath === "md") { + tmpl = new NunjucksLib.Template(str, this.njkEnv, null, false); + } else { + tmpl = new NunjucksLib.Template(str, this.njkEnv, inputPath, false); + } + + return function (data) { + return new Promise(function (resolve, reject) { + tmpl.render(data, function (err, res) { + if (err) { + reject(err); + } else { + resolve(res); + } + }); + }); + }; + } +} + +export default Nunjucks; diff --git a/node_modules/@11ty/eleventy/src/Engines/TemplateEngine.js b/node_modules/@11ty/eleventy/src/Engines/TemplateEngine.js new file mode 100644 index 0000000..bf228ef --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Engines/TemplateEngine.js @@ -0,0 +1,184 @@ +import EleventyExtensionMap from "../EleventyExtensionMap.js"; +import EleventyBaseError from "../Errors/EleventyBaseError.js"; + +class TemplateEngineConfigError extends EleventyBaseError {} + +class TemplateEngine { + constructor(name, eleventyConfig) { + this.name = name; + + this.engineLib = null; + this.cacheable = false; + + if (!eleventyConfig) { + throw new TemplateEngineConfigError("Missing `eleventyConfig` argument."); + } + this.eleventyConfig = eleventyConfig; + } + + get dirs() { + return this.eleventyConfig.directories; + } + + get inputDir() { + return this.dirs.input; + } + + get includesDir() { + return this.dirs.includes; + } + + get config() { + if (this.eleventyConfig.constructor.name !== "TemplateConfig") { + throw new Error("Expecting a TemplateConfig instance."); + } + + return this.eleventyConfig.getConfig(); + } + + get benchmarks() { + if (!this._benchmarks) { + this._benchmarks = { + aggregate: this.config.benchmarkManager.get("Aggregate"), + }; + } + return this._benchmarks; + } + + get engineManager() { + return this._engineManager; + } + + set engineManager(manager) { + this._engineManager = manager; + } + + get extensionMap() { + if (!this._extensionMap) { + this._extensionMap = new EleventyExtensionMap(this.eleventyConfig); + this._extensionMap.setFormats([]); + } + return this._extensionMap; + } + + set extensionMap(map) { + this._extensionMap = map; + } + + get extensions() { + if (!this._extensions) { + this._extensions = this.extensionMap.getExtensionsFromKey(this.name); + } + return this._extensions; + } + + get extensionEntries() { + if (!this._extensionEntries) { + this._extensionEntries = this.extensionMap.getExtensionEntriesFromKey(this.name); + } + return this._extensionEntries; + } + + getName() { + return this.name; + } + + // Backwards compat + getIncludesDir() { + return this.includesDir; + } + + /** + * @protected + */ + setEngineLib(engineLib) { + this.engineLib = engineLib; + + // Run engine amendments (via issue #2438) + for (let amendment of this.config.libraryAmendments[this.name] || []) { + // TODO it’d be nice if this were async friendly + amendment(engineLib); + } + } + + getEngineLib() { + return this.engineLib; + } + + async _testRender(str, data) { + // @ts-ignore + let fn = await this.compile(str); + return fn(data); + } + + useJavaScriptImport() { + return false; + } + + // JavaScript files defer to the module loader rather than read the files to strings + needsToReadFileContents() { + return true; + } + + getExtraDataFromFile() { + return {}; + } + + getCompileCacheKey(str, inputPath) { + // Changing to use inputPath and contents, using only file contents (`str`) caused issues when two + // different files had identical content (2.0.0-canary.16) + + // Caches are now segmented based on inputPath so using inputPath here is superfluous (2.0.0-canary.19) + // But we do want a non-falsy value here even if `str` is an empty string. + return { + useCache: true, + key: inputPath + str, + }; + } + + get defaultTemplateFileExtension() { + return "html"; + } + + // Whether or not to wrap in Eleventy layouts + useLayouts() { + return true; + } + + /** @returns {boolean|undefined} */ + permalinkNeedsCompilation(str) { + return this.needsCompilation(); + } + + // whether or not compile is needed or can we return the plaintext? + needsCompilation(str) { + return true; + } + + /** + * Make sure compile is implemented downstream. + * @abstract + * @return {Promise} + */ + async compile() { + throw new Error("compile() must be implemented by engine"); + } + + // See https://v3.11ty.dev/docs/watch-serve/#watch-javascript-dependencies + static shouldSpiderJavaScriptDependencies() { + return false; + } + + hasDependencies(inputPath) { + if (this.config.uses.getDependencies(inputPath) === false) { + return false; + } + return true; + } + + isFileRelevantTo(inputPath, comparisonFile) { + return this.config.uses.isFileRelevantTo(inputPath, comparisonFile); + } +} + +export default TemplateEngine; diff --git a/node_modules/@11ty/eleventy/src/Engines/TemplateEngineManager.js b/node_modules/@11ty/eleventy/src/Engines/TemplateEngineManager.js new file mode 100644 index 0000000..35f9c58 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Engines/TemplateEngineManager.js @@ -0,0 +1,197 @@ +import debugUtil from "debug"; +import EleventyBaseError from "../Errors/EleventyBaseError.js"; +import { EleventyImportFromEleventy } from "../Util/Require.js"; + +const debug = debugUtil("Eleventy:TemplateEngineManager"); + +class TemplateEngineManagerConfigError extends EleventyBaseError {} + +class TemplateEngineManager { + constructor(eleventyConfig) { + if (!eleventyConfig || eleventyConfig.constructor.name !== "TemplateConfig") { + throw new TemplateEngineManagerConfigError("Missing or invalid `config` argument."); + } + this.eleventyConfig = eleventyConfig; + + this.engineCache = {}; + this.importCache = {}; + } + + get config() { + return this.eleventyConfig.getConfig(); + } + + static isAlias(entry) { + if (entry.aliasKey) { + return true; + } + + return entry.key !== entry.extension; + } + + static isSimpleAlias(entry) { + if (!this.isAlias(entry)) { + return false; + } + + // has keys other than key, extension, and aliasKey + return ( + Object.keys(entry).some((key) => { + return key !== "key" && key !== "extension" && key !== "aliasKey"; + }) === false + ); + } + + get keyToClassNameMap() { + if (!this._keyToClassNameMap) { + this._keyToClassNameMap = { + md: "Markdown", + html: "Html", + njk: "Nunjucks", + liquid: "Liquid", + "11ty.js": "JavaScript", + }; + + // Custom entries *can* overwrite default entries above + if ("extensionMap" in this.config) { + for (let entry of this.config.extensionMap) { + // either the key does not already exist or it is not a simple alias and is an override: https://v3.11ty.dev/docs/languages/custom/#overriding-an-existing-template-language + let existingTarget = this._keyToClassNameMap[entry.key]; + let isAlias = TemplateEngineManager.isAlias(entry); + + if (!existingTarget && isAlias) { + throw new Error( + `An attempt to alias ${entry.aliasKey} to ${entry.key} was made, but ${entry.key} is not a recognized template syntax.`, + ); + } + + if (isAlias) { + // only `key` and `extension`, not `compile` or other options + if (!TemplateEngineManager.isSimpleAlias(entry)) { + this._keyToClassNameMap[entry.aliasKey] = "Custom"; + } else { + this._keyToClassNameMap[entry.aliasKey] = this._keyToClassNameMap[entry.key]; + } + } else { + // not an alias, so `key` and `extension` are the same here. + // *can* override a built-in extension! + this._keyToClassNameMap[entry.key] = "Custom"; + } + } + } + } + + return this._keyToClassNameMap; + } + + reset() { + this.engineCache = {}; + } + + getClassNameFromTemplateKey(key) { + return this.keyToClassNameMap[key]; + } + + hasEngine(name) { + return !!this.getClassNameFromTemplateKey(name); + } + + isEngineRemovedFromCore(name) { + return ["ejs", "hbs", "mustache", "haml", "pug"].includes(name) && !this.hasEngine(name); + } + + async getEngineClassByExtension(extension) { + if (this.importCache[extension]) { + return this.importCache[extension]; + } + + let promise; + + // We include these as raw strings (and not more readable variables) so they’re parsed by a bundler. + if (extension === "md") { + promise = EleventyImportFromEleventy("./src/Engines/Markdown.js"); + } else if (extension === "html") { + promise = EleventyImportFromEleventy("./src/Engines/Html.js"); + } else if (extension === "njk") { + promise = EleventyImportFromEleventy("./src/Engines/Nunjucks.js"); + } else if (extension === "liquid") { + promise = EleventyImportFromEleventy("./src/Engines/Liquid.js"); + } else if (extension === "11ty.js") { + promise = EleventyImportFromEleventy("./src/Engines/JavaScript.js"); + } else { + promise = this.getCustomEngineClass(); + } + + this.importCache[extension] = promise; + + return promise; + } + + async getCustomEngineClass() { + if (!this._CustomEngine) { + this._CustomEngine = EleventyImportFromEleventy("./src/Engines/Custom.js"); + } + return this._CustomEngine; + } + + async #getEngine(name, extensionMap) { + let cls = await this.getEngineClassByExtension(name); + let instance = new cls(name, this.eleventyConfig); + instance.extensionMap = extensionMap; + instance.engineManager = this; + + let extensionEntry = extensionMap.getExtensionEntry(name); + + // Override a built-in extension (md => md) + // If provided a "Custom" engine using addExtension, but that engine's instance is *not* custom, + // The user must be overriding a built-in engine i.e. addExtension('md', { ...overrideBehavior }) + let className = this.getClassNameFromTemplateKey(name); + + if (className === "Custom" && instance.constructor.name !== "CustomEngine") { + let CustomEngine = await this.getCustomEngineClass(); + let overrideCustomEngine = new CustomEngine(name, this.eleventyConfig); + + // Keep track of the "default" engine 11ty would normally use + // This allows the user to access the default engine in their override + overrideCustomEngine.setDefaultEngine(instance); + + instance = overrideCustomEngine; + // Alias to a built-in extension (11ty.tsx => 11ty.js) + } else if ( + instance.constructor.name === "CustomEngine" && + TemplateEngineManager.isAlias(extensionEntry) + ) { + // add defaultRenderer for complex aliases with their own compile functions. + let originalEngineInstance = await this.getEngine(extensionEntry.key, extensionMap); + instance.setDefaultEngine(originalEngineInstance); + } + + return instance; + } + + async getEngine(name, extensionMap) { + // Warning about engine deprecation + if (this.isEngineRemovedFromCore(name)) { + throw new Error( + `Per the 11ty Community Survey (2023), the "${name}" template language was moved from core to an officially supported plugin in v3.0. These plugins live here: https://github.com/11ty/eleventy-plugin-template-languages and are documented on their respective template language docs at https://v3.11ty.dev/docs/languages/ You are also empowered to implement *any* template language yourself using https://v3.11ty.dev/docs/languages/custom/`, + ); + } + + if (!this.hasEngine(name)) { + throw new Error(`Template Engine ${name} does not exist in getEngine()`); + } + + // TODO these cached engines should be based on extensions not name, then we can remove the error in + // "Double override (not aliases) throws an error" test in TemplateRenderCustomTest.js + if (!this.engineCache[name]) { + debug("Engine cache miss %o (should only happen once per type)", name); + // Make sure cache key is based on name and not path + // Custom class is used for all plugins, cache once per plugin + this.engineCache[name] = this.#getEngine(name, extensionMap); + } + + return this.engineCache[name]; + } +} + +export default TemplateEngineManager; diff --git a/node_modules/@11ty/eleventy/src/Engines/Util/ContextAugmenter.js b/node_modules/@11ty/eleventy/src/Engines/Util/ContextAugmenter.js new file mode 100644 index 0000000..dd5fbc6 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Engines/Util/ContextAugmenter.js @@ -0,0 +1,67 @@ +const DATA_KEYS = ["page", "eleventy"]; + +function augmentFunction(fn, options = {}) { + let t = typeof fn; + if (t !== "function") { + throw new Error( + "Invalid type passed to `augmentFunction`. A function was expected and received: " + t, + ); + } + + /** @this {object} */ + return function (...args) { + let context = augmentObject(this || {}, options); + return fn.call(context, ...args); + }; +} + +function augmentObject(targetObject, options = {}) { + options = Object.assign( + { + source: undefined, // where to copy from + overwrite: true, + lazy: false, // lazily fetch the property + // getter: function() {}, + }, + options, + ); + + for (let key of DATA_KEYS) { + // Skip if overwrite: false and prop already exists on target + if (!options.overwrite && targetObject[key]) { + continue; + } + + if (options.lazy) { + let value; + if (typeof options.getter == "function") { + value = () => options.getter(key, options.source); + } else { + value = () => options.source?.[key]; + } + + // lazy getter important for Liquid strictVariables support + Object.defineProperty(targetObject, key, { + writable: true, + configurable: true, + enumerable: true, + value, + }); + } else { + let value; + if (typeof options.getter == "function") { + value = options.getter(key, options.source); + } else { + value = options.source?.[key]; + } + + if (value) { + targetObject[key] = value; + } + } + } + + return targetObject; +} + +export { DATA_KEYS as augmentKeys, augmentFunction, augmentObject }; diff --git a/node_modules/@11ty/eleventy/src/Errors/DuplicatePermalinkOutputError.js b/node_modules/@11ty/eleventy/src/Errors/DuplicatePermalinkOutputError.js new file mode 100644 index 0000000..444195c --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Errors/DuplicatePermalinkOutputError.js @@ -0,0 +1,9 @@ +import EleventyBaseError from "./EleventyBaseError.js"; + +class DuplicatePermalinkOutputError extends EleventyBaseError { + get removeDuplicateErrorStringFromOutput() { + return true; + } +} + +export default DuplicatePermalinkOutputError; diff --git a/node_modules/@11ty/eleventy/src/Errors/EleventyBaseError.js b/node_modules/@11ty/eleventy/src/Errors/EleventyBaseError.js new file mode 100644 index 0000000..6e76c5f --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Errors/EleventyBaseError.js @@ -0,0 +1,24 @@ +/** + * This class serves as basis for all Eleventy-specific errors. + * @ignore + */ +class EleventyBaseError extends Error { + /** + * @param {string} message - The error message to display. + * @param {unknown} [originalError] - The original error caught. + */ + constructor(message, originalError) { + super(message); + + this.name = this.constructor.name; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + + if (originalError) { + this.originalError = originalError; + } + } +} +export default EleventyBaseError; diff --git a/node_modules/@11ty/eleventy/src/Errors/EleventyErrorHandler.js b/node_modules/@11ty/eleventy/src/Errors/EleventyErrorHandler.js new file mode 100644 index 0000000..c24b1ca --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Errors/EleventyErrorHandler.js @@ -0,0 +1,151 @@ +import util from "node:util"; +import debugUtil from "debug"; + +import ConsoleLogger from "../Util/ConsoleLogger.js"; +import EleventyErrorUtil from "./EleventyErrorUtil.js"; + +const debug = debugUtil("Eleventy:EleventyErrorHandler"); + +class EleventyErrorHandler { + constructor() { + this._isVerbose = true; + } + + get isVerbose() { + return this._isVerbose; + } + + set isVerbose(verbose) { + this._isVerbose = !!verbose; + this.logger.isVerbose = !!verbose; + } + + get logger() { + if (!this._logger) { + this._logger = new ConsoleLogger(); + this._logger.isVerbose = this.isVerbose; + } + + return this._logger; + } + + set logger(logger) { + this._logger = logger; + } + + warn(e, msg) { + if (msg) { + this.initialMessage(msg, "warn", "yellow"); + } + this.log(e, "warn"); + } + + fatal(e, msg) { + this.error(e, msg); + process.exitCode = 1; + } + + once(type, e, msg) { + if (e.__errorAlreadyLogged) { + return; + } + + this[type || "error"](e, msg); + + Object.defineProperty(e, "__errorAlreadyLogged", { + value: true, + }); + } + + error(e, msg) { + if (msg) { + this.initialMessage(msg, "error", "red", true); + } + this.log(e, "error", undefined, true); + } + + static getTotalErrorCount(e) { + let totalErrorCount = 0; + let errorCountRef = e; + while (errorCountRef) { + totalErrorCount++; + errorCountRef = errorCountRef.originalError; + } + return totalErrorCount; + } + + //https://nodejs.org/api/process.html + log(e, type = "log", chalkColor = "", forceToConsole = false) { + if (process.env.DEBUG) { + debug("Full error object: %o", util.inspect(e, { showHidden: false, depth: null })); + } + + let showStack = true; + if (e.skipOriginalStack) { + showStack = false; + } + + let totalErrorCount = EleventyErrorHandler.getTotalErrorCount(e); + let ref = e; + let index = 1; + while (ref) { + let nextRef = ref.originalError; + + // Nunjucks wraps errors and puts the original in error.cause + if (nextRef?.cause?.originalError) { + nextRef = nextRef.cause.originalError; + } + + if (!nextRef && EleventyErrorUtil.hasEmbeddedError(ref.message)) { + nextRef = EleventyErrorUtil.deconvertErrorToObject(ref); + } + + if (nextRef?.skipOriginalStack) { + showStack = false; + } + + this.logger.message( + `${totalErrorCount > 1 ? `${index}. ` : ""}${( + EleventyErrorUtil.cleanMessage(ref.message) || "(No error message provided)" + ).trim()}${ref.name !== "Error" ? ` (via ${ref.name})` : ""}`, + type, + chalkColor, + forceToConsole, + ); + + if (process.env.DEBUG) { + debug(`(${type} stack): ${ref.stack}`); + } else if (!nextRef) { + // last error in the loop + + // remove duplicate error messages if the stack contains the original message output above + let stackStr = ref.stack || ""; + if (e.removeDuplicateErrorStringFromOutput) { + stackStr = stackStr.replace( + `${ref.name}: ${ref.message}`, + "(Repeated output has been truncated…)", + ); + } + + if (showStack) { + this.logger.message( + "\nOriginal error stack trace: " + stackStr, + type, + chalkColor, + forceToConsole, + ); + } + } + ref = nextRef; + index++; + } + } + + initialMessage(message, type = "log", chalkColor = "blue", forceToConsole = false) { + if (message) { + this.logger.message(message + ":", type, chalkColor, forceToConsole); + } + } +} + +export { EleventyErrorHandler }; diff --git a/node_modules/@11ty/eleventy/src/Errors/EleventyErrorUtil.js b/node_modules/@11ty/eleventy/src/Errors/EleventyErrorUtil.js new file mode 100644 index 0000000..c87ea6a --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Errors/EleventyErrorUtil.js @@ -0,0 +1,72 @@ +import TemplateContentPrematureUseError from "./TemplateContentPrematureUseError.js"; + +/* Hack to workaround the variety of error handling schemes in template languages */ +class EleventyErrorUtil { + static get prefix() { + return ">>>>>11ty>>>>>"; + } + static get suffix() { + return "<<<<<11ty<<<<<"; + } + + static hasEmbeddedError(msg) { + if (!msg) { + return false; + } + + return msg.includes(EleventyErrorUtil.prefix) && msg.includes(EleventyErrorUtil.suffix); + } + + static cleanMessage(msg) { + if (!msg) { + return ""; + } + + if (!EleventyErrorUtil.hasEmbeddedError(msg)) { + return "" + msg; + } + + return msg.slice(0, Math.max(0, msg.indexOf(EleventyErrorUtil.prefix))); + } + + static deconvertErrorToObject(error) { + if (!error || !error.message) { + throw new Error(`Could not convert error object from: ${error}`); + } + if (!EleventyErrorUtil.hasEmbeddedError(error.message)) { + return error; + } + + let msg = error.message; + let objectString = msg.substring( + msg.indexOf(EleventyErrorUtil.prefix) + EleventyErrorUtil.prefix.length, + msg.lastIndexOf(EleventyErrorUtil.suffix), + ); + let obj = JSON.parse(objectString); + obj.name = error.name; + return obj; + } + + // pass an error through a random template engine’s error handling unscathed + static convertErrorToString(error) { + return ( + EleventyErrorUtil.prefix + + JSON.stringify({ message: error.message, stack: error.stack }) + + EleventyErrorUtil.suffix + ); + } + + static isPrematureTemplateContentError(e) { + // TODO the rest of the template engines + return ( + e instanceof TemplateContentPrematureUseError || + (e.originalError && + (e.originalError.name === "RenderError" || + e.originalError.name === "UndefinedVariableError") && + e.originalError.originalError instanceof TemplateContentPrematureUseError) || // Liquid + (e.message || "").indexOf("TemplateContentPrematureUseError") > -1 + ); // Nunjucks + } +} + +export default EleventyErrorUtil; diff --git a/node_modules/@11ty/eleventy/src/Errors/TemplateContentPrematureUseError.js b/node_modules/@11ty/eleventy/src/Errors/TemplateContentPrematureUseError.js new file mode 100644 index 0000000..5266cd2 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Errors/TemplateContentPrematureUseError.js @@ -0,0 +1,5 @@ +import EleventyBaseError from "./EleventyBaseError.js"; + +class TemplateContentPrematureUseError extends EleventyBaseError {} + +export default TemplateContentPrematureUseError; diff --git a/node_modules/@11ty/eleventy/src/Errors/TemplateContentUnrenderedTemplateError.js b/node_modules/@11ty/eleventy/src/Errors/TemplateContentUnrenderedTemplateError.js new file mode 100644 index 0000000..ee270d5 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Errors/TemplateContentUnrenderedTemplateError.js @@ -0,0 +1,5 @@ +import EleventyBaseError from "./EleventyBaseError.js"; + +class TemplateContentUnrenderedTemplateError extends EleventyBaseError {} + +export default TemplateContentUnrenderedTemplateError; diff --git a/node_modules/@11ty/eleventy/src/Errors/UsingCircularTemplateContentReferenceError.js b/node_modules/@11ty/eleventy/src/Errors/UsingCircularTemplateContentReferenceError.js new file mode 100644 index 0000000..5608feb --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Errors/UsingCircularTemplateContentReferenceError.js @@ -0,0 +1,5 @@ +import EleventyBaseError from "./EleventyBaseError.js"; + +class UsingCircularTemplateContentReferenceError extends EleventyBaseError {} + +export default UsingCircularTemplateContentReferenceError; diff --git a/node_modules/@11ty/eleventy/src/EventBus.js b/node_modules/@11ty/eleventy/src/EventBus.js new file mode 100644 index 0000000..8846da6 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/EventBus.js @@ -0,0 +1,23 @@ +import debugUtil from "debug"; + +import EventEmitter from "./Util/AsyncEventEmitter.js"; + +const debug = debugUtil("Eleventy:EventBus"); + +/** + * @module 11ty/eleventy/EventBus + * @ignore + */ + +debug("Setting up global EventBus."); +/** + * Provides a global event bus that modules deep down in the stack can + * subscribe to from a global singleton for decoupled pub/sub. + * @type {module:11ty/eleventy/Util/AsyncEventEmitter~AsyncEventEmitter} + */ +let bus = new EventEmitter(); +bus.setMaxListeners(100); + +debug("EventBus max listener count: %o", bus.getMaxListeners()); + +export default bus; diff --git a/node_modules/@11ty/eleventy/src/FileSystemSearch.js b/node_modules/@11ty/eleventy/src/FileSystemSearch.js new file mode 100644 index 0000000..6cccd36 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/FileSystemSearch.js @@ -0,0 +1,102 @@ +import fastglob from "fast-glob"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import { isGlobMatch } from "./Util/GlobMatcher.js"; + +const debug = debugUtil("Eleventy:FastGlobManager"); + +class FileSystemSearch { + constructor() { + this.inputs = {}; + this.outputs = {}; + this.promises = {}; + this.count = 0; + } + + getCacheKey(key, globs, options) { + if (Array.isArray(globs)) { + globs = globs.sort(); + } + return key + JSON.stringify(globs) + JSON.stringify(options); + } + + // returns a promise + search(key, globs, options = {}) { + debug("Glob search (%o) searching for: %o", key, globs); + + if (!Array.isArray(globs)) { + globs = [globs]; + } + + // Strip leading slashes from everything! + globs = globs.map((entry) => TemplatePath.stripLeadingDotSlash(entry)); + + if (options.ignore && Array.isArray(options.ignore)) { + options.ignore = options.ignore.map((entry) => TemplatePath.stripLeadingDotSlash(entry)); + debug("Glob search (%o) ignoring: %o", key, options.ignore); + } + + let cacheKey = this.getCacheKey(key, globs, options); + + // Only after the promise has resolved + if (this.outputs[cacheKey]) { + return Array.from(this.outputs[cacheKey]); + } + + if (!this.promises[cacheKey]) { + this.inputs[cacheKey] = { + input: globs, + options, + }; + + this.count++; + + this.promises[cacheKey] = fastglob( + globs, + Object.assign( + { + caseSensitiveMatch: false, // insensitive + dot: true, + }, + options, + ), + ).then((results) => { + this.outputs[cacheKey] = new Set( + results.map((entry) => TemplatePath.addLeadingDotSlash(entry)), + ); + return Array.from(this.outputs[cacheKey]); + }); + } + + // may be an unresolved promise + return this.promises[cacheKey]; + } + + _modify(path, setOperation) { + path = TemplatePath.stripLeadingDotSlash(path); + + let normalized = TemplatePath.addLeadingDotSlash(path); + + for (let key in this.inputs) { + let { input, options } = this.inputs[key]; + if ( + isGlobMatch(path, input, { + ignore: options.ignore, + }) + ) { + this.outputs[key][setOperation](normalized); + } + } + } + + add(path) { + this._modify(path, "add"); + } + + delete(path) { + this._modify(path, "delete"); + } +} + +export default FileSystemSearch; diff --git a/node_modules/@11ty/eleventy/src/Filters/GetCollectionItem.js b/node_modules/@11ty/eleventy/src/Filters/GetCollectionItem.js new file mode 100644 index 0000000..7512940 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Filters/GetCollectionItem.js @@ -0,0 +1,20 @@ +export default function getCollectionItem(collection, page, modifier = 0) { + let j = 0; + let index; + for (let item of collection) { + if ( + item.inputPath === page.inputPath && + (item.outputPath === page.outputPath || item.url === page.url) + ) { + index = j; + break; + } + j++; + } + + if (index !== undefined && collection?.length) { + if (index + modifier >= 0 && index + modifier < collection.length) { + return collection[index + modifier]; + } + } +} diff --git a/node_modules/@11ty/eleventy/src/Filters/GetCollectionItemIndex.js b/node_modules/@11ty/eleventy/src/Filters/GetCollectionItemIndex.js new file mode 100644 index 0000000..9e12854 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Filters/GetCollectionItemIndex.js @@ -0,0 +1,17 @@ +// TODO locale-friendly, see GetLocaleCollectionItem.js) +export default function getCollectionItemIndex(collection, page) { + if (!page) { + page = this.page; + } + + let j = 0; + for (let item of collection) { + if ( + item.inputPath === page.inputPath && + (item.outputPath === page.outputPath || item.url === page.url) + ) { + return j; + } + j++; + } +} diff --git a/node_modules/@11ty/eleventy/src/Filters/GetLocaleCollectionItem.js b/node_modules/@11ty/eleventy/src/Filters/GetLocaleCollectionItem.js new file mode 100644 index 0000000..1f96622 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Filters/GetLocaleCollectionItem.js @@ -0,0 +1,47 @@ +import getCollectionItem from "./GetCollectionItem.js"; + +// Work with I18n Plugin src/Plugins/I18nPlugin.js to retrieve root pages (not i18n pages) +function resolveRootPage(config, pageOverride, languageCode) { + let localeFilter = config.getFilter("locale_page"); + if (!localeFilter || typeof localeFilter !== "function") { + return pageOverride; + } + + // returns root/default-language `page` object + return localeFilter.call(this, pageOverride, languageCode); +} + +function getLocaleCollectionItem(config, collection, pageOverride, langCode, indexModifier = 0) { + if (!langCode) { + // if page.lang exists (2.0.0-canary.14 and i18n plugin added, use page language) + if (this.page.lang) { + langCode = this.page.lang; + } else { + return getCollectionItem(collection, pageOverride || this.page, indexModifier); + } + } + + let rootPage = resolveRootPage.call(this, config, pageOverride); // implied current page, default language + let modifiedRootItem = getCollectionItem(collection, rootPage, indexModifier); + if (!modifiedRootItem) { + return; // no root item exists for the previous/next page + } + + // Resolve modified root `page` back to locale `page` + // This will return a non localized version of the page as a fallback + let modifiedLocalePage = resolveRootPage.call(this, config, modifiedRootItem.data.page, langCode); + // already localized (or default language) + if (!("__locale_page_resolved" in modifiedLocalePage)) { + return modifiedRootItem; + } + + // find the modified locale `page` again in `collections.all` + let all = + this.collections?.all || + this.ctx?.collections?.all || + this.context?.environments?.collections?.all || + []; + return getCollectionItem(all, modifiedLocalePage, 0); +} + +export default getLocaleCollectionItem; diff --git a/node_modules/@11ty/eleventy/src/Filters/Slug.js b/node_modules/@11ty/eleventy/src/Filters/Slug.js new file mode 100644 index 0000000..03a77cc --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Filters/Slug.js @@ -0,0 +1,14 @@ +import slugify from "slugify"; + +export default function (str, options = {}) { + return slugify( + "" + str, + Object.assign( + { + replacement: "-", + lower: true, + }, + options, + ), + ); +} diff --git a/node_modules/@11ty/eleventy/src/Filters/Slugify.js b/node_modules/@11ty/eleventy/src/Filters/Slugify.js new file mode 100644 index 0000000..e84b42d --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Filters/Slugify.js @@ -0,0 +1,14 @@ +import slugify from "@sindresorhus/slugify"; + +export default function (str, options = {}) { + return slugify( + "" + str, + Object.assign( + { + // lowercase: true, // default + decamelize: false, + }, + options, + ), + ); +} diff --git a/node_modules/@11ty/eleventy/src/Filters/Url.js b/node_modules/@11ty/eleventy/src/Filters/Url.js new file mode 100644 index 0000000..87fc1e2 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Filters/Url.js @@ -0,0 +1,35 @@ +import { TemplatePath } from "@11ty/eleventy-utils"; + +import isValidUrl from "../Util/ValidUrl.js"; + +// Note: This filter is used in the Eleventy Navigation plugin in versions prior to 0.3.4 +export default function (url, pathPrefix) { + // work with undefined + url = url || ""; + + if (isValidUrl(url) || (url.startsWith("//") && url !== "//")) { + return url; + } + + if (pathPrefix === undefined || typeof pathPrefix !== "string") { + // When you retrieve this with config.getFilter("url") it + // grabs the pathPrefix argument from your config for you (see defaultConfig.js) + throw new Error("pathPrefix (String) is required in the `url` filter."); + } + + let normUrl = TemplatePath.normalizeUrlPath(url); + let normRootDir = TemplatePath.normalizeUrlPath("/", pathPrefix); + let normFull = TemplatePath.normalizeUrlPath("/", pathPrefix, url); + let isRootDirTrailingSlash = + normRootDir.length && normRootDir.charAt(normRootDir.length - 1) === "/"; + + // minor difference with straight `normalize`, "" resolves to root dir and not "." + // minor difference with straight `normalize`, "/" resolves to root dir + if (normUrl === "/" || normUrl === normRootDir) { + return normRootDir + (!isRootDirTrailingSlash ? "/" : ""); + } else if (normUrl.indexOf("/") === 0) { + return normFull; + } + + return normUrl; +} diff --git a/node_modules/@11ty/eleventy/src/GlobalDependencyMap.js b/node_modules/@11ty/eleventy/src/GlobalDependencyMap.js new file mode 100644 index 0000000..caeff62 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/GlobalDependencyMap.js @@ -0,0 +1,424 @@ +import { DepGraph } from "dependency-graph"; +import debugUtil from "debug"; +import { TemplatePath } from "@11ty/eleventy-utils"; + +import JavaScriptDependencies from "./Util/JavaScriptDependencies.js"; +import PathNormalizer from "./Util/PathNormalizer.js"; + +const debug = debugUtil("Eleventy:Dependencies"); + +class GlobalDependencyMap { + // dependency-graph requires these keys to be alphabetic strings + static LAYOUT_KEY = "layout"; + static COLLECTION_PREFIX = "__collection:"; + + #templateConfig; + + reset() { + this._map = undefined; + } + + setIsEsm(isEsm) { + this.isEsm = isEsm; + } + + setTemplateConfig(templateConfig) { + this.#templateConfig = templateConfig; + } + + setConfig(config) { + if (this.config) { + return; + } + + this.config = config; + + // These have leading dot slashes, but so do the paths from Eleventy + this.config.events.once("eleventy.layouts", async (layouts) => { + await this.addLayoutsToMap(layouts); + }); + } + + filterOutLayouts(nodes = []) { + return nodes.filter((node) => { + let data = this.map.getNodeData(node); + if (data?.type === GlobalDependencyMap.LAYOUT_KEY) { + return false; + } + return true; + }); + } + + filterOutCollections(nodes = []) { + return nodes.filter((node) => !node.startsWith(GlobalDependencyMap.COLLECTION_PREFIX)); + } + + removeLayoutNodes(normalizedLayouts) { + let nodes = this.map.overallOrder(); + for (let node of nodes) { + let data = this.map.getNodeData(node); + if (!data || !data.type || data.type !== GlobalDependencyMap.LAYOUT_KEY) { + continue; + } + + // previous layout is not in the new layout map (no templates are using it) + if (!normalizedLayouts[node]) { + this.map.removeNode(node); + } + // important: if the layout map changed to have different templates (but was not removed) + // this is already handled by `resetNode` called via TemplateMap + } + } + + // Eleventy Layouts don’t show up in the dependency graph, so we handle those separately + async addLayoutsToMap(layouts) { + let normalizedLayouts = this.normalizeLayoutsObject(layouts); + + // Clear out any previous layout relationships to make way for the new ones + this.removeLayoutNodes(normalizedLayouts); + + for (let layout in normalizedLayouts) { + // We add this pre-emptively to add the `layout` data + if (!this.map.hasNode(layout)) { + this.map.addNode(layout, { + type: GlobalDependencyMap.LAYOUT_KEY, + }); + } else { + this.map.setNodeData(layout, { + type: GlobalDependencyMap.LAYOUT_KEY, + }); + } + + // Potential improvement: only add the first template in the chain for a template and manage any upstream layouts by their own relationships + for (let pageTemplate of normalizedLayouts[layout]) { + this.addDependency(pageTemplate, [layout]); + } + + if (this.#templateConfig?.shouldSpiderJavaScriptDependencies()) { + let deps = await JavaScriptDependencies.getDependencies([layout], this.isEsm); + this.addDependency(layout, deps); + } + } + } + + get map() { + if (!this._map) { + this._map = new DepGraph({ circular: true }); + } + + return this._map; + } + + set map(graph) { + this._map = graph; + } + + normalizeNode(node) { + if (!node) { + return; + } + + // TODO tests for this + // Fix URL objects passed in (sass does this) + if (typeof node !== "string" && "toString" in node) { + node = node.toString(); + } + + if (typeof node !== "string") { + throw new Error("`addDependencies` files must be strings. Received:" + node); + } + + return PathNormalizer.fullNormalization(node); + } + + normalizeLayoutsObject(layouts) { + let o = {}; + for (let rawLayout in layouts) { + let layout = this.normalizeNode(rawLayout); + o[layout] = layouts[rawLayout].map((entry) => this.normalizeNode(entry)); + } + return o; + } + + getDependantsFor(node) { + if (!node) { + return new Set(); + } + + node = this.normalizeNode(node); + + if (!this.map.hasNode(node)) { + return new Set(); + } + + // Direct dependants and dependencies, both publish and consume from collections + return this.map.directDependantsOf(node); + } + + hasNode(node) { + return this.map.hasNode(this.normalizeNode(node)); + } + + findCollectionsRemovedFrom(node, collectionNames) { + if (!this.hasNode(node)) { + return new Set(); + } + + let prevDeps = this.getDependantsFor(node) + .filter((entry) => { + return entry.startsWith(GlobalDependencyMap.COLLECTION_PREFIX); + }) + .map((entry) => { + return GlobalDependencyMap.getEntryFromCollectionKey(entry); + }); + + let prevDepsSet = new Set(prevDeps); + let deleted = new Set(); + for (let dep of prevDepsSet) { + if (!collectionNames.has(dep)) { + deleted.add(dep); + } + } + + return deleted; + } + + resetNode(node) { + node = this.normalizeNode(node); + + if (!this.map.hasNode(node)) { + return; + } + + // We don’t want to remove relationships that consume this, controlled by the upstream content + // for (let dep of this.map.directDependantsOf(node)) { + // this.map.removeDependency(dep, node); + // } + + for (let dep of this.map.directDependenciesOf(node)) { + this.map.removeDependency(node, dep); + } + } + + getTemplatesThatConsumeCollections(collectionNames) { + let templates = new Set(); + for (let name of collectionNames) { + let collectionName = GlobalDependencyMap.getCollectionKeyForEntry(name); + if (!this.map.hasNode(collectionName)) { + continue; + } + for (let node of this.map.dependantsOf(collectionName)) { + if (!node.startsWith(GlobalDependencyMap.COLLECTION_PREFIX)) { + let data = this.map.getNodeData(node); + if (!data || !data.type || data.type != GlobalDependencyMap.LAYOUT_KEY) { + templates.add(node); + } + } + } + } + return templates; + } + + getLayoutsUsedBy(node) { + node = this.normalizeNode(node); + + if (!this.map.hasNode(node)) { + return []; + } + + let layouts = []; + + // include self, if layout + if (this.map.getNodeData(node)?.type === GlobalDependencyMap.LAYOUT_KEY) { + layouts.push(node); + } + + this.map.dependantsOf(node).forEach((node) => { + let data = this.map.getNodeData(node); + // we only want layouts + if (data?.type === GlobalDependencyMap.LAYOUT_KEY) { + return layouts.push(node); + } + }); + + return layouts; + } + + // In order + // Does not include original templatePaths (unless *they* are second-order relevant) + getTemplatesRelevantToTemplateList(templatePaths) { + let overallOrder = this.map.overallOrder(); + overallOrder = this.filterOutLayouts(overallOrder); + overallOrder = this.filterOutCollections(overallOrder); + + let relevantLookup = {}; + for (let inputPath of templatePaths) { + inputPath = TemplatePath.stripLeadingDotSlash(inputPath); + + let deps = this.getDependencies(inputPath, false); + + if (Array.isArray(deps)) { + let paths = this.filterOutCollections(deps); + for (let node of paths) { + relevantLookup[node] = true; + } + } + } + + return overallOrder.filter((node) => { + if (relevantLookup[node]) { + return true; + } + return false; + }); + } + + // Layouts are not relevant to compile cache and can be ignored + getDependencies(node, includeLayouts = true) { + node = this.normalizeNode(node); + + // `false` means the Node was unknown + if (!this.map.hasNode(node)) { + return false; + } + + return this.map.dependenciesOf(node).filter((node) => { + if (includeLayouts) { + return true; + } + + // When includeLayouts is `false` we want to filter out layouts + let data = this.map.getNodeData(node); + if (data?.type === GlobalDependencyMap.LAYOUT_KEY) { + return false; + } + return true; + }); + } + + // node arguments are already normalized + _addDependency(from, toArray = []) { + this.map.addNode(from); + + if (!Array.isArray(toArray)) { + throw new Error("Second argument to `addDependency` must be an Array."); + } + + // debug("%o depends on %o", from, toArray); + + for (let to of toArray) { + if (!this.map.hasNode(to)) { + this.map.addNode(to); + } + if (from !== to) { + this.map.addDependency(from, to); + } + } + } + + addDependency(from, toArray = []) { + this._addDependency( + this.normalizeNode(from), + toArray.map((to) => this.normalizeNode(to)), + ); + } + + static getEntryFromCollectionKey(entry) { + return entry.slice(GlobalDependencyMap.COLLECTION_PREFIX.length); + } + + static getCollectionKeyForEntry(entry) { + return `${GlobalDependencyMap.COLLECTION_PREFIX}${entry}`; + } + + addDependencyConsumesCollection(from, collectionName) { + let nodeName = this.normalizeNode(from); + debug("%o depends on collection: %o", nodeName, collectionName); + this._addDependency(nodeName, [GlobalDependencyMap.getCollectionKeyForEntry(collectionName)]); + } + + addDependencyPublishesToCollection(from, collectionName) { + let normalizedFrom = this.normalizeNode(from); + this._addDependency(GlobalDependencyMap.getCollectionKeyForEntry(collectionName), [ + normalizedFrom, + ]); + } + + // Layouts are not relevant to compile cache and can be ignored + hasDependency(from, to, includeLayouts) { + to = this.normalizeNode(to); + + let deps = this.getDependencies(from, includeLayouts); // normalizes `from` + + if (!deps) { + return false; + } + + return deps.includes(to); + } + + // Layouts are not relevant to compile cache and can be ignored + isFileRelevantTo(fullTemplateInputPath, comparisonFile, includeLayouts) { + fullTemplateInputPath = this.normalizeNode(fullTemplateInputPath); + comparisonFile = this.normalizeNode(comparisonFile); + + // No watch/serve changed file + if (!comparisonFile) { + return false; + } + + // The file that changed is the relevant file + if (fullTemplateInputPath === comparisonFile) { + return true; + } + + // The file that changed is a dependency of the template + // comparisonFile is used by fullTemplateInputPath + if (this.hasDependency(fullTemplateInputPath, comparisonFile, includeLayouts)) { + return true; + } + + return false; + } + + isFileUsedBy(parent, child, includeLayouts) { + if (this.hasDependency(parent, child, includeLayouts)) { + // child is used by parent + return true; + } + return false; + } + + stringify() { + return JSON.stringify(this.map, function replacer(key, value) { + // Serialize internal Map objects. + if (value instanceof Map) { + let obj = {}; + for (let [k, v] of value) { + obj[k] = v; + } + return obj; + } + + return value; + }); + } + + restore(persisted) { + let obj = JSON.parse(persisted); + let graph = new DepGraph({ circular: true }); + + // https://github.com/jriecken/dependency-graph/issues/44 + // Restore top level serialized Map objects (in stringify above) + for (let key in obj) { + let map = graph[key]; + for (let k in obj[key]) { + let v = obj[key][k]; + map.set(k, v); + } + } + this.map = graph; + } +} + +export default GlobalDependencyMap; diff --git a/node_modules/@11ty/eleventy/src/Plugins/HtmlBasePlugin.js b/node_modules/@11ty/eleventy/src/Plugins/HtmlBasePlugin.js new file mode 100644 index 0000000..bed8d49 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Plugins/HtmlBasePlugin.js @@ -0,0 +1,151 @@ +import { DeepCopy } from "@11ty/eleventy-utils"; +import urlFilter from "../Filters/Url.js"; +import PathPrefixer from "../Util/PathPrefixer.js"; +import { HtmlTransformer } from "../Util/HtmlTransformer.js"; +import isValidUrl from "../Util/ValidUrl.js"; + +function addPathPrefixToUrl(url, pathPrefix, base) { + let u; + if (base) { + u = new URL(url, base); + } else { + u = new URL(url); + } + + // Add pathPrefix **after** url is transformed using base + if (pathPrefix) { + u.pathname = PathPrefixer.joinUrlParts(pathPrefix, u.pathname); + } + return u.toString(); +} + +// pathprefix is only used when overrideBase is a full URL +function transformUrl(url, base, opts = {}) { + let { pathPrefix, pageUrl } = opts; + + // full URL, return as-is + if (isValidUrl(url)) { + return url; + } + + // Not a full URL, but with a full base URL + // e.g. relative urls like "subdir/", "../subdir", "./subdir" + if (isValidUrl(base)) { + // convert relative paths to absolute path first using pageUrl + if (pageUrl && !url.startsWith("/")) { + let urlObj = new URL(url, `http://example.com${pageUrl}`); + url = urlObj.pathname + (urlObj.hash || ""); + } + + return addPathPrefixToUrl(url, pathPrefix, base); + } + + // Not a full URL, nor a full base URL (call the built-in `url` filter) + return urlFilter(url, base); +} + +function eleventyHtmlBasePlugin(eleventyConfig, defaultOptions = {}) { + let opts = DeepCopy( + { + // eleventyConfig.pathPrefix is new in Eleventy 2.0.0-canary.15 + // `base` can be a directory (for path prefix transformations) + // OR a full URL with origin and pathname + baseHref: eleventyConfig.pathPrefix, + + extensions: "html", + }, + defaultOptions, + ); + + // `filters` option to rename filters was removed in 3.0.0-alpha.13 + // Renaming these would cause issues in other plugins (e.g. RSS) + if (opts.filters !== undefined) { + throw new Error( + "The `filters` option in the HTML Base plugin was removed to prevent future cross-plugin compatibility issues.", + ); + } + + if (opts.baseHref === undefined) { + throw new Error("The `base` option is required in the HTML Base plugin."); + } + + eleventyConfig.addFilter("addPathPrefixToFullUrl", function (url) { + return addPathPrefixToUrl(url, eleventyConfig.pathPrefix); + }); + + // Apply to one URL + eleventyConfig.addFilter( + "htmlBaseUrl", + + /** @this {object} */ + function (url, baseOverride, pageUrlOverride) { + let base = baseOverride || opts.baseHref; + + // Do nothing with a default base + if (base === "/") { + return url; + } + + return transformUrl(url, base, { + pathPrefix: eleventyConfig.pathPrefix, + pageUrl: pageUrlOverride || this.page?.url, + }); + }, + ); + + // Apply to a block of HTML + eleventyConfig.addAsyncFilter( + "transformWithHtmlBase", + + /** @this {object} */ + function (content, baseOverride, pageUrlOverride) { + let base = baseOverride || opts.baseHref; + + // Do nothing with a default base + if (base === "/") { + return content; + } + + return HtmlTransformer.transformStandalone(content, (url) => { + return transformUrl(url.trim(), base, { + pathPrefix: eleventyConfig.pathPrefix, + pageUrl: pageUrlOverride || this.page?.url, + }); + }); + }, + ); + + // Apply to all HTML output in your project + eleventyConfig.htmlTransformer.addUrlTransform( + opts.extensions, + + /** @this {object} */ + function (urlInMarkup) { + // baseHref override is via renderTransforms filter for adding the absolute URL (e.g. https://example.com/pathPrefix/) for RSS/Atom/JSON feeds + return transformUrl(urlInMarkup.trim(), this.baseHref || opts.baseHref, { + pathPrefix: eleventyConfig.pathPrefix, + pageUrl: this.url, + }); + }, + { + priority: -1, // run last (especially after PathToUrl transform) + enabled: function (context) { + // Enabled when pathPrefix is non-default or via renderTransforms + return context.baseHref || opts.baseHref !== "/"; + }, + }, + ); +} + +Object.defineProperty(eleventyHtmlBasePlugin, "eleventyPackage", { + value: "@11ty/eleventy/html-base-plugin", +}); + +Object.defineProperty(eleventyHtmlBasePlugin, "eleventyPluginOptions", { + value: { + unique: true, + }, +}); + +export default eleventyHtmlBasePlugin; +export { transformUrl as applyBaseToUrl }; diff --git a/node_modules/@11ty/eleventy/src/Plugins/I18nPlugin.js b/node_modules/@11ty/eleventy/src/Plugins/I18nPlugin.js new file mode 100644 index 0000000..6f53825 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Plugins/I18nPlugin.js @@ -0,0 +1,317 @@ +import { bcp47Normalize } from "bcp-47-normalize"; +import iso639 from "iso-639-1"; +import { DeepCopy } from "@11ty/eleventy-utils"; + +// pathPrefix note: +// When using `locale_url` filter with the `url` filter, `locale_url` must run first like +// `| locale_url | url`. If you run `| url | locale_url` it won’t match correctly. + +// TODO improvement would be to throw an error if `locale_url` finds a url with the +// path prefix at the beginning? Would need a better way to know `url` has transformed a string +// rather than just raw comparison. +// e.g. --pathprefix=/en/ should return `/en/en/` for `/en/index.liquid` + +class LangUtils { + static getLanguageCodeFromInputPath(filepath) { + return (filepath || "").split("/").find((entry) => Comparator.isLangCode(entry)); + } + + static getLanguageCodeFromUrl(url) { + let s = (url || "").split("/"); + return s.length > 0 && Comparator.isLangCode(s[1]) ? s[1] : ""; + } + + static swapLanguageCodeNoCheck(str, langCode) { + let found = false; + return str + .split("/") + .map((entry) => { + // only match the first one + if (!found && Comparator.isLangCode(entry)) { + found = true; + return langCode; + } + return entry; + }) + .join("/"); + } + + static swapLanguageCode(str, langCode) { + if (!Comparator.isLangCode(langCode)) { + return str; + } + + return LangUtils.swapLanguageCodeNoCheck(str, langCode); + } +} + +class Comparator { + // https://en.wikipedia.org/wiki/IETF_language_tag#Relation_to_other_standards + // Requires a ISO-639-1 language code at the start (2 characters before the first -) + static isLangCode(code) { + let [s] = (code || "").split("-"); + if (!iso639.validate(s)) { + return false; + } + if (!bcp47Normalize(code)) { + return false; + } + return true; + } + + static urlHasLangCode(url, code) { + if (!Comparator.isLangCode(code)) { + return false; + } + + return url.split("/").some((entry) => entry === code); + } +} + +function normalizeInputPath(inputPath, extensionMap) { + if (extensionMap) { + return extensionMap.removeTemplateExtension(inputPath); + } + return inputPath; +} + +/* + * Input: { + * '/en-us/test/': './test/stubs-i18n/en-us/test.11ty.js', + * '/en/test/': './test/stubs-i18n/en/test.liquid', + * '/es/test/': './test/stubs-i18n/es/test.njk', + * '/non-lang-file/': './test/stubs-i18n/non-lang-file.njk' + * } + * + * Output: { + * '/en-us/test/': [ { url: '/en/test/' }, { url: '/es/test/' } ], + * '/en/test/': [ { url: '/en-us/test/' }, { url: '/es/test/' } ], + * '/es/test/': [ { url: '/en-us/test/' }, { url: '/en/test/' } ] + * } + */ +function getLocaleUrlsMap(urlToInputPath, extensionMap, options = {}) { + let filemap = {}; + + for (let url in urlToInputPath) { + // Group number comes from Pagination.js + let { inputPath: originalFilepath, groupNumber } = urlToInputPath[url]; + let filepath = normalizeInputPath(originalFilepath, extensionMap); + let replaced = + LangUtils.swapLanguageCodeNoCheck(filepath, "__11ty_i18n") + `_group:${groupNumber}`; + + if (!filemap[replaced]) { + filemap[replaced] = []; + } + + let langCode = LangUtils.getLanguageCodeFromInputPath(originalFilepath); + if (!langCode) { + langCode = LangUtils.getLanguageCodeFromUrl(url); + } + if (!langCode) { + langCode = options.defaultLanguage; + } + + if (langCode) { + filemap[replaced].push({ + url, + lang: langCode, + label: iso639.getNativeName(langCode.split("-")[0]), + }); + } else { + filemap[replaced].push({ url }); + } + } + + // Default sorted by lang code + for (let key in filemap) { + filemap[key].sort(function (a, b) { + if (a.lang < b.lang) { + return -1; + } + if (a.lang > b.lang) { + return 1; + } + return 0; + }); + } + + // map of input paths => array of localized urls + let urlMap = {}; + for (let filepath in filemap) { + for (let entry of filemap[filepath]) { + let url = entry.url; + if (!urlMap[url]) { + urlMap[url] = filemap[filepath].filter((entry) => { + if (entry.lang) { + return true; + } + return entry.url !== url; + }); + } + } + } + + return urlMap; +} + +function eleventyI18nPlugin(eleventyConfig, opts = {}) { + let options = DeepCopy( + { + defaultLanguage: "", + filters: { + url: "locale_url", + links: "locale_links", + }, + errorMode: "strict", // allow-fallback, never + }, + opts, + ); + + if (!options.defaultLanguage) { + throw new Error( + "You must specify a `defaultLanguage` in Eleventy’s Internationalization (I18N) plugin.", + ); + } + + let extensionMap; + eleventyConfig.on("eleventy.extensionmap", (map) => { + extensionMap = map; + }); + + let bench = eleventyConfig.benchmarkManager.get("Aggregate"); + let contentMaps = {}; + eleventyConfig.on("eleventy.contentMap", function ({ urlToInputPath, inputPathToUrl }) { + let b = bench.get("(i18n Plugin) Setting up content map."); + b.before(); + contentMaps.inputPathToUrl = inputPathToUrl; + contentMaps.urlToInputPath = urlToInputPath; + + contentMaps.localeUrlsMap = getLocaleUrlsMap(urlToInputPath, extensionMap, options); + b.after(); + }); + + eleventyConfig.addGlobalData("eleventyComputed.page.lang", () => { + // if addGlobalData receives a function it will execute it immediately, + // so we return a nested function for computed data + return (data) => { + return LangUtils.getLanguageCodeFromUrl(data.page.url) || options.defaultLanguage; + }; + }); + + // Normalize a theoretical URL based on the current page’s language + // If a non-localized file exists, returns the URL without a language assigned + // Fails if no file exists (localized and not localized) + eleventyConfig.addFilter(options.filters.url, function (url, langCodeOverride) { + let langCode = + langCodeOverride || + LangUtils.getLanguageCodeFromUrl(this.page?.url) || + options.defaultLanguage; + + // Already has a language code on it and has a relevant url with the target language code + if ( + contentMaps.localeUrlsMap[url] || + (!url.endsWith("/") && contentMaps.localeUrlsMap[`${url}/`]) + ) { + for (let existingUrlObj of contentMaps.localeUrlsMap[url] || + contentMaps.localeUrlsMap[`${url}/`]) { + if (Comparator.urlHasLangCode(existingUrlObj.url, langCode)) { + return existingUrlObj.url; + } + } + } + + // Needs the language code prepended to the URL + let prependedLangCodeUrl = `/${langCode}${url}`; + if ( + contentMaps.localeUrlsMap[prependedLangCodeUrl] || + (!prependedLangCodeUrl.endsWith("/") && contentMaps.localeUrlsMap[`${prependedLangCodeUrl}/`]) + ) { + return prependedLangCodeUrl; + } + + if ( + contentMaps.urlToInputPath[url] || + (!url.endsWith("/") && contentMaps.urlToInputPath[`${url}/`]) + ) { + // this is not a localized file (independent of a language code) + if (options.errorMode === "strict") { + throw new Error( + `Localized file for URL ${prependedLangCodeUrl} was not found in your project. A non-localized version does exist—are you sure you meant to use the \`${options.filters.url}\` filter for this? You can bypass this error using the \`errorMode\` option in the I18N plugin (current value: "${options.errorMode}").`, + ); + } + } else if (options.errorMode === "allow-fallback") { + // You’re linking to a localized file that doesn’t exist! + throw new Error( + `Localized file for URL ${prependedLangCodeUrl} was not found in your project! You will need to add it if you want to link to it using the \`${options.filters.url}\` filter. You can bypass this error using the \`errorMode\` option in the I18N plugin (current value: "${options.errorMode}").`, + ); + } + + return url; + }); + + // Refactor to use url + // Find the links that are localized alternates to the inputPath argument + eleventyConfig.addFilter(options.filters.links, function (urlOverride) { + let url = urlOverride || this.page?.url; + return (contentMaps.localeUrlsMap[url] || []).filter((entry) => { + return entry.url !== url; + }); + }); + + // Returns a `page`-esque variable for the root default language page + // If paginated, returns first result only + eleventyConfig.addFilter( + "locale_page", // This is not exposed in `options` because it is an Eleventy internals filter (used in get*CollectionItem filters) + function (pageOverride, languageCode) { + // both args here are optional + if (!languageCode) { + languageCode = options.defaultLanguage; + } + + let page = pageOverride || this.page; + let url; // new url + if (contentMaps.localeUrlsMap[page.url]) { + for (let entry of contentMaps.localeUrlsMap[page.url]) { + if (entry.lang === languageCode) { + url = entry.url; + } + } + } + + let inputPath = LangUtils.swapLanguageCode(page.inputPath, languageCode); + + if ( + !url || + !Array.isArray(contentMaps.inputPathToUrl[inputPath]) || + contentMaps.inputPathToUrl[inputPath].length === 0 + ) { + // no internationalized pages found + return page; + } + + let result = { + // // note that the permalink/slug may be different for the localized file! + url, + inputPath, + filePathStem: LangUtils.swapLanguageCode(page.filePathStem, languageCode), + // outputPath is omitted here, not necessary for GetCollectionItem.js if url is provided + __locale_page_resolved: true, + }; + return result; + }, + ); +} + +export { Comparator, LangUtils }; + +Object.defineProperty(eleventyI18nPlugin, "eleventyPackage", { + value: "@11ty/eleventy/i18n-plugin", +}); + +Object.defineProperty(eleventyI18nPlugin, "eleventyPluginOptions", { + value: { + unique: true, + }, +}); + +export default eleventyI18nPlugin; diff --git a/node_modules/@11ty/eleventy/src/Plugins/IdAttributePlugin.js b/node_modules/@11ty/eleventy/src/Plugins/IdAttributePlugin.js new file mode 100644 index 0000000..3fe7438 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Plugins/IdAttributePlugin.js @@ -0,0 +1,103 @@ +import matchHelper from "posthtml-match-helper"; +import { decodeHTML } from "entities"; + +import slugifyFilter from "../Filters/Slugify.js"; +import MemoizeUtil from "../Util/MemoizeFunction.js"; + +function getTextNodeContent(node) { + if (node.attrs?.["eleventy:id-ignore"] === "") { + delete node.attrs["eleventy:id-ignore"]; + return ""; + } + if (!node.content) { + return ""; + } + + return node.content + .map((entry) => { + if (typeof entry === "string") { + return entry; + } + if (Array.isArray(entry.content)) { + return getTextNodeContent(entry); + } + return ""; + }) + .join(""); +} + +function IdAttributePlugin(eleventyConfig, options = {}) { + if (!options.slugify) { + options.slugify = MemoizeUtil(slugifyFilter); + } + if (!options.selector) { + options.selector = "[id],h1,h2,h3,h4,h5,h6"; + } + options.decodeEntities = options.decodeEntities ?? true; + options.checkDuplicates = options.checkDuplicates ?? "error"; + + eleventyConfig.htmlTransformer.addPosthtmlPlugin( + "html", + function (pluginOptions = {}) { + if (typeof options.filter === "function") { + if (options.filter(pluginOptions) === false) { + return function () {}; + } + } + + return function (tree) { + // One per page + let conflictCheck = {}; + // Cache heading nodes for conflict resolution + let headingNodes = {}; + + tree.match(matchHelper(options.selector), function (node) { + if (node.attrs?.id) { + let id = node.attrs?.id; + if (conflictCheck[id]) { + conflictCheck[id]++; + if (headingNodes[id]) { + // Rename conflicting assigned heading id + let newId = `${id}-${conflictCheck[id]}`; + headingNodes[newId] = headingNodes[id]; + headingNodes[newId].attrs.id = newId; + delete headingNodes[id]; + } else if (options.checkDuplicates === "error") { + // Existing `id` conflicts with assigned heading id, throw error + throw new Error( + "Duplicate `id` attribute (" + + id + + ") in markup on " + + pluginOptions.page.inputPath, + ); + } + } else { + conflictCheck[id] = 1; + } + } else if (!node.attrs?.id && node.content) { + node.attrs = node.attrs || {}; + let textContent = getTextNodeContent(node); + if (options.decodeEntities) { + textContent = decodeHTML(textContent); + } + let id = options.slugify(textContent); + + if (conflictCheck[id]) { + conflictCheck[id]++; + id = `${id}-${conflictCheck[id]}`; + } else { + conflictCheck[id] = 1; + } + + headingNodes[id] = node; + node.attrs.id = id; + } + + return node; + }); + }; + } /* , {} // pluginOptions */, + ); +} + +export { IdAttributePlugin }; diff --git a/node_modules/@11ty/eleventy/src/Plugins/InputPathToUrl.js b/node_modules/@11ty/eleventy/src/Plugins/InputPathToUrl.js new file mode 100644 index 0000000..ddc60ed --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Plugins/InputPathToUrl.js @@ -0,0 +1,177 @@ +import path from "node:path"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import isValidUrl from "../Util/ValidUrl.js"; + +function getValidPath(contentMap, testPath) { + let normalized = TemplatePath.addLeadingDotSlash(testPath); + + // it must exist in the content map to be valid + if (contentMap[normalized]) { + return normalized; + } +} + +function normalizeInputPath(targetInputPath, inputDir, sourceInputPath, contentMap) { + // inputDir is optional at the beginning of the developer supplied-path + + // Input directory already on the input path + if (TemplatePath.join(targetInputPath).startsWith(TemplatePath.join(inputDir))) { + let absolutePath = getValidPath(contentMap, targetInputPath); + if (absolutePath) { + return absolutePath; + } + } + + // Relative to project input directory + let relativeToInputDir = getValidPath(contentMap, TemplatePath.join(inputDir, targetInputPath)); + if (relativeToInputDir) { + return relativeToInputDir; + } + + if (targetInputPath && !path.isAbsolute(targetInputPath)) { + // Relative to source file’s input path + let sourceInputDir = TemplatePath.getDirFromFilePath(sourceInputPath); + let relativeToSourceFile = getValidPath( + contentMap, + TemplatePath.join(sourceInputDir, targetInputPath), + ); + if (relativeToSourceFile) { + return relativeToSourceFile; + } + } + + // the transform may have sent in a URL so we just return it as-is + return targetInputPath; +} + +function parseFilePath(filepath) { + try { + /* u: URL { + href: 'file:///tmpl.njk#anchor', + origin: 'null', + protocol: 'file:', + username: '', + password: '', + host: '', + hostname: '', + port: '', + pathname: '/tmpl.njk', + search: '', + searchParams: URLSearchParams {}, + hash: '#anchor' + } */ + + // Note that `node:url` -> pathToFileURL creates an absolute path, which we don’t want + // URL(`file:#anchor`) gives back a pathname of `/` + let u = new URL(`file:${filepath}`); + filepath = filepath.replace(u.search, ""); + filepath = filepath.replace(u.hash, ""); + + return [ + // search includes ?, hash includes # + u.search + u.hash, + filepath, + ]; + } catch (e) { + return ["", filepath]; + } +} + +function FilterPlugin(eleventyConfig) { + let contentMap; + eleventyConfig.on("eleventy.contentMap", function ({ inputPathToUrl }) { + contentMap = inputPathToUrl; + }); + + eleventyConfig.addFilter("inputPathToUrl", function (targetFilePath) { + if (!contentMap) { + throw new Error("Internal error: contentMap not available for `inputPathToUrl` filter."); + } + + if (isValidUrl(targetFilePath)) { + return targetFilePath; + } + + let inputDir = eleventyConfig.directories.input; + let suffix = ""; + [suffix, targetFilePath] = parseFilePath(targetFilePath); + // @ts-ignore + targetFilePath = normalizeInputPath(targetFilePath, inputDir, this.page.inputPath, contentMap); + + let urls = contentMap[targetFilePath]; + if (!urls || urls.length === 0) { + throw new Error( + "`inputPathToUrl` filter could not find a matching target for " + targetFilePath, + ); + } + + return `${urls[0]}${suffix}`; + }); +} + +function TransformPlugin(eleventyConfig, defaultOptions = {}) { + let opts = Object.assign( + { + extensions: "html", + }, + defaultOptions, + ); + + let contentMap = null; + eleventyConfig.on("eleventy.contentMap", function ({ inputPathToUrl }) { + contentMap = inputPathToUrl; + }); + + eleventyConfig.htmlTransformer.addUrlTransform(opts.extensions, function (targetFilepathOrUrl) { + if (!contentMap) { + throw new Error("Internal error: contentMap not available for the `pathToUrl` Transform."); + } + if (isValidUrl(targetFilepathOrUrl)) { + return targetFilepathOrUrl; + } + + let inputDir = eleventyConfig.directories.input; + + let suffix = ""; + [suffix, targetFilepathOrUrl] = parseFilePath(targetFilepathOrUrl); + targetFilepathOrUrl = normalizeInputPath( + targetFilepathOrUrl, + inputDir, + // @ts-ignore + this.page.inputPath, + contentMap, + ); + + let urls = contentMap[targetFilepathOrUrl]; + if (!targetFilepathOrUrl || !urls || urls.length === 0) { + // fallback, transforms don’t error on missing paths (though the pathToUrl filter does) + return `${targetFilepathOrUrl}${suffix}`; + } + + return `${urls[0]}${suffix}`; + }); +} + +Object.defineProperty(FilterPlugin, "eleventyPackage", { + value: "@11ty/eleventy/inputpath-to-url-filter-plugin", +}); + +Object.defineProperty(FilterPlugin, "eleventyPluginOptions", { + value: { + unique: true, + }, +}); + +Object.defineProperty(TransformPlugin, "eleventyPackage", { + value: "@11ty/eleventy/inputpath-to-url-transform-plugin", +}); + +Object.defineProperty(TransformPlugin, "eleventyPluginOptions", { + value: { + unique: true, + }, +}); + +export default TransformPlugin; + +export { FilterPlugin, TransformPlugin }; diff --git a/node_modules/@11ty/eleventy/src/Plugins/Pagination.js b/node_modules/@11ty/eleventy/src/Plugins/Pagination.js new file mode 100755 index 0000000..bf8d865 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Plugins/Pagination.js @@ -0,0 +1,380 @@ +import { isPlainObject } from "@11ty/eleventy-utils"; +import lodash from "@11ty/lodash-custom"; +import { DeepCopy } from "@11ty/eleventy-utils"; + +import EleventyBaseError from "../Errors/EleventyBaseError.js"; +import { ProxyWrap } from "../Util/Objects/ProxyWrap.js"; +// import { DeepFreeze } from "../Util/Objects/DeepFreeze.js"; +import TemplateData from "../Data/TemplateData.js"; + +const { set: lodashSet, get: lodashGet, chunk: lodashChunk } = lodash; + +class PaginationConfigError extends EleventyBaseError {} +class PaginationError extends EleventyBaseError {} + +class Pagination { + constructor(tmpl, data, config) { + if (!config) { + throw new PaginationConfigError("Expected `config` argument to Pagination class."); + } + + this.config = config; + + this.setTemplate(tmpl); + this.setData(data); + } + + get inputPathForErrorMessages() { + if (this.template) { + return ` (${this.template.inputPath})`; + } + return ""; + } + + static hasPagination(data) { + return "pagination" in data; + } + + hasPagination() { + if (!this.data) { + throw new Error( + `Missing \`setData\` call for Pagination object${this.inputPathForErrorMessages}`, + ); + } + return Pagination.hasPagination(this.data); + } + + circularReferenceCheck(data) { + let key = data.pagination.data; + let includedTags = TemplateData.getIncludedTagNames(data); + + for (let tag of includedTags) { + if (`collections.${tag}` === key) { + throw new PaginationError( + `Pagination circular reference${this.inputPathForErrorMessages}, data:\`${key}\` iterates over both the \`${tag}\` collection and also supplies pages to that collection.`, + ); + } + } + } + + setData(data) { + this.data = data || {}; + this.target = []; + + if (!this.hasPagination()) { + return; + } + + if (!data.pagination) { + throw new Error( + `Misconfigured pagination data in template front matter${this.inputPathForErrorMessages} (YAML front matter precaution: did you use tabs and not spaces for indentation?).`, + ); + } else if (!("size" in data.pagination)) { + throw new Error( + `Missing pagination size in front matter data${this.inputPathForErrorMessages}`, + ); + } + this.circularReferenceCheck(data); + + this.size = data.pagination.size; + this.alias = data.pagination.alias; + this.fullDataSet = this._get(this.data, this._getDataKey()); + // this returns an array + this.target = this._resolveItems(); + this.chunkedItems = this.pagedItems; + } + + setTemplate(tmpl) { + this.template = tmpl; + } + + _getDataKey() { + return this.data.pagination.data; + } + + shouldResolveDataToObjectValues() { + if ("resolve" in this.data.pagination) { + return this.data.pagination.resolve === "values"; + } + return false; + } + + isFiltered(value) { + if ("filter" in this.data.pagination) { + let filtered = this.data.pagination.filter; + if (Array.isArray(filtered)) { + return filtered.indexOf(value) > -1; + } + + return filtered === value; + } + + return false; + } + + _has(target, key) { + let notFoundValue = "__NOT_FOUND_ERROR__"; + let data = lodashGet(target, key, notFoundValue); + return data !== notFoundValue; + } + + _get(target, key) { + let notFoundValue = "__NOT_FOUND_ERROR__"; + let data = lodashGet(target, key, notFoundValue); + if (data === notFoundValue) { + throw new Error( + `Could not find pagination data${this.inputPathForErrorMessages}, went looking for: ${key}`, + ); + } + return data; + } + + _resolveItems() { + let keys; + if (Array.isArray(this.fullDataSet)) { + keys = this.fullDataSet; + this.paginationTargetType = "array"; + } else if (isPlainObject(this.fullDataSet)) { + this.paginationTargetType = "object"; + if (this.shouldResolveDataToObjectValues()) { + keys = Object.values(this.fullDataSet); + } else { + keys = Object.keys(this.fullDataSet); + } + } else { + throw new Error( + `Unexpected data found in pagination target${this.inputPathForErrorMessages}: expected an Array or an Object.`, + ); + } + + // keys must be an array + let result = keys.slice(); + + if (this.data.pagination.before && typeof this.data.pagination.before === "function") { + // we don’t need to make a copy of this because we .slice() above to create a new copy + let fns = {}; + if (this.config) { + fns = this.config.javascriptFunctions; + } + result = this.data.pagination.before.call(fns, result, this.data); + } + + if (this.data.pagination.reverse === true) { + result = result.reverse(); + } + + if (this.data.pagination.filter) { + result = result.filter((value) => !this.isFiltered(value)); + } + + return result; + } + + get pagedItems() { + if (!this.data) { + throw new Error( + `Missing \`setData\` call for Pagination object${this.inputPathForErrorMessages}`, + ); + } + + const chunks = lodashChunk(this.target, this.size); + if (this.data.pagination?.generatePageOnEmptyData) { + return chunks.length ? chunks : [[]]; + } else { + return chunks; + } + } + + getPageCount() { + if (!this.hasPagination()) { + return 0; + } + + return this.chunkedItems.length; + } + + getNormalizedItems(pageItems) { + return this.size === 1 ? pageItems[0] : pageItems; + } + + getOverrideDataPages(items, pageNumber) { + return { + // See Issue #345 for more examples + page: { + previous: pageNumber > 0 ? this.getNormalizedItems(items[pageNumber - 1]) : null, + next: pageNumber < items.length - 1 ? this.getNormalizedItems(items[pageNumber + 1]) : null, + first: items.length ? this.getNormalizedItems(items[0]) : null, + last: items.length ? this.getNormalizedItems(items[items.length - 1]) : null, + }, + + pageNumber, + }; + } + + getOverrideDataLinks(pageNumber, templateCount, links) { + let obj = {}; + + // links are okay but hrefs are better + obj.previousPageLink = pageNumber > 0 ? links[pageNumber - 1] : null; + obj.previous = obj.previousPageLink; + + obj.nextPageLink = pageNumber < templateCount - 1 ? links[pageNumber + 1] : null; + obj.next = obj.nextPageLink; + + obj.firstPageLink = links.length > 0 ? links[0] : null; + obj.lastPageLink = links.length > 0 ? links[links.length - 1] : null; + + obj.links = links; + // todo deprecated, consistency with collections and use links instead + obj.pageLinks = links; + return obj; + } + + getOverrideDataHrefs(pageNumber, templateCount, hrefs) { + let obj = {}; + + // hrefs are better than links + obj.previousPageHref = pageNumber > 0 ? hrefs[pageNumber - 1] : null; + obj.nextPageHref = pageNumber < templateCount - 1 ? hrefs[pageNumber + 1] : null; + + obj.firstPageHref = hrefs.length > 0 ? hrefs[0] : null; + obj.lastPageHref = hrefs.length > 0 ? hrefs[hrefs.length - 1] : null; + + obj.hrefs = hrefs; + + // better names + obj.href = { + previous: obj.previousPageHref, + next: obj.nextPageHref, + first: obj.firstPageHref, + last: obj.lastPageHref, + }; + + return obj; + } + + async getPageTemplates() { + if (!this.data) { + throw new Error( + `Missing \`setData\` call for Pagination object${this.inputPathForErrorMessages}`, + ); + } + + if (!this.hasPagination()) { + return []; + } + + let entries = []; + let items = this.chunkedItems; + let pages = this.size === 1 ? items.map((entry) => entry[0]) : items; + + let links = []; + let hrefs = []; + + let hasPermalinkField = Boolean(this.data[this.config.keys.permalink]); + let hasComputedPermalinkField = Boolean( + this.data.eleventyComputed && this.data.eleventyComputed[this.config.keys.permalink], + ); + + // Do *not* pass collections through DeepCopy, we’ll re-add them back in later. + let collections = this.data.collections; + if (collections) { + delete this.data.collections; + } + + let parentData = DeepCopy( + { + pagination: { + data: this.data.pagination.data, + size: this.data.pagination.size, + alias: this.alias, + pages, + }, + }, + this.data, + ); + + // Restore skipped collections + if (collections) { + this.data.collections = collections; + // Keep the original reference to the collections, no deep copy!! + parentData.collections = collections; + } + + // TODO this does work fine but let’s wait on enabling it. + // DeepFreeze(parentData, ["collections"]); + + // TODO future improvement dea: use a light Template wrapper for paged template clones (PagedTemplate?) + // so that we don’t have the memory cost of the full template (and can reuse the parent + // template for some things) + + let indices = new Set(); + for (let j = 0; j <= items.length - 1; j++) { + indices.add(j); + } + + for (let pageNumber of indices) { + let cloned = await this.template.clone(); + + if (pageNumber > 0 && !hasPermalinkField && !hasComputedPermalinkField) { + cloned.setExtraOutputSubdirectory(pageNumber); + } + + let paginationData = { + pagination: { + items: items[pageNumber], + }, + page: {}, + }; + Object.assign(paginationData.pagination, this.getOverrideDataPages(items, pageNumber)); + + if (this.alias) { + lodashSet(paginationData, this.alias, this.getNormalizedItems(items[pageNumber])); + } + + // Do *not* deep merge pagination data! See https://github.com/11ty/eleventy/issues/147#issuecomment-440802454 + let clonedData = ProxyWrap(paginationData, parentData); + + // Previous method: + // let clonedData = DeepCopy(paginationData, parentData); + + let { /*linkInstance,*/ rawPath, path, href } = await cloned.getOutputLocations(clonedData); + // TODO subdirectory to links if the site doesn’t live at / + if (rawPath) { + links.push("/" + rawPath); + } + + hrefs.push(href); + + // page.url and page.outputPath are used to avoid another getOutputLocations call later, see Template->addComputedData + clonedData.page.url = href; + clonedData.page.outputPath = path; + + entries.push({ + pageNumber, + + // This is used by i18n Plugin to allow subgroups of nested pagination to be separate + groupNumber: items[pageNumber]?.[0]?.eleventyPaginationGroupNumber, + + template: cloned, + data: clonedData, + }); + } + + // we loop twice to pass in the appropriate prev/next links (already full generated now) + let index = 0; + for (let pageEntry of entries) { + let linksObj = this.getOverrideDataLinks(index, items.length, links); + + Object.assign(pageEntry.data.pagination, linksObj); + + let hrefsObj = this.getOverrideDataHrefs(index, items.length, hrefs); + Object.assign(pageEntry.data.pagination, hrefsObj); + index++; + } + + return entries; + } +} + +export default Pagination; diff --git a/node_modules/@11ty/eleventy/src/Plugins/RenderPlugin.js b/node_modules/@11ty/eleventy/src/Plugins/RenderPlugin.js new file mode 100644 index 0000000..6636a86 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Plugins/RenderPlugin.js @@ -0,0 +1,481 @@ +import fs from "graceful-fs"; +import { Merge, TemplatePath, isPlainObject } from "@11ty/eleventy-utils"; +import { evalToken } from "liquidjs"; + +// TODO add a first-class Markdown component to expose this using Markdown-only syntax (will need to be synchronous for markdown-it) + +import { ProxyWrap } from "../Util/Objects/ProxyWrap.js"; +import TemplateDataInitialGlobalData from "../Data/TemplateDataInitialGlobalData.js"; +import EleventyBaseError from "../Errors/EleventyBaseError.js"; +import TemplateRender from "../TemplateRender.js"; +import ProjectDirectories from "../Util/ProjectDirectories.js"; +import TemplateConfig from "../TemplateConfig.js"; +import Liquid from "../Engines/Liquid.js"; + +class EleventyNunjucksError extends EleventyBaseError {} + +/** @this {object} */ +async function compile(content, templateLang, options = {}) { + let { templateConfig, extensionMap } = options; + + if (!templateConfig) { + templateConfig = new TemplateConfig(null, false); + templateConfig.setDirectories(new ProjectDirectories()); + await templateConfig.init(); + } + + // Breaking change in 2.0+, previous default was `html` and now we default to the page template syntax + if (!templateLang) { + templateLang = this.page.templateSyntax; + } + + let tr = new TemplateRender(templateLang, templateConfig); + tr.extensionMap = extensionMap; + if (templateLang) { + await tr.setEngineOverride(templateLang); + } else { + await tr.init(); + } + + // TODO tie this to the class, not the extension + if ( + tr.engine.name === "11ty.js" || + tr.engine.name === "11ty.cjs" || + tr.engine.name === "11ty.mjs" + ) { + throw new Error( + "11ty.js is not yet supported as a template engine for `renderTemplate`. Use `renderFile` instead!", + ); + } + + return tr.getCompiledTemplate(content); +} + +// No templateLang default, it should infer from the inputPath. +async function compileFile(inputPath, options = {}, templateLang) { + let { templateConfig, extensionMap, config } = options; + if (!inputPath) { + throw new Error("Missing file path argument passed to the `renderFile` shortcode."); + } + + if (!fs.existsSync(TemplatePath.normalizeOperatingSystemFilePath(inputPath))) { + throw new Error( + "Could not find render plugin file for the `renderFile` shortcode, looking for: " + inputPath, + ); + } + + let wasTemplateConfigMissing = false; + if (!templateConfig) { + templateConfig = new TemplateConfig(null, false); + templateConfig.setDirectories(new ProjectDirectories()); + wasTemplateConfigMissing = true; + } + if (config && typeof config === "function") { + await config(templateConfig.userConfig); + } + if (wasTemplateConfigMissing) { + await templateConfig.init(); + } + + let tr = new TemplateRender(inputPath, templateConfig); + tr.extensionMap = extensionMap; + + if (templateLang) { + await tr.setEngineOverride(templateLang); + } else { + await tr.init(); + } + + if (!tr.engine.needsToReadFileContents()) { + return tr.getCompiledTemplate(null); + } + + // TODO we could make this work with full templates (with front matter?) + let content = fs.readFileSync(inputPath, "utf8"); + return tr.getCompiledTemplate(content); +} + +/** @this {object} */ +async function renderShortcodeFn(fn, data) { + if (fn === undefined) { + return; + } else if (typeof fn !== "function") { + throw new Error(`The \`compile\` function did not return a function. Received ${fn}`); + } + + // if the user passes a string or other literal, remap to an object. + if (!isPlainObject(data)) { + data = { + _: data, + }; + } + + if ("data" in this && isPlainObject(this.data)) { + // when options.accessGlobalData is true, this allows the global data + // to be accessed inside of the shortcode as a fallback + + data = ProxyWrap(data, this.data); + } else { + // save `page` and `eleventy` for reuse + data.page = this.page; + data.eleventy = this.eleventy; + } + + return fn(data); +} + +/** + * @module 11ty/eleventy/Plugins/RenderPlugin + */ + +/** + * A plugin to add shortcodes to render an Eleventy template + * string (or file) inside of another template. {@link https://v3.11ty.dev/docs/plugins/render/} + * + * @since 1.0.0 + * @param {module:11ty/eleventy/UserConfig} eleventyConfig - User-land configuration instance. + * @param {object} options - Plugin options + */ +function eleventyRenderPlugin(eleventyConfig, options = {}) { + /** + * @typedef {object} options + * @property {string} [tagName] - The shortcode name to render a template string. + * @property {string} [tagNameFile] - The shortcode name to render a template file. + * @property {module:11ty/eleventy/TemplateConfig} [templateConfig] - Configuration object + * @property {boolean} [accessGlobalData] - Whether or not the template has access to the page’s data. + */ + let defaultOptions = { + tagName: "renderTemplate", + tagNameFile: "renderFile", + filterName: "renderContent", + templateConfig: null, + accessGlobalData: false, + }; + let opts = Object.assign(defaultOptions, options); + + function liquidTemplateTag(liquidEngine, tagName) { + // via https://github.com/harttle/liquidjs/blob/b5a22fa0910c708fe7881ef170ed44d3594e18f3/src/builtin/tags/raw.ts + return { + parse: function (tagToken, remainTokens) { + this.name = tagToken.name; + + if (eleventyConfig.liquid.parameterParsing === "builtin") { + this.orderedArgs = Liquid.parseArgumentsBuiltin(tagToken.args); + // note that Liquid does have a Hash class for name-based argument parsing but offers no easy to support both modes in one class + } else { + this.legacyArgs = tagToken.args; + } + + this.tokens = []; + + var stream = liquidEngine.parser + .parseStream(remainTokens) + .on("token", (token) => { + if (token.name === "end" + tagName) stream.stop(); + else this.tokens.push(token); + }) + .on("end", () => { + throw new Error(`tag ${tagToken.getText()} not closed`); + }); + + stream.start(); + }, + render: function* (ctx) { + let normalizedContext = {}; + if (ctx) { + if (opts.accessGlobalData) { + // parent template data cascade + normalizedContext.data = ctx.getAll(); + } + + normalizedContext.page = ctx.get(["page"]); + normalizedContext.eleventy = ctx.get(["eleventy"]); + } + + let argArray = []; + if (this.legacyArgs) { + let rawArgs = Liquid.parseArguments(null, this.legacyArgs); + for (let arg of rawArgs) { + let b = yield liquidEngine.evalValue(arg, ctx); + argArray.push(b); + } + } else if (this.orderedArgs) { + for (let arg of this.orderedArgs) { + let b = yield evalToken(arg, ctx); + argArray.push(b); + } + } + + // plaintext paired shortcode content + let body = this.tokens.map((token) => token.getText()).join(""); + + let ret = _renderStringShortcodeFn.call( + normalizedContext, + body, + // templateLang, data + ...argArray, + ); + yield ret; + return ret; + }, + }; + } + + // TODO I don’t think this works with whitespace control, e.g. {%- endrenderTemplate %} + function nunjucksTemplateTag(NunjucksLib, tagName) { + return new (function () { + this.tags = [tagName]; + + this.parse = function (parser, nodes) { + var tok = parser.nextToken(); + + var args = parser.parseSignature(true, true); + const begun = parser.advanceAfterBlockEnd(tok.value); + + // This code was ripped from the Nunjucks parser for `raw` + // https://github.com/mozilla/nunjucks/blob/fd500902d7c88672470c87170796de52fc0f791a/nunjucks/src/parser.js#L655 + const endTagName = "end" + tagName; + // Look for upcoming raw blocks (ignore all other kinds of blocks) + const rawBlockRegex = new RegExp( + "([\\s\\S]*?){%\\s*(" + tagName + "|" + endTagName + ")\\s*(?=%})%}", + ); + let rawLevel = 1; + let str = ""; + let matches = null; + + // Exit when there's nothing to match + // or when we've found the matching "endraw" block + while ((matches = parser.tokens._extractRegex(rawBlockRegex)) && rawLevel > 0) { + const all = matches[0]; + const pre = matches[1]; + const blockName = matches[2]; + + // Adjust rawlevel + if (blockName === tagName) { + rawLevel += 1; + } else if (blockName === endTagName) { + rawLevel -= 1; + } + + // Add to str + if (rawLevel === 0) { + // We want to exclude the last "endraw" + str += pre; + // Move tokenizer to beginning of endraw block + parser.tokens.backN(all.length - pre.length); + } else { + str += all; + } + } + + let body = new nodes.Output(begun.lineno, begun.colno, [ + new nodes.TemplateData(begun.lineno, begun.colno, str), + ]); + return new nodes.CallExtensionAsync(this, "run", args, [body]); + }; + + this.run = function (...args) { + let resolve = args.pop(); + let body = args.pop(); + let [context, ...argArray] = args; + + let normalizedContext = {}; + if (context.ctx?.page) { + normalizedContext.ctx = context.ctx; + + // TODO .data + // if(opts.accessGlobalData) { + // normalizedContext.data = context.ctx; + // } + + normalizedContext.page = context.ctx.page; + normalizedContext.eleventy = context.ctx.eleventy; + } + + body(function (e, bodyContent) { + if (e) { + resolve( + new EleventyNunjucksError(`Error with Nunjucks paired shortcode \`${tagName}\``, e), + ); + } + + Promise.resolve( + _renderStringShortcodeFn.call( + normalizedContext, + bodyContent, + // templateLang, data + ...argArray, + ), + ).then( + function (returnValue) { + resolve(null, new NunjucksLib.runtime.SafeString(returnValue)); + }, + function (e) { + resolve( + new EleventyNunjucksError(`Error with Nunjucks paired shortcode \`${tagName}\``, e), + null, + ); + }, + ); + }); + }; + })(); + } + + // This will only work on 1.0.0-beta.5+ but is only necessary if you want to reuse your config inside of template shortcodes. + // Just rendering raw templates (without filters, shortcodes, etc. from your config) will work fine on old versions. + let templateConfig; + eleventyConfig.on("eleventy.config", (cfg) => { + templateConfig = cfg; + }); + + let extensionMap; + eleventyConfig.on("eleventy.extensionmap", (map) => { + extensionMap = map; + }); + + /** @this {object} */ + async function _renderStringShortcodeFn(content, templateLang, data = {}) { + // Default is fn(content, templateLang, data) but we want to support fn(content, data) too + if (typeof templateLang !== "string") { + data = templateLang; + templateLang = false; + } + + let fn = await compile.call(this, content, templateLang, { + templateConfig: opts.templateConfig || templateConfig, + extensionMap, + }); + + return renderShortcodeFn.call(this, fn, data); + } + + /** @this {object} */ + async function _renderFileShortcodeFn(inputPath, data = {}, templateLang) { + let options = { + templateConfig: opts.templateConfig || templateConfig, + extensionMap, + }; + + let fn = await compileFile.call(this, inputPath, options, templateLang); + + return renderShortcodeFn.call(this, fn, data); + } + + // Render strings + if (opts.tagName) { + // use falsy to opt-out + eleventyConfig.addJavaScriptFunction(opts.tagName, _renderStringShortcodeFn); + + eleventyConfig.addLiquidTag(opts.tagName, function (liquidEngine) { + return liquidTemplateTag(liquidEngine, opts.tagName); + }); + + eleventyConfig.addNunjucksTag(opts.tagName, function (nunjucksLib) { + return nunjucksTemplateTag(nunjucksLib, opts.tagName); + }); + } + + // Filter for rendering strings + if (opts.filterName) { + eleventyConfig.addAsyncFilter(opts.filterName, _renderStringShortcodeFn); + } + + // Render File + // use `false` to opt-out + if (opts.tagNameFile) { + eleventyConfig.addAsyncShortcode(opts.tagNameFile, _renderFileShortcodeFn); + } +} + +// Will re-use the same configuration instance both at a top level and across any nested renders +class RenderManager { + /** @type {Promise|undefined} */ + #hasConfigInitialized; + + constructor() { + this.templateConfig = new TemplateConfig(null, false); + this.templateConfig.setDirectories(new ProjectDirectories()); + + // This is the only plugin running on the Edge + this.templateConfig.userConfig.addPlugin(eleventyRenderPlugin, { + templateConfig: this.templateConfig, + accessGlobalData: true, + }); + } + + async init() { + if (this.#hasConfigInitialized) { + return this.#hasConfigInitialized; + } + if (this.templateConfig.hasInitialized()) { + return true; + } + this.#hasConfigInitialized = this.templateConfig.init(); + await this.#hasConfigInitialized; + + return true; + } + + // `callback` is async-friendly but requires await upstream + config(callback) { + // run an extra `function(eleventyConfig)` configuration callbacks + if (callback && typeof callback === "function") { + return callback(this.templateConfig.userConfig); + } + } + + get initialGlobalData() { + if (!this._data) { + this._data = new TemplateDataInitialGlobalData(this.templateConfig); + } + return this._data; + } + + // because we don’t have access to the full data cascade—but + // we still want configuration data added via `addGlobalData` + async getData(...data) { + await this.init(); + + let globalData = await this.initialGlobalData.getData(); + let merged = Merge({}, globalData, ...data); + return merged; + } + + async compile(content, templateLang, options = {}) { + await this.init(); + + // Missing here: extensionMap + options.templateConfig = this.templateConfig; + + // We don’t need `compile.call(this)` here because the Edge always uses "liquid" as the template lang (instead of relying on this.page.templateSyntax) + // returns promise + return compile(content, templateLang, options); + } + + async render(fn, edgeData, buildTimeData) { + await this.init(); + + let mergedData = await this.getData(edgeData); + // Set .data for options.accessGlobalData feature + let context = { + data: mergedData, + }; + + return renderShortcodeFn.call(context, fn, buildTimeData); + } +} + +Object.defineProperty(eleventyRenderPlugin, "eleventyPackage", { + value: "@11ty/eleventy/render-plugin", +}); + +Object.defineProperty(eleventyRenderPlugin, "eleventyPluginOptions", { + value: { + unique: true, + }, +}); + +export default eleventyRenderPlugin; + +export { compileFile as File, compile as String, RenderManager }; diff --git a/node_modules/@11ty/eleventy/src/Template.js b/node_modules/@11ty/eleventy/src/Template.js new file mode 100755 index 0000000..d92e4ac --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Template.js @@ -0,0 +1,1124 @@ +import util from "node:util"; +import os from "node:os"; +import path from "node:path"; + +import fs from "graceful-fs"; +import lodash from "@11ty/lodash-custom"; +import { DateTime } from "luxon"; +import { TemplatePath, isPlainObject } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; +import chalk from "kleur"; + +import ConsoleLogger from "./Util/ConsoleLogger.js"; +import getDateFromGitLastUpdated from "./Util/DateGitLastUpdated.js"; +import getDateFromGitFirstAdded from "./Util/DateGitFirstAdded.js"; +import TemplateData from "./Data/TemplateData.js"; +import TemplateContent from "./TemplateContent.js"; +import TemplatePermalink from "./TemplatePermalink.js"; +import TemplateLayout from "./TemplateLayout.js"; +import TemplateFileSlug from "./TemplateFileSlug.js"; +import ComputedData from "./Data/ComputedData.js"; +import Pagination from "./Plugins/Pagination.js"; +import TemplateBehavior from "./TemplateBehavior.js"; +import TemplateContentPrematureUseError from "./Errors/TemplateContentPrematureUseError.js"; +import TemplateContentUnrenderedTemplateError from "./Errors/TemplateContentUnrenderedTemplateError.js"; +import EleventyBaseError from "./Errors/EleventyBaseError.js"; +import ReservedData from "./Util/ReservedData.js"; +import TransformsUtil from "./Util/TransformsUtil.js"; + +const { set: lodashSet, get: lodashGet } = lodash; +const fsStat = util.promisify(fs.stat); + +const debug = debugUtil("Eleventy:Template"); +const debugDev = debugUtil("Dev:Eleventy:Template"); + +class Template extends TemplateContent { + constructor(templatePath, templateData, extensionMap, config) { + debugDev("new Template(%o)", templatePath); + super(templatePath, config); + + this.parsed = path.parse(templatePath); + + // for pagination + this.extraOutputSubdirectory = ""; + + this.extensionMap = extensionMap; + + this.linters = []; + this.transforms = {}; + + this.setTemplateData(templateData); + + this.isVerbose = true; + this.isDryRun = false; + this.writeCount = 0; + + this.fileSlug = new TemplateFileSlug(this.inputPath, this.extensionMap, this.eleventyConfig); + this.fileSlugStr = this.fileSlug.getSlug(); + this.filePathStem = this.fileSlug.getFullPathWithoutExtension(); + + this.outputFormat = "fs"; + + this.behavior = new TemplateBehavior(this.config); + this.behavior.setOutputFormat(this.outputFormat); + } + + setTemplateData(templateData) { + this.templateData = templateData; + } + + get existsCache() { + return this.eleventyConfig.existsCache; + } + + get logger() { + if (!this._logger) { + this._logger = new ConsoleLogger(); + this._logger.isVerbose = this.isVerbose; + } + return this._logger; + } + + /* Setter for Logger */ + set logger(logger) { + this._logger = logger; + } + + isRenderable() { + return this.behavior.isRenderable(); + } + + isRenderableDisabled() { + return this.behavior.isRenderableDisabled(); + } + + isRenderableOptional() { + // A template that is lazily rendered once if used by a second order dependency of another template dependency. + // e.g. You change firstpost.md, which is used by feed.xml, but secondpost.md (also used by feed.xml) + // has not yet rendered and needs to be rendered once to populate the cache. + return this.behavior.isRenderableOptional(); + } + + setRenderableOverride(renderableOverride) { + this.behavior.setRenderableOverride(renderableOverride); + } + + reset() { + this.renderCount = 0; + this.writeCount = 0; + } + + resetCaches(types) { + types = this.getResetTypes(types); + + super.resetCaches(types); + + if (types.data) { + delete this._dataCache; + // delete this._usePermalinkRoot; + // delete this._stats; + } + + if (types.render) { + delete this._cacheRenderedPromise; + delete this._cacheRenderedTransformsAndLayoutsPromise; + } + } + + setOutputFormat(to) { + this.outputFormat = to; + this.behavior.setOutputFormat(to); + } + + setIsVerbose(isVerbose) { + this.isVerbose = isVerbose; + this.logger.isVerbose = isVerbose; + } + + setDryRunViaIncremental(isIncremental) { + this.isDryRun = isIncremental; + this.isIncremental = isIncremental; + } + + setDryRun(isDryRun) { + this.isDryRun = !!isDryRun; + } + + setExtraOutputSubdirectory(dir) { + this.extraOutputSubdirectory = dir + "/"; + } + + getTemplateSubfolder() { + return TemplatePath.stripLeadingSubPath(this.parsed.dir, this.inputDir); + } + + getLayout(layoutKey) { + // already cached downstream in TemplateLayout -> TemplateCache + try { + return TemplateLayout.getTemplate(layoutKey, this.eleventyConfig, this.extensionMap); + } catch (e) { + throw new EleventyBaseError( + `Problem creating an Eleventy Layout for the "${this.inputPath}" template file.`, + e, + ); + } + } + + get baseFile() { + return this.extensionMap.removeTemplateExtension(this.parsed.base); + } + + async _getRawPermalinkInstance(permalinkValue) { + let perm = new TemplatePermalink(permalinkValue, this.extraOutputSubdirectory); + perm.setUrlTransforms(this.config.urlTransforms); + + this.behavior.setFromPermalink(perm); + + return perm; + } + + async _getLink(data) { + if (!data) { + throw new Error("data argument missing in Template->_getLink"); + } + + let permalink = data[this.config.keys.permalink]; + let permalinkValue; + + // `permalink: false` means render but no file system write, e.g. use in collections only) + // `permalink: true` throws an error + if (typeof permalink === "boolean") { + debugDev("Using boolean permalink %o", permalink); + permalinkValue = permalink; + } else if (permalink && (!this.config.dynamicPermalinks || data.dynamicPermalink === false)) { + debugDev("Not using dynamic permalinks, using %o", permalink); + permalinkValue = permalink; + } else if (isPlainObject(permalink)) { + // Empty permalink {} object should act as if no permalink was set at all + // and inherit the default behavior + let isEmptyObject = Object.keys(permalink).length === 0; + if (!isEmptyObject) { + let promises = []; + let keys = []; + for (let key in permalink) { + keys.push(key); + if (key !== "build" && Array.isArray(permalink[key])) { + promises.push( + Promise.all([...permalink[key]].map((entry) => super.renderPermalink(entry, data))), + ); + } else { + promises.push(super.renderPermalink(permalink[key], data)); + } + } + + let results = await Promise.all(promises); + + permalinkValue = {}; + for (let j = 0, k = keys.length; j < k; j++) { + let key = keys[j]; + permalinkValue[key] = results[j]; + debug( + "Rendering permalink.%o for %o: %s becomes %o", + key, + this.inputPath, + permalink[key], + results[j], + ); + } + } + } else if (permalink) { + // render variables inside permalink front matter, bypass markdown + permalinkValue = await super.renderPermalink(permalink, data); + debug("Rendering permalink for %o: %s becomes %o", this.inputPath, permalink, permalinkValue); + debugDev("Permalink rendered with data: %o", data); + } + + // Override default permalink behavior. Only do this if permalink was _not_ in the data cascade + if (!permalink && this.config.dynamicPermalinks && data.dynamicPermalink !== false) { + let permalinkCompilation = this.engine.permalinkNeedsCompilation(""); + if (typeof permalinkCompilation === "function") { + let ret = await this._renderFunction(permalinkCompilation, permalinkValue, this.inputPath); + if (ret !== undefined) { + if (typeof ret === "function") { + // function + permalinkValue = await this._renderFunction(ret, data); + } else { + // scalar + permalinkValue = ret; + } + } + } + } + + if (permalinkValue !== undefined) { + return this._getRawPermalinkInstance(permalinkValue); + } + + // No `permalink` specified in data cascade, do the default + let p = TemplatePermalink.generate( + this.getTemplateSubfolder(), + this.baseFile, + this.extraOutputSubdirectory, + this.engine.defaultTemplateFileExtension, + ); + p.setUrlTransforms(this.config.urlTransforms); + return p; + } + + async usePermalinkRoot() { + // @cachedproperty + if (this._usePermalinkRoot === undefined) { + // TODO this only works with immediate front matter and not data files + let { data } = await this.getFrontMatterData(); + this._usePermalinkRoot = data[this.config.keys.permalinkRoot]; + } + + return this._usePermalinkRoot; + } + + async getOutputLocations(data) { + this.bench.get("(count) getOutputLocations").incrementCount(); + let link = await this._getLink(data); + + let path; + if (await this.usePermalinkRoot()) { + path = link.toPathFromRoot(); + } else { + path = link.toPath(this.outputDir); + } + + return { + linkInstance: link, + rawPath: link.toOutputPath(), + href: link.toHref(), + path: path, + }; + } + + // This is likely now a test-only method + // Preferred to use the singular `getOutputLocations` above. + async getRawOutputPath(data) { + this.bench.get("(count) getRawOutputPath").incrementCount(); + let link = await this._getLink(data); + return link.toOutputPath(); + } + + // Preferred to use the singular `getOutputLocations` above. + async getOutputHref(data) { + this.bench.get("(count) getOutputHref").incrementCount(); + let link = await this._getLink(data); + return link.toHref(); + } + + // Preferred to use the singular `getOutputLocations` above. + async getOutputPath(data) { + this.bench.get("(count) getOutputPath").incrementCount(); + let link = await this._getLink(data); + if (await this.usePermalinkRoot()) { + return link.toPathFromRoot(); + } + return link.toPath(this.outputDir); + } + + async _testGetAllLayoutFrontMatterData() { + let { data: frontMatterData } = await this.getFrontMatterData(); + + if (frontMatterData[this.config.keys.layout]) { + let layout = this.getLayout(frontMatterData[this.config.keys.layout]); + return await layout.getData(); + } + return {}; + } + + async #getData() { + debugDev("%o getData", this.inputPath); + let localData = {}; + let globalData = {}; + + if (this.templateData) { + localData = await this.templateData.getTemplateDirectoryData(this.inputPath); + globalData = await this.templateData.getGlobalData(this.inputPath); + debugDev("%o getData getTemplateDirectoryData and getGlobalData", this.inputPath); + } + + let { data: frontMatterData } = await this.getFrontMatterData(); + + let mergedLayoutData = {}; + if (this.engine.useLayouts()) { + let layoutKey = + frontMatterData[this.config.keys.layout] || + localData[this.config.keys.layout] || + globalData[this.config.keys.layout]; + + // Layout front matter data + if (layoutKey) { + let layout = this.getLayout(layoutKey); + + mergedLayoutData = await layout.getData(); + debugDev("%o getData merged layout chain front matter", this.inputPath); + } + } + + try { + let mergedData = TemplateData.mergeDeep( + this.config.dataDeepMerge, + {}, + globalData, + mergedLayoutData, + localData, + frontMatterData, + ); + + if (this.config.freezeReservedData) { + ReservedData.check(mergedData); + } + + await this.addPage(mergedData); + + debugDev("%o getData mergedData", this.inputPath); + + return mergedData; + } catch (e) { + if ( + ReservedData.isReservedDataError(e) || + (e instanceof TypeError && + e.message.startsWith("Cannot add property") && + e.message.endsWith("not extensible")) + ) { + throw new EleventyBaseError( + `You attempted to set one of Eleventy’s reserved data property names${e.reservedNames ? `: ${e.reservedNames.join(", ")}` : ""}. You can opt-out of this behavior with \`eleventyConfig.setFreezeReservedData(false)\` or rename/remove the property in your data cascade that conflicts with Eleventy’s reserved property names (e.g. \`eleventy\`, \`pkg\`, and others). Learn more: https://v3.11ty.dev/docs/data-eleventy-supplied/`, + e, + ); + } + + throw e; + } + } + + async getData() { + if (!this._dataCache) { + // @cachedproperty + this._dataCache = this.#getData(); + } + + return this._dataCache; + } + + async addPage(data) { + if (!("page" in data)) { + data.page = {}; + } + + // Make sure to keep these keys synchronized in src/Util/ReservedData.js + data.page.inputPath = this.inputPath; + data.page.fileSlug = this.fileSlugStr; + data.page.filePathStem = this.filePathStem; + data.page.outputFileExtension = this.engine.defaultTemplateFileExtension; + data.page.templateSyntax = this.templateRender.getEnginesList( + data[this.config.keys.engineOverride], + ); + + let newDate = await this.getMappedDate(data); + // Skip date assignment if custom date is falsy. + if (newDate) { + data.page.date = newDate; + } + + // data.page.url + // data.page.outputPath + // data.page.excerpt from gray-matter and Front Matter + // data.page.lang from I18nPlugin + } + + // Tests only + async render() { + throw new Error("Internal error: `Template->render` was removed in Eleventy 3.0."); + } + + // Tests only + async renderLayout() { + throw new Error("Internal error: `Template->renderLayout` was removed in Eleventy 3.0."); + } + + async renderDirect(str, data, bypassMarkdown) { + return super.render(str, data, bypassMarkdown); + } + + // This is the primary render mechanism, called via TemplateMap->populateContentDataInMap + async renderPageEntryWithoutLayout(pageEntry) { + // @cachedproperty + if (!this._cacheRenderedPromise) { + this._cacheRenderedPromise = this.renderDirect(pageEntry.rawInput, pageEntry.data); + this.renderCount++; + } + + return this._cacheRenderedPromise; + } + + addLinter(callback) { + this.linters.push(callback); + } + + async runLinters(str, page) { + let { inputPath, outputPath, url } = page; + let pageData = page.data.page; + + for (let linter of this.linters) { + // these can be asynchronous but no guarantee of order when they run + linter.call( + { + inputPath, + outputPath, + url, + page: pageData, + }, + str, + inputPath, + outputPath, + ); + } + } + + setTransforms(transforms) { + if (!isPlainObject(transforms)) { + throw new Error("Object expected in setTransforms"); + } + this.transforms = transforms; + } + + async runTransforms(str, pageEntry) { + return TransformsUtil.runAll(str, pageEntry.data.page, this.transforms, { + logger: this.logger, + }); + } + + _addComputedEntry(computedData, obj, parentKey, declaredDependencies) { + // this check must come before isPlainObject + if (typeof obj === "function") { + computedData.add(parentKey, obj, declaredDependencies); + } else if (Array.isArray(obj) || isPlainObject(obj)) { + for (let key in obj) { + let keys = []; + if (parentKey) { + keys.push(parentKey); + } + keys.push(key); + this._addComputedEntry(computedData, obj[key], keys.join("."), declaredDependencies); + } + } else if (typeof obj === "string") { + computedData.addTemplateString( + parentKey, + async function (innerData) { + return this.tmpl.renderComputedData(obj, innerData); + }, + declaredDependencies, + this.getParseForSymbolsFunction(obj), + this, + ); + } else { + // Numbers, booleans, etc + computedData.add(parentKey, obj, declaredDependencies); + } + } + + async addComputedData(data) { + if (isPlainObject(data?.[this.config.keys.computed])) { + this.computedData = new ComputedData(this.config); + + // Note that `permalink` is only a thing that gets consumed—it does not go directly into generated data + // this allows computed entries to use page.url or page.outputPath and they’ll be resolved properly + + // TODO Room for optimization here—we don’t need to recalculate `getOutputHref` and `getOutputPath` + // TODO Why are these using addTemplateString instead of add + this.computedData.addTemplateString( + "page.url", + async function (data) { + return this.tmpl.getOutputHref(data); + }, + data.permalink ? ["permalink"] : undefined, + false, // skip symbol resolution + this, + ); + + this.computedData.addTemplateString( + "page.outputPath", + async function (data) { + return this.tmpl.getOutputPath(data); + }, + data.permalink ? ["permalink"] : undefined, + false, // skip symbol resolution + this, + ); + + // Check for reserved properties in computed data + if (this.config.freezeReservedData) { + ReservedData.check(data[this.config.keys.computed]); + } + + // actually add the computed data + this._addComputedEntry(this.computedData, data[this.config.keys.computed]); + + // limited run of computed data—save the stuff that relies on collections for later. + debug("First round of computed data for %o", this.inputPath); + await this.computedData.setupData(data, function (entry) { + return !this.isUsesStartsWith(entry, "collections."); + + // TODO possible improvement here is to only process page.url, page.outputPath, permalink + // instead of only punting on things that rely on collections. + // let firstPhaseComputedData = ["page.url", "page.outputPath", ...this.getOrderFor("page.url"), ...this.getOrderFor("page.outputPath")]; + // return firstPhaseComputedData.indexOf(entry) > -1; + }); + } else { + if (!("page" in data)) { + data.page = {}; + } + + // pagination will already have these set via Pagination->getPageTemplates + if (data.page.url && data.page.outputPath) { + return; + } + + let { href, path } = await this.getOutputLocations(data); + data.page.url = href; + data.page.outputPath = path; + } + } + + // Computed data consuming collections! + async resolveRemainingComputedData(data) { + // If it doesn’t exist, computed data is not used for this template + if (this.computedData) { + debug("Second round of computed data for %o", this.inputPath); + await this.computedData.processRemainingData(data); + } + } + + static augmentWithTemplateContentProperty(obj) { + return Object.defineProperties(obj, { + needsCheck: { + enumerable: false, + writable: true, + value: true, + }, + _templateContent: { + enumerable: false, + writable: true, + value: undefined, + }, + templateContent: { + enumerable: true, + set(content) { + if (content === undefined) { + this.needsCheck = false; + } + this._templateContent = content; + }, + get() { + if (this.needsCheck && this._templateContent === undefined) { + if (this.template.isRenderable()) { + // should at least warn here + throw new TemplateContentPrematureUseError( + `Tried to use templateContent too early on ${this.inputPath}${ + this.pageNumber ? ` (page ${this.pageNumber})` : "" + }`, + ); + } else { + throw new TemplateContentUnrenderedTemplateError( + `Tried to use templateContent on unrendered template: ${ + this.inputPath + }${this.pageNumber ? ` (page ${this.pageNumber})` : ""}`, + ); + } + } + return this._templateContent; + }, + }, + // Alias for templateContent for consistency + content: { + enumerable: true, + get() { + return this.templateContent; + }, + set() { + throw new Error("Setter not available for `content`. Use `templateContent` instead."); + }, + }, + }); + } + + static async runPreprocessors(inputPath, content, data, preprocessors) { + let skippedVia = false; + for (let [name, preprocessor] of Object.entries(preprocessors)) { + let { filter, callback } = preprocessor; + + let filters; + if (Array.isArray(filter)) { + filters = filter; + } else if (typeof filter === "string") { + filters = filter.split(","); + } else { + throw new Error( + `Expected file extensions passed to "${name}" content preprocessor to be a string or array. Received: ${filter}`, + ); + } + + filters = filters.map((extension) => { + if (extension.startsWith(".") || extension === "*") { + return extension; + } + + return `.${extension}`; + }); + + if (!filters.some((extension) => extension === "*" || inputPath.endsWith(extension))) { + // skip + continue; + } + + try { + let ret = await callback.call( + { + inputPath, + }, + data, + content, + ); + + // Returning explicit false is the same as ignoring the template + if (ret === false) { + skippedVia = name; + continue; + } + + // Different from transforms: returning falsy (not false) here does nothing (skips the preprocessor) + if (ret) { + content = ret; + } + } catch (e) { + throw new EleventyBaseError( + `Preprocessor \`${name}\` encountered an error when transforming ${inputPath}.`, + e, + ); + } + } + + return { + skippedVia, + content, + }; + } + + async getTemplates(data) { + let content = await this.getPreRender(); + let { skippedVia, content: rawInput } = await Template.runPreprocessors( + this.inputPath, + content, + data, + this.config.preprocessors, + ); + + if (skippedVia) { + debug( + "Skipping %o, the %o preprocessor returned an explicit `false`", + this.inputPath, + skippedVia, + ); + return []; + } + + // https://github.com/11ty/eleventy/issues/1206 + data.page.rawInput = rawInput; + + if (!Pagination.hasPagination(data)) { + await this.addComputedData(data); + + let obj = { + template: this, // not on the docs but folks are relying on it + rawInput, + groupNumber: 0, // i18n plugin + data, + + page: data.page, + inputPath: this.inputPath, + fileSlug: this.fileSlugStr, + filePathStem: this.filePathStem, + date: data.page.date, + outputPath: data.page.outputPath, + url: data.page.url, + }; + + obj = Template.augmentWithTemplateContentProperty(obj); + + return [obj]; + } else { + // needs collections for pagination items + // but individual pagination entries won’t be part of a collection + this.paging = new Pagination(this, data, this.config); + + let pageTemplates = await this.paging.getPageTemplates(); + let objects = []; + + for (let pageEntry of pageTemplates) { + await pageEntry.template.addComputedData(pageEntry.data); + + let obj = { + template: pageEntry.template, // not on the docs but folks are relying on it + rawInput, + pageNumber: pageEntry.pageNumber, + groupNumber: pageEntry.groupNumber || 0, + + data: pageEntry.data, + + inputPath: this.inputPath, + fileSlug: this.fileSlugStr, + filePathStem: this.filePathStem, + + page: pageEntry.data.page, + date: pageEntry.data.page.date, + outputPath: pageEntry.data.page.outputPath, + url: pageEntry.data.page.url, + }; + + obj = Template.augmentWithTemplateContentProperty(obj); + + objects.push(obj); + } + + return objects; + } + } + + async _write({ url, outputPath, data, rawInput }, finalContent) { + let lang = { + start: "Writing", + finished: "written", + }; + + if (!this.isDryRun) { + let isVirtual = this.isVirtualTemplate(); + let engineList = this.templateRender.getReadableEnginesListDifferingFromFileExtension(); + let suffix = `${isVirtual ? " (virtual)" : ""}${engineList ? ` (${engineList})` : ""}`; + this.logger.log( + `${lang.start} ${outputPath} ${chalk.gray(`from ${this.inputPath}${suffix}`)}`, + ); + } else if (this.isDryRun) { + return; + } + + let templateBenchmarkDir = this.bench.get("Template make parent directory"); + templateBenchmarkDir.before(); + + let templateOutputDir = path.parse(outputPath).dir; + if (templateOutputDir) { + if (!this.existsCache.exists(templateOutputDir)) { + fs.mkdirSync(templateOutputDir, { recursive: true }); + } + } + templateBenchmarkDir.after(); + + if (!Buffer.isBuffer(finalContent) && typeof finalContent !== "string") { + throw new Error( + `The return value from the render function for the ${this.engine.name} template was not a String or Buffer. Received ${finalContent}`, + ); + } + + let templateBenchmark = this.bench.get("Template Write"); + templateBenchmark.before(); + + // Note: This deliberately uses the synchronous version to avoid + // unbounded concurrency: https://github.com/11ty/eleventy/issues/3271 + fs.writeFileSync(outputPath, finalContent); + + templateBenchmark.after(); + this.writeCount++; + debug(`${outputPath} ${lang.finished}.`); + + let ret = { + inputPath: this.inputPath, + outputPath: outputPath, + url, + content: finalContent, + rawInput, + }; + + if (data && this.config.dataFilterSelectors?.size > 0) { + ret.data = this.retrieveDataForJsonOutput(data, this.config.dataFilterSelectors); + } + + return ret; + } + + async #renderPageEntryWithLayoutsAndTransforms(pageEntry) { + let content; + let layoutKey = pageEntry.data[this.config.keys.layout]; + if (this.engine.useLayouts() && layoutKey) { + let layout = pageEntry.template.getLayout(layoutKey); + content = await layout.renderPageEntry(pageEntry); + } else { + content = pageEntry.templateContent; + } + + await this.runLinters(content, pageEntry); + + content = await this.runTransforms(content, pageEntry); + + return content; + } + + async renderPageEntry(pageEntry) { + // @cachedproperty + if (!pageEntry.template._cacheRenderedTransformsAndLayoutsPromise) { + pageEntry.template._cacheRenderedTransformsAndLayoutsPromise = + this.#renderPageEntryWithLayoutsAndTransforms(pageEntry); + } + + return pageEntry.template._cacheRenderedTransformsAndLayoutsPromise; + } + + retrieveDataForJsonOutput(data, selectors) { + let filtered = {}; + for (let selector of selectors) { + let value = lodashGet(data, selector); + lodashSet(filtered, selector, value); + } + return filtered; + } + + async generateMapEntry(mapEntry, to) { + let ret = []; + + for (let page of mapEntry._pages) { + let content; + + // Note that behavior.render is overridden when using json or ndjson output + if (page.template.isRenderable()) { + // this reuses page.templateContent, it doesn’t render it + content = await page.template.renderPageEntry(page); + } + + if (to === "json" || to === "ndjson") { + let obj = { + url: page.url, + inputPath: page.inputPath, + outputPath: page.outputPath, + rawInput: page.rawInput, + content: content, + }; + + if (this.config.dataFilterSelectors?.size > 0) { + obj.data = this.retrieveDataForJsonOutput(page.data, this.config.dataFilterSelectors); + } + + if (to === "ndjson") { + let jsonString = JSON.stringify(obj); + this.logger.toStream(jsonString + os.EOL); + continue; + } + + // json + ret.push(obj); + continue; + } + + if (!page.template.isRenderable()) { + debug("Template not written %o from %o.", page.outputPath, page.template.inputPath); + continue; + } + + if (!page.template.behavior.isWriteable()) { + debug( + "Template not written %o from %o (via permalink: false, permalink.build: false, or a permalink object without a build property).", + page.outputPath, + page.template.inputPath, + ); + continue; + } + + // compile returned undefined + if (content !== undefined) { + ret.push(this._write(page, content)); + } + } + + return Promise.all(ret); + } + + async clone() { + // TODO do we need to even run the constructor here or can we simplify it even more + let tmpl = new Template( + this.inputPath, + this.templateData, + this.extensionMap, + this.eleventyConfig, + ); + + // We use this cheap property setter below instead + // await tmpl.getTemplateRender(); + + // preserves caches too, e.g. _frontMatterDataCache + for (let key in this) { + tmpl[key] = this[key]; + } + + return tmpl; + } + + getWriteCount() { + return this.writeCount; + } + + getRenderCount() { + return this.renderCount; + } + + async getInputFileStat() { + // @cachedproperty + if (this._stats) { + return this._stats; + } + + this._stats = fsStat(this.inputPath); + + return this._stats; + } + + async _getDateInstance(key = "birthtimeMs") { + let stat = await this.getInputFileStat(); + + // Issue 1823: https://github.com/11ty/eleventy/issues/1823 + // return current Date in a Lambda + // otherwise ctime would be "1980-01-01T00:00:00.000Z" + // otherwise birthtime would be "1970-01-01T00:00:00.000Z" + if (stat.birthtimeMs === 0) { + return new Date(); + } + + let newDate = new Date(stat[key]); + + debug( + "Template date: using file’s %o for %o of %o (from %o)", + key, + this.inputPath, + newDate, + stat.birthtimeMs, + ); + + return newDate; + } + + async getMappedDate(data) { + let dateValue = data?.date; + + // These can return a Date object, or a string. + // Already type checked to be functions in UserConfig + for (let fn of this.config.customDateParsing) { + let ret = fn.call( + { + page: data.page, + }, + dateValue, + ); + + if (ret) { + debug("getMappedDate: date value override via `addDateParsing` callback to %o", ret); + dateValue = ret; + } + } + + if (dateValue) { + debug("getMappedDate: using a date in the data for %o of %o", this.inputPath, data.date); + if (dateValue instanceof DateTime) { + // YAML does its own date parsing + debug("getMappedDate: found DateTime instance: %o", dateValue); + return dateValue.toJSDate(); + } + + if (dateValue instanceof Date) { + // YAML does its own date parsing + debug("getMappedDate: found Date instance (maybe from YAML): %o", dateValue); + return dateValue; + } + + // special strings + if (!this.isVirtualTemplate()) { + if (dateValue.toLowerCase() === "git last modified") { + let d = getDateFromGitLastUpdated(this.inputPath); + if (d) { + return d; + } + + // return now if this file is not yet available in `git` + return new Date(); + } + if (dateValue.toLowerCase() === "last modified") { + return this._getDateInstance("ctimeMs"); + } + if (dateValue.toLowerCase() === "git created") { + let d = getDateFromGitFirstAdded(this.inputPath); + if (d) { + return d; + } + + // return now if this file is not yet available in `git` + return new Date(); + } + if (dateValue.toLowerCase() === "created") { + return this._getDateInstance("birthtimeMs"); + } + } + + // try to parse with Luxon + let date = DateTime.fromISO(dateValue, { zone: "utc" }); + if (!date.isValid) { + throw new Error( + `Data cascade value for \`date\` (${dateValue}) is invalid for ${this.inputPath}`, + ); + } + debug("getMappedDate: Luxon parsed %o: %o and %o", dateValue, date, date.toJSDate()); + + return date.toJSDate(); + } + + // No Date supplied in the Data Cascade, try to find the date in the file name + let filepathRegex = this.inputPath.match(/(\d{4}-\d{2}-\d{2})/); + if (filepathRegex !== null) { + // if multiple are found in the path, use the first one for the date + let dateObj = DateTime.fromISO(filepathRegex[1], { + zone: "utc", + }).toJSDate(); + debug( + "getMappedDate: using filename regex time for %o of %o: %o", + this.inputPath, + filepathRegex[1], + dateObj, + ); + return dateObj; + } + + // No Date supplied in the Data Cascade + if (this.isVirtualTemplate()) { + return new Date(); + } + + return this._getDateInstance("birthtimeMs"); + } + + // Important reminder: Template data is first generated in TemplateMap + async getTemplateMapEntries(data) { + debugDev("%o getMapped()", this.inputPath); + + this.behavior.setRenderViaDataCascade(data); + + let entries = []; + // does not return outputPath or url, we don’t want to render permalinks yet + entries.push({ + template: this, + inputPath: this.inputPath, + data, + }); + + return entries; + } +} + +export default Template; diff --git a/node_modules/@11ty/eleventy/src/TemplateBehavior.js b/node_modules/@11ty/eleventy/src/TemplateBehavior.js new file mode 100644 index 0000000..8dff97c --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateBehavior.js @@ -0,0 +1,85 @@ +import { isPlainObject } from "@11ty/eleventy-utils"; + +class TemplateBehavior { + #isRenderOptional; + + constructor(config) { + this.render = true; + this.write = true; + this.outputFormat = null; + + if (!config) { + throw new Error("Missing config argument in TemplateBehavior"); + } + this.config = config; + } + + // Render override set to false + isRenderableDisabled() { + return this.renderableOverride === false; + } + + isRenderableOptional() { + return this.#isRenderOptional; + } + + // undefined (fallback), true, false + setRenderableOverride(renderableOverride) { + if (renderableOverride === "optional") { + this.#isRenderOptional = true; + this.renderableOverride = undefined; + } else { + this.#isRenderOptional = false; + this.renderableOverride = renderableOverride; + } + } + + // permalink *has* a build key or output is json/ndjson + isRenderable() { + return this.renderableOverride ?? (this.render || this.isRenderForced()); + } + + setOutputFormat(format) { + this.outputFormat = format; + } + + isRenderForced() { + return this.outputFormat === "json" || this.outputFormat === "ndjson"; + } + + isWriteable() { + return this.write; + } + + // Duplicate logic with TemplatePermalink constructor + setRenderViaDataCascade(data) { + // render is false *only* if `build` key does not exist in permalink objects (both in data and eleventyComputed) + // (note that permalink: false means it won’t write but will still render) + + let keys = new Set(); + if (isPlainObject(data.permalink)) { + for (let key of Object.keys(data.permalink)) { + keys.add(key); + } + } + + let computedKey = this.config.keys.computed; + if (computedKey in data && isPlainObject(data[computedKey]?.permalink)) { + for (let key of Object.keys(data[computedKey].permalink)) { + keys.add(key); + } + } + + if (keys.size) { + this.render = keys.has("build"); + } + } + + setFromPermalink(templatePermalink) { + // this.render is duplicated between TemplatePermalink and `setRenderViaDataCascade` above + this.render = templatePermalink._isRendered; + + this.write = templatePermalink._writeToFileSystem; + } +} +export default TemplateBehavior; diff --git a/node_modules/@11ty/eleventy/src/TemplateCache.js b/node_modules/@11ty/eleventy/src/TemplateCache.js new file mode 100644 index 0000000..ec11437 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateCache.js @@ -0,0 +1,104 @@ +import { TemplatePath } from "@11ty/eleventy-utils"; + +import eventBus from "./EventBus.js"; + +// Note: this is only used for TemplateLayout right now but could be used for more +// Just be careful because right now the TemplateLayout cache keys are not directly mapped to paths +// So you may get collisions if you use this for other things. +class TemplateCache { + constructor() { + this.cache = {}; + this.cacheByInputPath = {}; + } + + clear() { + this.cache = {}; + this.cacheByInputPath = {}; + } + + // alias + removeAll() { + this.clear(); + } + + size() { + return Object.keys(this.cacheByInputPath).length; + } + + add(layoutTemplate) { + let keys = new Set(); + + if (typeof layoutTemplate === "string") { + throw new Error( + "Invalid argument type passed to TemplateCache->add(). Should be a TemplateLayout.", + ); + } + + if ("getFullKey" in layoutTemplate) { + keys.add(layoutTemplate.getFullKey()); + } + + if ("getKey" in layoutTemplate) { + // if `key` was an alias, also set to the pathed layout value too + // e.g. `layout: "default"` and `layout: "default.liquid"` will both map to the same template. + keys.add(layoutTemplate.getKey()); + } + + for (let key of keys) { + this.cache[key] = layoutTemplate; + } + + // also the full template input path for use with eleventy --serve/--watch e.g. `_includes/default.liquid` (see `remove` below) + let fullPath = TemplatePath.stripLeadingDotSlash(layoutTemplate.inputPath); + this.cacheByInputPath[fullPath] = layoutTemplate; + } + + has(key) { + return key in this.cache; + } + + get(key) { + if (!this.has(key)) { + throw new Error(`Could not find ${key} in TemplateCache.`); + } + + return this.cache[key]; + } + + remove(layoutFilePath) { + layoutFilePath = TemplatePath.stripLeadingDotSlash(layoutFilePath); + if (!this.cacheByInputPath[layoutFilePath]) { + // not a layout file + return; + } + + let layoutTemplate = this.cacheByInputPath[layoutFilePath]; + layoutTemplate.resetCaches(); + + let keys = layoutTemplate.getCacheKeys(); + for (let key of keys) { + delete this.cache[key]; + } + + delete this.cacheByInputPath[layoutFilePath]; + } +} + +let layoutCache = new TemplateCache(); + +eventBus.on("eleventy.resourceModified", (path, usedBy, metadata = {}) => { + // https://github.com/11ty/eleventy-plugin-bundle/issues/10 + if (metadata.viaConfigReset) { + layoutCache.removeAll(); + } else if (metadata.relevantLayouts?.length) { + // reset the appropriate layouts relevant to the file. + for (let layoutPath of metadata.relevantLayouts || []) { + layoutCache.remove(layoutPath); + } + } else { + layoutCache.remove(path); + } +}); + +// singleton +export default layoutCache; diff --git a/node_modules/@11ty/eleventy/src/TemplateCollection.js b/node_modules/@11ty/eleventy/src/TemplateCollection.js new file mode 100755 index 0000000..6b75b2f --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateCollection.js @@ -0,0 +1,81 @@ +import { TemplatePath } from "@11ty/eleventy-utils"; + +import TemplateData from "./Data/TemplateData.js"; +import Sortable from "./Util/Objects/Sortable.js"; +import { isGlobMatch } from "./Util/GlobMatcher.js"; + +class TemplateCollection extends Sortable { + constructor() { + super(); + + this._filteredByGlobsCache = new Map(); + } + + getAll() { + return this.items.slice(); + } + + getAllSorted() { + return this.sort(Sortable.sortFunctionDateInputPath); + } + + getSortedByDate() { + return this.sort(Sortable.sortFunctionDate); + } + + getGlobs(globs) { + if (typeof globs === "string") { + globs = [globs]; + } + + globs = globs.map((glob) => TemplatePath.addLeadingDotSlash(glob)); + + return globs; + } + + getFilteredByGlob(globs) { + globs = this.getGlobs(globs); + + let key = globs.join("::"); + if (!this._dirty) { + // Try to find a pre-sorted list and clone it. + if (this._filteredByGlobsCache.has(key)) { + return [...this._filteredByGlobsCache.get(key)]; + } + } else if (this._filteredByGlobsCache.size) { + // Blow away cache + this._filteredByGlobsCache = new Map(); + } + + let filtered = this.getAllSorted().filter((item) => { + return isGlobMatch(item.inputPath, globs); + }); + this._dirty = false; + this._filteredByGlobsCache.set(key, [...filtered]); + return filtered; + } + + getFilteredByTag(tagName) { + return this.getAllSorted().filter((item) => { + if (!tagName || TemplateData.getIncludedTagNames(item.data).includes(tagName)) { + return true; + } + return false; + }); + } + + getFilteredByTags(...tags) { + return this.getAllSorted().filter((item) => { + let itemTags = TemplateData.getIncludedTagNames(item.data); + return tags.every((requiredTag) => { + if (Array.isArray(itemTags)) { + return itemTags.includes(requiredTag); + } else { + return itemTags === requiredTag; + } + }); + }); + } +} + +export default TemplateCollection; diff --git a/node_modules/@11ty/eleventy/src/TemplateConfig.js b/node_modules/@11ty/eleventy/src/TemplateConfig.js new file mode 100644 index 0000000..93528db --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateConfig.js @@ -0,0 +1,551 @@ +import fs from "node:fs"; +import chalk from "kleur"; +import { Merge, TemplatePath, isPlainObject } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import { EleventyImportRaw, EleventyImportRawFromEleventy } from "./Util/Require.js"; +import EleventyBaseError from "./Errors/EleventyBaseError.js"; +import UserConfig from "./UserConfig.js"; +import GlobalDependencyMap from "./GlobalDependencyMap.js"; +import ExistsCache from "./Util/ExistsCache.js"; +import eventBus from "./EventBus.js"; +import ProjectTemplateFormats from "./Util/ProjectTemplateFormats.js"; + +const debug = debugUtil("Eleventy:TemplateConfig"); +const debugDev = debugUtil("Dev:Eleventy:TemplateConfig"); + +/** + * @module 11ty/eleventy/TemplateConfig + */ + +/** + * Config as used by the template. + * @typedef {object} module:11ty/eleventy/TemplateConfig~TemplateConfig~config + * @property {String} [pathPrefix] - The path prefix. + */ + +/** + * Errors in eleventy config. + * @ignore + */ +class EleventyConfigError extends EleventyBaseError {} + +/** + * Errors in eleventy plugins. + * @ignore + */ +class EleventyPluginError extends EleventyBaseError {} + +/** + * Config for a template. + * @ignore + * @param {{}} customRootConfig - tbd. + * @param {String} projectConfigPath - Path to local project config. + */ +class TemplateConfig { + #templateFormats; + #runMode; + #configManuallyDefined = false; + /** @type {UserConfig} */ + #userConfig = new UserConfig(); + + constructor(customRootConfig, projectConfigPath) { + /** @type {object} */ + this.overrides = {}; + + /** + * @type {String} + * @description Path to local project config. + * @default .eleventy.js + */ + if (projectConfigPath !== undefined) { + this.#configManuallyDefined = true; + + if (!projectConfigPath) { + // falsy skips config files + this.projectConfigPaths = []; + } else { + this.projectConfigPaths = [projectConfigPath]; + } + } else { + this.projectConfigPaths = [ + ".eleventy.js", + "eleventy.config.js", + "eleventy.config.mjs", + "eleventy.config.cjs", + ]; + } + + if (customRootConfig) { + /** + * @type {object} + * @description Custom root config. + */ + this.customRootConfig = customRootConfig; + debug("Warning: Using custom root config!"); + } else { + this.customRootConfig = null; + } + + this.hasConfigMerged = false; + this.isEsm = false; + } + + get userConfig() { + return this.#userConfig; + } + + get aggregateBenchmark() { + return this.userConfig.benchmarks.aggregate; + } + + /* Setter for Logger */ + setLogger(logger) { + this.logger = logger; + this.userConfig.logger = this.logger; + } + + /* Setter for Directories instance */ + setDirectories(directories) { + this.directories = directories; + this.userConfig.directories = directories.getUserspaceInstance(); + } + + /* Setter for TemplateFormats instance */ + setTemplateFormats(templateFormats) { + this.#templateFormats = templateFormats; + } + + get templateFormats() { + if (!this.#templateFormats) { + this.#templateFormats = new ProjectTemplateFormats(); + } + return this.#templateFormats; + } + + /* Backwards compat */ + get inputDir() { + return this.directories.input; + } + + setRunMode(runMode) { + this.#runMode = runMode; + } + + shouldSpiderJavaScriptDependencies() { + // not for a standard build + return ( + (this.#runMode === "watch" || this.#runMode === "serve") && + this.userConfig.watchJavaScriptDependencies + ); + } + + /** + * Normalises local project config file path. + * + * @method + * @returns {String|undefined} - The normalised local project config file path. + */ + getLocalProjectConfigFile() { + let configFiles = this.getLocalProjectConfigFiles(); + // Add the configFiles[0] in case of a test, where no file exists on the file system + let configFile = configFiles.find((path) => path && fs.existsSync(path)) || configFiles[0]; + if (configFile) { + return configFile; + } + } + + getLocalProjectConfigFiles() { + if (this.projectConfigPaths?.length > 0) { + return TemplatePath.addLeadingDotSlashArray(this.projectConfigPaths.filter((path) => path)); + } + return []; + } + + setProjectUsingEsm(isEsmProject) { + this.isEsm = !!isEsmProject; + this.usesGraph.setIsEsm(isEsmProject); + } + + getIsProjectUsingEsm() { + return this.isEsm; + } + + /** + * Resets the configuration. + */ + async reset() { + debugDev("Resetting configuration: TemplateConfig and UserConfig."); + this.userConfig.reset(); + // await this.initializeRootConfig(); + await this.forceReloadConfig(); + this.usesGraph.reset(); + + // Clear the compile cache + eventBus.emit("eleventy.compileCacheReset"); + } + + /** + * Resets the configuration while in watch mode. + * + * @todo Add implementation. + */ + resetOnWatch() { + // nothing yet + } + + hasInitialized() { + return this.hasConfigMerged; + } + + /** + * Async-friendly init method + */ + async init(overrides) { + await this.initializeRootConfig(); + + if (overrides) { + this.appendToRootConfig(overrides); + } + + this.config = await this.mergeConfig(); + this.hasConfigMerged = true; + } + + /** + * Force a reload of the configuration object. + */ + async forceReloadConfig() { + this.hasConfigMerged = false; + await this.init(); + } + + /** + * Returns the config object. + * + * @returns {{}} - The config object. + */ + getConfig() { + if (!this.hasConfigMerged) { + throw new Error("Invalid call to .getConfig(). Needs an .init() first."); + } + + return this.config; + } + + /** + * Overwrites the config path. + * + * @param {String} path - The new config path. + */ + async setProjectConfigPath(path) { + this.#configManuallyDefined = true; + + if (path !== undefined) { + this.projectConfigPaths = [path]; + } else { + this.projectConfigPaths = []; + } + + if (this.hasConfigMerged) { + // merge it again + debugDev("Merging in getConfig again after setting the local project config path."); + await this.forceReloadConfig(); + } + } + + /** + * Overwrites the path prefix. + * + * @param {String} pathPrefix - The new path prefix. + */ + setPathPrefix(pathPrefix) { + if (pathPrefix && pathPrefix !== "/") { + debug("Setting pathPrefix to %o", pathPrefix); + this.overrides.pathPrefix = pathPrefix; + } + } + + /** + * Gets the current path prefix denoting the root folder the output will be deployed to + * + * @returns {String} - The path prefix string + */ + getPathPrefix() { + if (this.overrides.pathPrefix) { + return this.overrides.pathPrefix; + } + + if (!this.hasConfigMerged) { + throw new Error("Config has not yet merged. Needs `init()`."); + } + + return this.config?.pathPrefix; + } + + /** + * Bootstraps the config object. + */ + async initializeRootConfig() { + this.rootConfig = this.customRootConfig; + if (!this.rootConfig) { + let { default: cfg } = await EleventyImportRawFromEleventy("./src/defaultConfig.js"); + this.rootConfig = cfg; + } + + if (typeof this.rootConfig === "function") { + // Not yet using async in defaultConfig.js + this.rootConfig = this.rootConfig.call(this, this.userConfig); + } + + debug("Default Eleventy config %o", this.rootConfig); + } + + /* + * Add additional overrides to the root config object, used for testing + * + * @param {object} - a subset of the return Object from the user’s config file. + */ + appendToRootConfig(obj) { + Object.assign(this.rootConfig, obj); + } + + /* + * Process the userland plugins from the Config + * + * @param {object} - the return Object from the user’s config file. + */ + async processPlugins({ dir, pathPrefix }) { + this.userConfig.dir = dir; + this.userConfig.pathPrefix = pathPrefix; + + // for Nested addPlugin calls, Issue #1925 + this.userConfig._enablePluginExecution(); + + let storedActiveNamespace = this.userConfig.activeNamespace; + for (let { plugin, options, pluginNamespace } of this.userConfig.plugins) { + try { + this.userConfig.activeNamespace = pluginNamespace; + await this.userConfig._executePlugin(plugin, options); + } catch (e) { + let name = this.userConfig._getPluginName(plugin); + let namespaces = [storedActiveNamespace, pluginNamespace].filter((entry) => !!entry); + + let namespaceStr = ""; + if (namespaces.length) { + namespaceStr = ` (namespace: ${namespaces.join(".")})`; + } + + throw new EleventyPluginError( + `Error processing ${name ? `the \`${name}\`` : "a"} plugin${namespaceStr}`, + e, + ); + } + } + + this.userConfig.activeNamespace = storedActiveNamespace; + + this.userConfig._disablePluginExecution(); + } + + /** + * Fetches and executes the local configuration file + * + * @returns {Promise} merged - The merged config file object. + */ + async requireLocalConfigFile() { + let localConfig = {}; + let exportedConfig = {}; + + let path = this.projectConfigPaths.filter((path) => path).find((path) => fs.existsSync(path)); + + if (this.projectConfigPaths.length > 0 && this.#configManuallyDefined && !path) { + throw new EleventyConfigError( + "A configuration file was specified but not found: " + this.projectConfigPaths.join(", "), + ); + } + + debug(`Merging default config with ${path}`); + if (path) { + try { + let { default: configDefaultReturn, config: exportedConfigObject } = + await EleventyImportRaw(path, this.isEsm ? "esm" : "cjs"); + + exportedConfig = exportedConfigObject || {}; + + if (this.directories && Object.keys(exportedConfigObject?.dir || {}).length > 0) { + debug( + "Setting directories via `config.dir` export from config file: %o", + exportedConfigObject.dir, + ); + this.directories.setViaConfigObject(exportedConfigObject.dir); + } + + if (typeof configDefaultReturn === "function") { + localConfig = await configDefaultReturn(this.userConfig); + } else { + localConfig = configDefaultReturn; + } + + // Removed a check for `filters` in 3.0.0-alpha.6 (now using addTransform instead) https://v3.11ty.dev/docs/config/#transforms + } catch (err) { + let isModuleError = + err instanceof Error && (err?.message || "").includes("Cannot find module"); + + // TODO the error message here is bad and I feel bad (needs more accurate info) + return Promise.reject( + new EleventyConfigError( + `Error in your Eleventy config file '${path}'.` + + (isModuleError ? chalk.cyan(" You may need to run `npm install`.") : ""), + err, + ), + ); + } + } else { + debug( + "Project config file not found (not an error—skipping). Looked in: %o", + this.projectConfigPaths, + ); + } + + return { + localConfig, + exportedConfig, + }; + } + + /** + * Merges different config files together. + * + * @returns {Promise} merged - The merged config file. + */ + async mergeConfig() { + let { localConfig, exportedConfig } = await this.requireLocalConfigFile(); + + // Merge `export const config = {}` with `return {}` in config callback + if (isPlainObject(exportedConfig)) { + localConfig = Merge(localConfig || {}, exportedConfig); + } + + if (this.directories) { + if (Object.keys(this.userConfig.directoryAssignments || {}).length > 0) { + debug( + "Setting directories via set*Directory configuration APIs %o", + this.userConfig.directoryAssignments, + ); + this.directories.setViaConfigObject(this.userConfig.directoryAssignments); + } + + if (localConfig && Object.keys(localConfig?.dir || {}).length > 0) { + debug( + "Setting directories via `dir` object return from configuration file: %o", + localConfig.dir, + ); + this.directories.setViaConfigObject(localConfig.dir); + } + } + + // `templateFormats` is an override via `setTemplateFormats` + if (this.userConfig?.templateFormats) { + this.templateFormats.setViaConfig(this.userConfig.templateFormats); + } else if (localConfig?.templateFormats || this.rootConfig?.templateFormats) { + // Local project config or defaultConfig.js + this.templateFormats.setViaConfig( + localConfig.templateFormats || this.rootConfig?.templateFormats, + ); + } + + // `templateFormatsAdded` is additive via `addTemplateFormats` + if (this.userConfig?.templateFormatsAdded) { + this.templateFormats.addViaConfig(this.userConfig.templateFormatsAdded); + } + + let mergedConfig = Merge({}, this.rootConfig, localConfig); + + // Setup a few properties for plugins: + + // Set frozen templateFormats + mergedConfig.templateFormats = Object.freeze(this.templateFormats.getTemplateFormats()); + + // Setup pathPrefix set via command line for plugin consumption + if (this.overrides.pathPrefix) { + mergedConfig.pathPrefix = this.overrides.pathPrefix; + } + + // Returning a falsy value (e.g. "") from user config should reset to the default value. + if (!mergedConfig.pathPrefix) { + mergedConfig.pathPrefix = this.rootConfig.pathPrefix; + } + + // This is not set in UserConfig.js so that getters aren’t converted to strings + // We want to error if someone attempts to use a setter there. + if (this.directories) { + mergedConfig.directories = this.directories.getUserspaceInstance(); + } + + // Delay processing plugins until after the result of localConfig is returned + // But BEFORE the rest of the config options are merged + // this way we can pass directories and other template information to plugins + + await this.userConfig.events.emit("eleventy.beforeConfig", this.userConfig); + + let pluginsBench = this.aggregateBenchmark.get("Processing plugins in config"); + pluginsBench.before(); + await this.processPlugins(mergedConfig); + pluginsBench.after(); + + // Template formats added via plugins + if (this.userConfig?.templateFormatsAdded) { + this.templateFormats.addViaConfig(this.userConfig.templateFormatsAdded); + mergedConfig.templateFormats = Object.freeze(this.templateFormats.getTemplateFormats()); + } + + let eleventyConfigApiMergingObject = this.userConfig.getMergingConfigObject(); + + if ("templateFormats" in eleventyConfigApiMergingObject) { + throw new Error( + "Internal error: templateFormats should not return from `getMergingConfigObject`", + ); + } + + // Overrides are only used by pathPrefix + debug("Configuration overrides: %o", this.overrides); + Merge(mergedConfig, eleventyConfigApiMergingObject, this.overrides); + + debug("Current configuration: %o", mergedConfig); + + // Add to the merged config too + mergedConfig.uses = this.usesGraph; + + // this is used for the layouts event + this.usesGraph.setConfig(mergedConfig); + + return mergedConfig; + } + + get usesGraph() { + if (!this._usesGraph) { + this._usesGraph = new GlobalDependencyMap(); + this._usesGraph.setIsEsm(this.isEsm); + this._usesGraph.setTemplateConfig(this); + } + return this._usesGraph; + } + + get uses() { + if (!this.usesGraph) { + throw new Error("The Eleventy Global Dependency Graph has not yet been initialized."); + } + return this.usesGraph; + } + + get existsCache() { + if (!this._existsCache) { + this._existsCache = new ExistsCache(); + this._existsCache.setDirectoryCheck(true); + } + return this._existsCache; + } +} + +export default TemplateConfig; diff --git a/node_modules/@11ty/eleventy/src/TemplateContent.js b/node_modules/@11ty/eleventy/src/TemplateContent.js new file mode 100644 index 0000000..db3b641 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateContent.js @@ -0,0 +1,712 @@ +import os from "node:os"; + +import fs from "graceful-fs"; +import matter from "gray-matter"; +import lodash from "@11ty/lodash-custom"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; +import chardet from "chardet"; + +import EleventyExtensionMap from "./EleventyExtensionMap.js"; +import TemplateData from "./Data/TemplateData.js"; +import TemplateRender from "./TemplateRender.js"; +import EleventyBaseError from "./Errors/EleventyBaseError.js"; +import EleventyErrorUtil from "./Errors/EleventyErrorUtil.js"; +import eventBus from "./EventBus.js"; + +const { set: lodashSet } = lodash; +const debug = debugUtil("Eleventy:TemplateContent"); +const debugDiagnostic = debugUtil("Eleventy:Diagnostics"); +const debugDev = debugUtil("Dev:Eleventy:TemplateContent"); + +class TemplateContentConfigError extends EleventyBaseError {} +class TemplateContentFrontMatterError extends EleventyBaseError {} +class TemplateContentCompileError extends EleventyBaseError {} +class TemplateContentRenderError extends EleventyBaseError {} + +class TemplateContent { + constructor(inputPath, templateConfig) { + if (!templateConfig || templateConfig.constructor.name !== "TemplateConfig") { + throw new TemplateContentConfigError( + "Missing or invalid `templateConfig` argument to TemplateContent", + ); + } + this.eleventyConfig = templateConfig; + this.inputPath = inputPath; + } + + get dirs() { + return this.eleventyConfig.directories; + } + + get inputDir() { + return this.dirs.input; + } + + get outputDir() { + return this.dirs.output; + } + + getResetTypes(types) { + if (types) { + return Object.assign( + { + data: false, + read: false, + render: false, + }, + types, + ); + } + + return { + data: true, + read: true, + render: true, + }; + } + + // Called during an incremental build when the template instance is cached but needs to be reset because it has changed + resetCaches(types) { + types = this.getResetTypes(types); + + if (types.read) { + delete this.readingPromise; + delete this.inputContent; + delete this._frontMatterDataCache; + } + } + + /* Used by tests */ + get extensionMap() { + if (!this._extensionMap) { + this._extensionMap = new EleventyExtensionMap(this.eleventyConfig); + this._extensionMap.setFormats([]); + } + return this._extensionMap; + } + + set extensionMap(map) { + this._extensionMap = map; + } + + set eleventyConfig(config) { + this._config = config; + + if (this._config.constructor.name === "TemplateConfig") { + this._configOptions = this._config.getConfig(); + } else { + throw new TemplateContentConfigError("Tried to get an TemplateConfig but none was found."); + } + } + + get eleventyConfig() { + if (this._config.constructor.name === "TemplateConfig") { + return this._config; + } + throw new TemplateContentConfigError("Tried to get an TemplateConfig but none was found."); + } + + get config() { + if (this._config.constructor.name === "TemplateConfig" && !this._configOptions) { + this._configOptions = this._config.getConfig(); + } + + return this._configOptions; + } + + get bench() { + return this.config.benchmarkManager.get("Aggregate"); + } + + get engine() { + return this.templateRender.engine; + } + + get templateRender() { + if (!this.hasTemplateRender()) { + throw new Error(`\`templateRender\` has not yet initialized on ${this.inputPath}`); + } + + return this._templateRender; + } + + hasTemplateRender() { + return !!this._templateRender; + } + + async getTemplateRender() { + if (!this._templateRender) { + this._templateRender = new TemplateRender(this.inputPath, this.eleventyConfig); + this._templateRender.extensionMap = this.extensionMap; + await this._templateRender.init(); + } + + return this._templateRender; + } + + // For monkey patchers + get frontMatter() { + if (this.frontMatterOverride) { + return this.frontMatterOverride; + } else { + throw new Error( + "Unfortunately you’re using code that monkey patched some Eleventy internals and it isn’t async-friendly. Change your code to use the async `read()` method on the template instead!", + ); + } + } + + // For monkey patchers + set frontMatter(contentOverride) { + this.frontMatterOverride = contentOverride; + } + + getInputPath() { + return this.inputPath; + } + + getInputDir() { + return this.inputDir; + } + + isVirtualTemplate() { + let def = this.getVirtualTemplateDefinition(); + return !!def; + } + + getVirtualTemplateDefinition() { + let inputDirRelativeInputPath = + this.eleventyConfig.directories.getInputPathRelativeToInputDirectory(this.inputPath); + return this.config.virtualTemplates[inputDirRelativeInputPath]; + } + + async #read() { + let content = await this.inputContent; + + if (content || content === "") { + if (this.engine.useJavaScriptImport()) { + return { + data: {}, + content, + }; + } + + let options = this.config.frontMatterParsingOptions || {}; + let fm; + try { + // Added in 3.0, passed along to front matter engines + options.filePath = this.inputPath; + fm = matter(content, options); + } catch (e) { + throw new TemplateContentFrontMatterError( + `Having trouble reading front matter from template ${this.inputPath}`, + e, + ); + } + + if (options.excerpt && fm.excerpt) { + let excerptString = fm.excerpt + (options.excerpt_separator || "---"); + if (fm.content.startsWith(excerptString + os.EOL)) { + // with an os-specific newline after excerpt separator + fm.content = fm.excerpt.trim() + "\n" + fm.content.slice((excerptString + os.EOL).length); + } else if (fm.content.startsWith(excerptString + "\n")) { + // with a newline (\n) after excerpt separator + // This is necessary for some git configurations on windows + fm.content = fm.excerpt.trim() + "\n" + fm.content.slice((excerptString + 1).length); + } else if (fm.content.startsWith(excerptString)) { + // no newline after excerpt separator + fm.content = fm.excerpt + fm.content.slice(excerptString.length); + } + + // alias, defaults to page.excerpt + let alias = options.excerpt_alias || "page.excerpt"; + lodashSet(fm.data, alias, fm.excerpt); + } + + // For monkey patchers that used `frontMatter` 🤧 + // https://github.com/11ty/eleventy/issues/613#issuecomment-999637109 + // https://github.com/11ty/eleventy/issues/2710#issuecomment-1373854834 + // Removed this._frontMatter monkey patcher help in 3.0.0-alpha.7 + + return fm; + } else { + return { + data: {}, + content: "", + excerpt: "", + }; + } + } + + async read() { + if (!this.readingPromise) { + if (!this.inputContent) { + // @cachedproperty + this.inputContent = this.getInputContent(); + } + + // @cachedproperty + this.readingPromise = this.#read(); + } + + return this.readingPromise; + } + + /* Incremental builds cache the Template instances (in TemplateWriter) but + * these template specific caches are important for Pagination */ + static cache(path, content) { + this._inputCache.set(TemplatePath.absolutePath(path), content); + } + + static getCached(path) { + return this._inputCache.get(TemplatePath.absolutePath(path)); + } + + static deleteFromInputCache(path) { + this._inputCache.delete(TemplatePath.absolutePath(path)); + } + + // Used via clone + setInputContent(content) { + this.inputContent = content; + } + + async getInputContent() { + let tr = await this.getTemplateRender(); + + let virtualTemplateDefinition = this.getVirtualTemplateDefinition(); + if (virtualTemplateDefinition) { + let { content } = virtualTemplateDefinition; + return content; + } + + if ( + tr.engine.useJavaScriptImport() && + typeof tr.engine.getInstanceFromInputPath === "function" + ) { + return tr.engine.getInstanceFromInputPath(this.inputPath); + } + + if (!tr.engine.needsToReadFileContents()) { + return ""; + } + + let templateBenchmark = this.bench.get("Template Read"); + templateBenchmark.before(); + + let content; + + if (this.config.useTemplateCache) { + content = TemplateContent.getCached(this.inputPath); + } + + if (!content && content !== "") { + let contentBuffer = fs.readFileSync(this.inputPath); + + if (process.env.DEBUG) { + // Warning: this is slow!! + let encoding = chardet.detect(contentBuffer); + + if (encoding.startsWith("UTF-16")) { + debug("Warning: %o encoding detected on %o.", encoding, this.inputPath); + debugDiagnostic( + "%o encoding detected on %o. Please re-save as UTF-8.", + encoding, + this.inputPath, + ); + } else { + debug("%o encoding detected on %o.", encoding, this.inputPath); + } + } + + content = contentBuffer.toString("utf8"); + + if (this.config.useTemplateCache) { + TemplateContent.cache(this.inputPath, content); + } + } + + templateBenchmark.after(); + + return content; + } + + async _testGetFrontMatter() { + let fm = this.frontMatterOverride ? this.frontMatterOverride : await this.read(); + + return fm; + } + + async getPreRender() { + let fm = this.frontMatterOverride ? this.frontMatterOverride : await this.read(); + + return fm.content; + } + + async #getFrontMatterData() { + let fm = await this.read(); + + // gray-matter isn’t async-friendly but can return a promise from custom front matter + if (fm.data instanceof Promise) { + fm.data = await fm.data; + } + + let extraData = await this.engine.getExtraDataFromFile(this.inputPath); + + let virtualTemplateDefinition = this.getVirtualTemplateDefinition(); + let virtualTemplateData; + if (virtualTemplateDefinition) { + virtualTemplateData = virtualTemplateDefinition.data; + } + + let data = TemplateData.mergeDeep(false, fm.data, extraData, virtualTemplateData); + let cleanedData = TemplateData.cleanupData(data); + + return { + data: cleanedData, + excerpt: fm.excerpt, + }; + } + + async getFrontMatterData() { + if (!this._frontMatterDataCache) { + // @cachedproperty + this._frontMatterDataCache = this.#getFrontMatterData(); + } + + return this._frontMatterDataCache; + } + + async getEngineOverride() { + let { data: frontMatterData } = await this.getFrontMatterData(); + return frontMatterData[this.config.keys.engineOverride]; + } + + _getCompileCache(str) { + // Caches used to be bifurcated based on engine name, now they’re based on inputPath + let inputPathMap = TemplateContent._compileCache.get(this.inputPath); + if (!inputPathMap) { + inputPathMap = new Map(); + TemplateContent._compileCache.set(this.inputPath, inputPathMap); + } + + let cacheable = this.engine.cacheable; + let { useCache, key } = this.engine.getCompileCacheKey(str, this.inputPath); + + // We also tie the compile cache key to the UserConfig instance, to alleviate issues with global template cache + // Better to move the cache to the Eleventy instance instead, no? + // (This specifically failed I18nPluginTest cases with filters being cached across tests and not having access to each plugin’s options) + key = this.eleventyConfig.userConfig._getUniqueId() + key; + + return [cacheable, key, inputPathMap, useCache]; + } + + async compile(str, options = {}) { + let { type, bypassMarkdown, engineOverride } = options; + + let tr = await this.getTemplateRender(); + + if (engineOverride !== undefined) { + debugDev("%o overriding template engine to use %o", this.inputPath, engineOverride); + await tr.setEngineOverride(engineOverride, bypassMarkdown); + } else { + tr.setUseMarkdown(!bypassMarkdown); + } + + if (bypassMarkdown && !this.engine.needsCompilation(str)) { + return function () { + return str; + }; + } + + debugDev("%o compile() using engine: %o", this.inputPath, tr.engineName); + + try { + let res; + if (this.config.useTemplateCache) { + let [cacheable, key, cache, useCache] = this._getCompileCache(str); + if (cacheable && key) { + if (useCache && cache.has(key)) { + this.bench.get("(count) Template Compile Cache Hit").incrementCount(); + return cache.get(key); + } + + this.bench.get("(count) Template Compile Cache Miss").incrementCount(); + + // Compile cache is cleared when the resource is modified (below) + + // Compilation is async, so we eagerly cache a Promise that eventually + // resolves to the compiled function + cache.set( + key, + new Promise((resolve) => { + res = resolve; + }), + ); + } + } + + let typeStr = type ? ` ${type}` : ""; + let templateBenchmark = this.bench.get(`Template Compile${typeStr}`); + let inputPathBenchmark = this.bench.get(`> Compile${typeStr} > ${this.inputPath}`); + templateBenchmark.before(); + inputPathBenchmark.before(); + let fn = await tr.getCompiledTemplate(str); + inputPathBenchmark.after(); + templateBenchmark.after(); + debugDev("%o getCompiledTemplate function created", this.inputPath); + if (this.config.useTemplateCache && res) { + res(fn); + } + return fn; + } catch (e) { + let [cacheable, key, cache] = this._getCompileCache(str); + if (cacheable && key) { + cache.delete(key); + } + debug(`Having trouble compiling template ${this.inputPath}: %O`, str); + throw new TemplateContentCompileError( + `Having trouble compiling template ${this.inputPath}`, + e, + ); + } + } + + getParseForSymbolsFunction(str) { + let engine = this.engine; + + // Don’t use markdown as the engine to parse for symbols + // TODO pass in engineOverride here + let preprocessorEngine = this.templateRender.getPreprocessorEngine(); + if (preprocessorEngine && engine.getName() !== preprocessorEngine) { + let replacementEngine = this.templateRender.getEngineByName(preprocessorEngine); + if (replacementEngine) { + engine = replacementEngine; + } + } + + if ("parseForSymbols" in engine) { + return () => { + return engine.parseForSymbols(str); + }; + } + } + + // used by computed data or for permalink functions + async _renderFunction(fn, ...args) { + let mixins = Object.assign({}, this.config.javascriptFunctions); + let result = await fn.call(mixins, ...args); + + // normalize Buffer away if returned from permalink + if (Buffer.isBuffer(result)) { + return result.toString(); + } + + return result; + } + + async renderComputedData(str, data) { + if (typeof str === "function") { + return this._renderFunction(str, data); + } + + return this._render(str, data, { + type: "Computed Data", + bypassMarkdown: true, + }); + } + + async renderPermalink(permalink, data) { + let permalinkCompilation = this.engine.permalinkNeedsCompilation(permalink); + + // No string compilation: + // ({ compileOptions: { permalink: "raw" }}) + // These mean `permalink: false`, which is no file system writing: + // ({ compileOptions: { permalink: false }}) + // ({ compileOptions: { permalink: () => false }}) + // ({ compileOptions: { permalink: () => (() = > false) }}) + if (permalinkCompilation === false) { + return permalink; + } + + /* Custom `compile` function for permalinks, usage: + permalink: function(permalinkString, inputPath) { + return async function(data) { + return "THIS IS MY RENDERED PERMALINK"; + } + } + */ + if (permalinkCompilation && typeof permalinkCompilation === "function") { + permalink = await this._renderFunction(permalinkCompilation, permalink, this.inputPath); + } + + // Raw permalink function (in the app code data cascade) + if (typeof permalink === "function") { + return this._renderFunction(permalink, data); + } + + return this._render(permalink, data, { + type: "Permalink", + bypassMarkdown: true, + }); + } + + async render(str, data, bypassMarkdown) { + return this._render(str, data, { + bypassMarkdown, + type: "", + }); + } + + _getPaginationLogSuffix(data) { + let suffix = []; + if ("pagination" in data) { + suffix.push(" ("); + if (data.pagination.pages) { + suffix.push( + `${data.pagination.pages.length} page${data.pagination.pages.length !== 1 ? "s" : ""}`, + ); + } else { + suffix.push("Pagination"); + } + suffix.push(")"); + } + return suffix.join(""); + } + + async _render(str, data, options = {}) { + let { bypassMarkdown, type } = options; + + try { + if (bypassMarkdown && !this.engine.needsCompilation(str)) { + return str; + } + + let fn = await this.compile(str, { + bypassMarkdown, + engineOverride: data[this.config.keys.engineOverride], + type, + }); + + if (fn === undefined) { + return; + } else if (typeof fn !== "function") { + throw new Error(`The \`compile\` function did not return a function. Received ${fn}`); + } + + // Benchmark + let templateBenchmark = this.bench.get("Render"); + let inputPathBenchmark = this.bench.get( + `> Render${type ? ` ${type}` : ""} > ${this.inputPath}${this._getPaginationLogSuffix(data)}`, + ); + + templateBenchmark.before(); + if (inputPathBenchmark) { + inputPathBenchmark.before(); + } + + let rendered = await fn(data); + + if (inputPathBenchmark) { + inputPathBenchmark.after(); + } + templateBenchmark.after(); + debugDev("%o getCompiledTemplate called, rendered content created", this.inputPath); + return rendered; + } catch (e) { + if (EleventyErrorUtil.isPrematureTemplateContentError(e)) { + return Promise.reject(e); + } else { + let tr = await this.getTemplateRender(); + let engine = tr.getReadableEnginesList(); + debug(`Having trouble rendering ${engine} template ${this.inputPath}: %O`, str); + return Promise.reject( + new TemplateContentRenderError( + `Having trouble rendering ${engine} template ${this.inputPath}`, + e, + ), + ); + } + } + } + + getExtensionEntries() { + return this.engine.extensionEntries; + } + + isFileRelevantToThisTemplate(incrementalFile, metadata = {}) { + // always relevant if incremental file not set (build everything) + if (!incrementalFile) { + return true; + } + + let hasDependencies = this.engine.hasDependencies(incrementalFile); + + let isRelevant = this.engine.isFileRelevantTo(this.inputPath, incrementalFile); + + debug( + "Test dependencies to see if %o is relevant to %o: %o", + this.inputPath, + incrementalFile, + isRelevant, + ); + + let extensionEntries = this.getExtensionEntries().filter((entry) => !!entry.isIncrementalMatch); + if (extensionEntries.length) { + for (let entry of extensionEntries) { + if ( + entry.isIncrementalMatch.call( + { + inputPath: this.inputPath, + isFullTemplate: metadata.isFullTemplate, + isFileRelevantToInputPath: isRelevant, + doesFileHaveDependencies: hasDependencies, + }, + incrementalFile, + ) + ) { + return true; + } + } + + return false; + } else { + // Not great way of building all templates if this is a layout, include, JS dependency. + // TODO improve this for default template syntaxes + + // This is the fallback way of determining if something is incremental (no isIncrementalMatch available) + // This will be true if the inputPath and incrementalFile are the same + if (isRelevant) { + return true; + } + + // only return true here if dependencies are not known + if (!hasDependencies && !metadata.isFullTemplate) { + return true; + } + } + + return false; + } +} + +TemplateContent._inputCache = new Map(); +TemplateContent._compileCache = new Map(); +eventBus.on("eleventy.resourceModified", (path) => { + // delete from input cache + TemplateContent.deleteFromInputCache(path); + + // delete from compile cache + let normalized = TemplatePath.addLeadingDotSlash(path); + let compileCache = TemplateContent._compileCache.get(normalized); + if (compileCache) { + compileCache.clear(); + } +}); + +// Used when the configuration file reset https://github.com/11ty/eleventy/issues/2147 +eventBus.on("eleventy.compileCacheReset", (/*path*/) => { + TemplateContent._compileCache = new Map(); +}); + +export default TemplateContent; diff --git a/node_modules/@11ty/eleventy/src/TemplateFileSlug.js b/node_modules/@11ty/eleventy/src/TemplateFileSlug.js new file mode 100644 index 0000000..03c9a29 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateFileSlug.js @@ -0,0 +1,57 @@ +import path from "node:path"; +import { TemplatePath } from "@11ty/eleventy-utils"; + +class TemplateFileSlug { + constructor(inputPath, extensionMap, eleventyConfig) { + let inputDir = eleventyConfig.directories.input; + if (inputDir) { + inputPath = TemplatePath.stripLeadingSubPath(inputPath, inputDir); + } + + this.inputPath = inputPath; + this.cleanInputPath = inputPath.replace(/^.\//, ""); + + let dirs = this.cleanInputPath.split("/"); + this.dirs = dirs; + this.dirs.pop(); + + this.parsed = path.parse(inputPath); + this.filenameNoExt = extensionMap.removeTemplateExtension(this.parsed.base); + } + + // `page.filePathStem` see https://v3.11ty.dev/docs/data-eleventy-supplied/#page-variable + getFullPathWithoutExtension() { + return "/" + TemplatePath.join(...this.dirs, this._getRawSlug()); + } + + _getRawSlug() { + let slug = this.filenameNoExt; + return this._stripDateFromSlug(slug); + } + + /** Removes dates in the format of YYYY-MM-DD from a given slug string candidate. */ + _stripDateFromSlug(slug) { + let reg = slug.match(/\d{4}-\d{2}-\d{2}-(.*)/); + if (reg) { + return reg[1]; + } + return slug; + } + + // `page.fileSlug` see https://v3.11ty.dev/docs/data-eleventy-supplied/#page-variable + getSlug() { + let rawSlug = this._getRawSlug(); + + if (rawSlug === "index") { + if (!this.dirs.length) { + return ""; + } + let lastDir = this.dirs[this.dirs.length - 1]; + return this._stripDateFromSlug(lastDir); + } + + return rawSlug; + } +} + +export default TemplateFileSlug; diff --git a/node_modules/@11ty/eleventy/src/TemplateGlob.js b/node_modules/@11ty/eleventy/src/TemplateGlob.js new file mode 100644 index 0000000..9db85e9 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateGlob.js @@ -0,0 +1,35 @@ +import { TemplatePath } from "@11ty/eleventy-utils"; + +class TemplateGlob { + static normalizePath(...paths) { + if (paths[0].charAt(0) === "!") { + throw new Error( + `TemplateGlob.normalizePath does not accept ! glob paths like: ${paths.join("")}`, + ); + } + return TemplatePath.addLeadingDotSlash(TemplatePath.join(...paths)); + } + + static normalize(path) { + path = path.trim(); + if (path.charAt(0) === "!") { + return "!" + TemplateGlob.normalizePath(path.slice(1)); + } else { + return TemplateGlob.normalizePath(path); + } + } + + static map(files) { + if (typeof files === "string") { + return TemplateGlob.normalize(files); + } else if (Array.isArray(files)) { + return files.map(function (path) { + return TemplateGlob.normalize(path); + }); + } else { + return files; + } + } +} + +export default TemplateGlob; diff --git a/node_modules/@11ty/eleventy/src/TemplateLayout.js b/node_modules/@11ty/eleventy/src/TemplateLayout.js new file mode 100644 index 0000000..a58436d --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateLayout.js @@ -0,0 +1,242 @@ +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import TemplateLayoutPathResolver from "./TemplateLayoutPathResolver.js"; +import TemplateContent from "./TemplateContent.js"; +import TemplateData from "./Data/TemplateData.js"; +import templateCache from "./TemplateCache.js"; + +// const debug = debugUtil("Eleventy:TemplateLayout"); +const debugDev = debugUtil("Dev:Eleventy:TemplateLayout"); + +class TemplateLayout extends TemplateContent { + constructor(key, extensionMap, eleventyConfig) { + if (!eleventyConfig || eleventyConfig.constructor.name !== "TemplateConfig") { + throw new Error("Expected `eleventyConfig` in TemplateLayout constructor."); + } + + let resolver = new TemplateLayoutPathResolver(key, extensionMap, eleventyConfig); + let resolvedPath = resolver.getFullPath(); + + super(resolvedPath, eleventyConfig); + + if (!extensionMap) { + throw new Error("Expected `extensionMap` in TemplateLayout constructor."); + } + + this.extensionMap = extensionMap; + this.key = resolver.getNormalizedLayoutKey(); + this.dataKeyLayoutPath = key; + this.inputPath = resolvedPath; + } + + getKey() { + return this.key; + } + + getFullKey() { + return TemplateLayout.resolveFullKey(this.dataKeyLayoutPath, this.inputDir); + } + + getCacheKeys() { + return new Set([this.dataKeyLayoutPath, this.getFullKey(), this.key]); + } + + static resolveFullKey(key, inputDir) { + return TemplatePath.join(inputDir, key); + } + + static getTemplate(key, eleventyConfig, extensionMap) { + let config = eleventyConfig.getConfig(); + if (!config.useTemplateCache) { + return new TemplateLayout(key, extensionMap, eleventyConfig); + } + + let inputDir = eleventyConfig.directories.input; + let fullKey = TemplateLayout.resolveFullKey(key, inputDir); + if (!templateCache.has(fullKey)) { + let layout = new TemplateLayout(key, extensionMap, eleventyConfig); + + templateCache.add(layout); + debugDev("Added %o to TemplateCache", key); + + return layout; + } + + return templateCache.get(fullKey); + } + + async getTemplateLayoutMapEntry() { + let { data: frontMatterData } = await this.getFrontMatterData(); + return { + // Used by `TemplateLayout.getTemplate()` + key: this.dataKeyLayoutPath, + + // used by `this.getData()` + frontMatterData, + }; + } + + async #getTemplateLayoutMap() { + // For both the eleventy.layouts event and cyclical layout chain checking (e.g., a => b => c => a) + let layoutChain = new Set(); + layoutChain.add(this.inputPath); + + let cfgKey = this.config.keys.layout; + let map = []; + let mapEntry = await this.getTemplateLayoutMapEntry(); + + map.push(mapEntry); + + while (mapEntry.frontMatterData && cfgKey in mapEntry.frontMatterData) { + // Layout of the current layout + let parentLayoutKey = mapEntry.frontMatterData[cfgKey]; + + let layout = TemplateLayout.getTemplate( + parentLayoutKey, + this.eleventyConfig, + this.extensionMap, + ); + + // Abort if a circular layout chain is detected. Otherwise, we'll time out and run out of memory. + if (layoutChain.has(layout.inputPath)) { + throw new Error( + `Your layouts have a circular reference, starting at ${map[0].key}! The layout at ${layout.inputPath} was specified twice in this layout chain.`, + ); + } + + // Keep track of this layout so we can detect duplicates in subsequent iterations + layoutChain.add(layout.inputPath); + + // reassign for next loop + mapEntry = await layout.getTemplateLayoutMapEntry(); + + map.push(mapEntry); + } + + this.layoutChain = Array.from(layoutChain); + + return map; + } + + async getTemplateLayoutMap() { + if (!this.cachedLayoutMap) { + this.cachedLayoutMap = this.#getTemplateLayoutMap(); + } + + return this.cachedLayoutMap; + } + + async getLayoutChain() { + if (!Array.isArray(this.layoutChain)) { + await this.getTemplateLayoutMap(); + } + + return this.layoutChain; + } + + async #getData() { + let map = await this.getTemplateLayoutMap(); + let dataToMerge = []; + for (let j = map.length - 1; j >= 0; j--) { + dataToMerge.push(map[j].frontMatterData); + } + + // Deep merge of layout front matter + let data = TemplateData.mergeDeep(this.config.dataDeepMerge, {}, ...dataToMerge); + delete data[this.config.keys.layout]; + + return data; + } + + async getData() { + if (!this.dataCache) { + this.dataCache = this.#getData(); + } + + return this.dataCache; + } + + async #getCachedCompiledLayoutFunction() { + let rawInput = await this.getPreRender(); + let renderFunction = await this.compile(rawInput); + return renderFunction; + } + + // Do only cache this layout’s render function and delegate the rest to the other templates. + async getCachedCompiledLayoutFunction() { + if (!this.cachedCompiledLayoutFunction) { + this.cachedCompiledLayoutFunction = this.#getCachedCompiledLayoutFunction(); + } + + return this.cachedCompiledLayoutFunction; + } + + async getCompiledLayoutFunctions() { + let layoutMap = await this.getTemplateLayoutMap(); + let fns = []; + + try { + fns.push({ + render: await this.getCachedCompiledLayoutFunction(), + }); + + if (layoutMap.length > 1) { + let [, /*currentLayout*/ parentLayout] = layoutMap; + let { key } = parentLayout; + + let layoutTemplate = TemplateLayout.getTemplate( + key, + this.eleventyConfig, + this.extensionMap, + ); + + // The parent already includes the rest of the layout chain + let upstreamFns = await layoutTemplate.getCompiledLayoutFunctions(); + for (let j = 0, k = upstreamFns.length; j < k; j++) { + fns.push(upstreamFns[j]); + } + } + + return fns; + } catch (e) { + debugDev("Clearing TemplateCache after error."); + templateCache.clear(); + throw e; + } + } + + async render() { + throw new Error("Internal error: `render` was removed from TemplateLayout.js in Eleventy 3.0."); + } + + // Inefficient? We want to compile all the templatelayouts into a single reusable callback? + // Trouble: layouts may need data variables present downstream/upstream + // This is called from Template->renderPageEntry + async renderPageEntry(pageEntry) { + let templateContent = pageEntry.templateContent; + let compiledFunctions = await this.getCompiledLayoutFunctions(); + for (let { render } of compiledFunctions) { + let data = { + content: templateContent, + ...pageEntry.data, + }; + + templateContent = await render(data); + } + + // Don’t set `templateContent` on pageEntry because collection items should not have layout markup + return templateContent; + } + + resetCaches(types) { + super.resetCaches(types); + + delete this.dataCache; + delete this.layoutChain; + delete this.cachedLayoutMap; + delete this.cachedCompiledLayoutFunction; + } +} + +export default TemplateLayout; diff --git a/node_modules/@11ty/eleventy/src/TemplateLayoutPathResolver.js b/node_modules/@11ty/eleventy/src/TemplateLayoutPathResolver.js new file mode 100644 index 0000000..32006e1 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateLayoutPathResolver.js @@ -0,0 +1,136 @@ +import fs from "node:fs"; +import { TemplatePath } from "@11ty/eleventy-utils"; +// import debugUtil from "debug"; +// const debug = debugUtil("Eleventy:TemplateLayoutPathResolver"); + +class TemplateLayoutPathResolver { + constructor(path, extensionMap, eleventyConfig) { + if (!eleventyConfig) { + throw new Error("Expected `eleventyConfig` in TemplateLayoutPathResolver constructor"); + } + + this.eleventyConfig = eleventyConfig; + this.originalPath = path; + this.originalDisplayPath = + TemplatePath.join(this.layoutsDir, this.originalPath) + + ` (via \`layout: ${this.originalPath}\`)`; // for error messaging + + this.path = path; + this.aliases = {}; + this.extensionMap = extensionMap; + if (!extensionMap) { + throw new Error("Expected `extensionMap` in TemplateLayoutPathResolver constructor."); + } + + this.init(); + } + + getVirtualTemplate(layoutPath) { + let inputDirRelativePath = + this.eleventyConfig.directories.getLayoutPathRelativeToInputDirectory(layoutPath); + return this.config.virtualTemplates[inputDirRelativePath]; + } + + get dirs() { + return this.eleventyConfig.directories; + } + + get inputDir() { + return this.dirs.input; + } + + get layoutsDir() { + return this.dirs.layouts || this.dirs.includes; + } + + /* Backwards compat */ + getLayoutsDir() { + return this.layoutsDir; + } + + setAliases() { + this.aliases = Object.assign({}, this.config.layoutAliases, this.aliases); + } + + // for testing + set config(cfg) { + this._config = cfg; + this.init(); + } + + get config() { + if (this.eleventyConfig) { + return this.eleventyConfig.getConfig(); + } else { + throw new Error("Missing this.eleventyConfig"); + } + } + + exists(layoutPath) { + if (this.getVirtualTemplate(layoutPath)) { + return true; + } + let fullPath = this.eleventyConfig.directories.getLayoutPath(layoutPath); + if (fs.existsSync(fullPath)) { + return true; + } + return false; + } + + init() { + // we might be able to move this into the constructor? + this.aliases = Object.assign({}, this.config.layoutAliases, this.aliases); + + if (this.aliases[this.path]) { + this.path = this.aliases[this.path]; + } + + let useLayoutResolution = this.config.layoutResolution; + + if (this.path.split(".").length > 0 && this.exists(this.path)) { + this.filename = this.path; + this.fullPath = this.eleventyConfig.directories.getLayoutPath(this.path); + } else if (useLayoutResolution) { + this.filename = this.findFileName(); + this.fullPath = this.eleventyConfig.directories.getLayoutPath(this.filename || ""); + } + } + + addLayoutAlias(from, to) { + this.aliases[from] = to; + } + + getFileName() { + if (!this.filename) { + throw new Error( + `You’re trying to use a layout that does not exist: ${this.originalDisplayPath}`, + ); + } + + return this.filename; + } + + getFullPath() { + if (!this.filename) { + throw new Error( + `You’re trying to use a layout that does not exist: ${this.originalDisplayPath}`, + ); + } + + return this.fullPath; + } + + findFileName() { + for (let filename of this.extensionMap.getFileList(this.path)) { + if (this.exists(filename)) { + return filename; + } + } + } + + getNormalizedLayoutKey() { + return TemplatePath.stripLeadingSubPath(this.fullPath, this.layoutsDir); + } +} + +export default TemplateLayoutPathResolver; diff --git a/node_modules/@11ty/eleventy/src/TemplateMap.js b/node_modules/@11ty/eleventy/src/TemplateMap.js new file mode 100644 index 0000000..3017a0b --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateMap.js @@ -0,0 +1,828 @@ +import { DepGraph as DependencyGraph } from "dependency-graph"; +import { isPlainObject, TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import TemplateCollection from "./TemplateCollection.js"; +import EleventyErrorUtil from "./Errors/EleventyErrorUtil.js"; +import UsingCircularTemplateContentReferenceError from "./Errors/UsingCircularTemplateContentReferenceError.js"; +import EleventyBaseError from "./Errors/EleventyBaseError.js"; +import DuplicatePermalinkOutputError from "./Errors/DuplicatePermalinkOutputError.js"; +import TemplateData from "./Data/TemplateData.js"; + +const debug = debugUtil("Eleventy:TemplateMap"); +const debugDev = debugUtil("Dev:Eleventy:TemplateMap"); + +class TemplateMapConfigError extends EleventyBaseError {} +class EleventyDataSchemaError extends EleventyBaseError {} + +// These template URL filenames are allowed to exclude file extensions +const EXTENSIONLESS_URL_ALLOWLIST = [ + "/_redirects", // Netlify specific + "/.htaccess", // Apache + "/_headers", // Cloudflare +]; + +class TemplateMap { + constructor(eleventyConfig) { + if (!eleventyConfig) { + throw new TemplateMapConfigError("Missing config argument."); + } + this.eleventyConfig = eleventyConfig; + this.map = []; + this.collectionsData = null; + this.cached = false; + this.verboseOutput = true; + this.collection = new TemplateCollection(); + } + + set userConfig(config) { + this._userConfig = config; + } + + get userConfig() { + if (!this._userConfig) { + // TODO use this.config for this, need to add collections to mergeable props in userconfig + this._userConfig = this.eleventyConfig.userConfig; + } + + return this._userConfig; + } + + get config() { + if (!this._config) { + this._config = this.eleventyConfig.getConfig(); + } + return this._config; + } + + static get tagPrefix() { + return "___TAG___"; + } + + async add(template) { + if (!template) { + return; + } + + let data = await template.getData(); + let entries = await template.getTemplateMapEntries(data); + + for (let map of entries) { + this.map.push(map); + } + } + + getMap() { + return this.map; + } + + getTagTarget(str) { + if (str.startsWith("collections.")) { + return str.slice("collections.".length); + } + // Fixes #2851 + if (str.startsWith("collections['") || str.startsWith('collections["')) { + return str.slice("collections['".length, -2); + } + } + + /* --- + * pagination: + * data: collections + * --- + */ + isPaginationOverAllCollections(entry) { + if (entry.data.pagination?.data) { + return ( + entry.data.pagination.data === "collections" || + entry.data.pagination.data === "collections.all" + ); + } + } + + getPaginationTagTarget(entry) { + if (entry.data.pagination?.data) { + return this.getTagTarget(entry.data.pagination.data); + } + } + + addTagsToGraph(graph, inputPath, tags) { + if (!Array.isArray(tags)) { + return; + } + for (let tag of tags) { + let tagWithPrefix = TemplateMap.tagPrefix + tag; + if (!graph.hasNode(tagWithPrefix)) { + graph.addNode(tagWithPrefix); + } + + // Populates to collections.tagName + // Dependency from tag to inputPath + graph.addDependency(tagWithPrefix, inputPath); + } + } + + addDeclaredDependenciesToGraph(graph, inputPath, deps) { + if (!Array.isArray(deps)) { + return; + } + + for (let tag of deps) { + let tagWithPrefix = TemplateMap.tagPrefix + tag; + if (!graph.hasNode(tagWithPrefix)) { + graph.addNode(tagWithPrefix); + } + + // Dependency from inputPath to collection/tag + graph.addDependency(inputPath, tagWithPrefix); + } + } + + // Exclude: Pagination templates consuming `collections` or `collections.all` + // Exclude: Pagination templates that consume config API collections + + // Include: Pagination templates that don’t consume config API collections + // Include: Templates that don’t use Pagination + getMappedDependencies() { + let graph = new DependencyGraph(); + let tagPrefix = TemplateMap.tagPrefix; + + graph.addNode(tagPrefix + "all"); + + for (let entry of this.map) { + if (this.isPaginationOverAllCollections(entry)) { + continue; + } + + // using Pagination (but not targeting a user config collection) + let paginationTagTarget = this.getPaginationTagTarget(entry); + if (paginationTagTarget) { + if (this.isUserConfigCollectionName(paginationTagTarget)) { + // delay this one to the second stage + continue; + } else { + // using pagination but over a tagged collection + graph.addNode(entry.inputPath); + if (!graph.hasNode(tagPrefix + paginationTagTarget)) { + graph.addNode(tagPrefix + paginationTagTarget); + } + graph.addDependency(entry.inputPath, tagPrefix + paginationTagTarget); + } + } else { + // not using pagination + graph.addNode(entry.inputPath); + } + + let collections = TemplateData.getIncludedCollectionNames(entry.data); + this.addTagsToGraph(graph, entry.inputPath, collections); + + this.addDeclaredDependenciesToGraph( + graph, + entry.inputPath, + entry.data.eleventyImport?.collections, + ); + } + + return graph; + } + + // Exclude: Pagination templates consuming `collections` or `collections.all` + // Include: Pagination templates that consume config API collections + getDelayedMappedDependencies() { + let graph = new DependencyGraph(); + let tagPrefix = TemplateMap.tagPrefix; + + graph.addNode(tagPrefix + "all"); + + let userConfigCollections = this.getUserConfigCollectionNames(); + + // Add tags from named user config collections + for (let tag of userConfigCollections) { + graph.addNode(tagPrefix + tag); + } + + for (let entry of this.map) { + if (this.isPaginationOverAllCollections(entry)) { + continue; + } + + let paginationTagTarget = this.getPaginationTagTarget(entry); + if (paginationTagTarget && this.isUserConfigCollectionName(paginationTagTarget)) { + if (!graph.hasNode(entry.inputPath)) { + graph.addNode(entry.inputPath); + } + graph.addDependency(entry.inputPath, tagPrefix + paginationTagTarget); + + let collections = TemplateData.getIncludedCollectionNames(entry.data); + this.addTagsToGraph(graph, entry.inputPath, collections); + + this.addDeclaredDependenciesToGraph( + graph, + entry.inputPath, + entry.data.eleventyImport?.collections, + ); + } + } + + return graph; + } + + // Exclude: Pagination templates consuming `collections.all` + // Include: Pagination templates consuming `collections` + getPaginatedOverCollectionsMappedDependencies() { + let graph = new DependencyGraph(); + let tagPrefix = TemplateMap.tagPrefix; + let allNodeAdded = false; + + for (let entry of this.map) { + if (this.isPaginationOverAllCollections(entry) && !this.getPaginationTagTarget(entry)) { + if (!allNodeAdded) { + graph.addNode(tagPrefix + "all"); + allNodeAdded = true; + } + + if (!graph.hasNode(entry.inputPath)) { + graph.addNode(entry.inputPath); + } + + let collectionNames = TemplateData.getIncludedCollectionNames(entry.data); + if (collectionNames.includes("all")) { + // collections.all + graph.addDependency(tagPrefix + "all", entry.inputPath); + + // Note that `tags` are otherwise ignored here + } + + this.addDeclaredDependenciesToGraph( + graph, + entry.inputPath, + entry.data.eleventyImport?.collections, + ); + } + } + + return graph; + } + + // Include: Pagination templates consuming `collections.all` + getPaginatedOverAllCollectionMappedDependencies() { + let graph = new DependencyGraph(); + let tagPrefix = TemplateMap.tagPrefix; + let allNodeAdded = false; + + for (let entry of this.map) { + if ( + this.isPaginationOverAllCollections(entry) && + this.getPaginationTagTarget(entry) === "all" + ) { + if (!allNodeAdded) { + graph.addNode(tagPrefix + "all"); + allNodeAdded = true; + } + + if (!graph.hasNode(entry.inputPath)) { + graph.addNode(entry.inputPath); + } + + let collectionNames = TemplateData.getIncludedCollectionNames(entry.data); + if (collectionNames.includes("all")) { + // Populates into collections.all + // This is circular! + graph.addDependency(tagPrefix + "all", entry.inputPath); + + // Note that `tags` are otherwise ignored here + } + + this.addDeclaredDependenciesToGraph( + graph, + entry.inputPath, + entry.data.eleventyImport?.collections, + ); + } + } + + return graph; + } + + getTemplateMapDependencyGraph() { + return [ + this.getMappedDependencies(), + this.getDelayedMappedDependencies(), + this.getPaginatedOverCollectionsMappedDependencies(), + this.getPaginatedOverAllCollectionMappedDependencies(), + ]; + } + + getFullTemplateMapOrder() { + // convert dependency graphs to ordered arrays + return this.getTemplateMapDependencyGraph().map((entry) => entry.overallOrder()); + } + + #addEntryToGlobalDependencyGraph(entry) { + let paginationTagTarget = this.getPaginationTagTarget(entry); + if (paginationTagTarget) { + this.config.uses.addDependencyConsumesCollection(entry.inputPath, paginationTagTarget); + } + + let collectionNames = TemplateData.getIncludedCollectionNames(entry.data); + for (let name of collectionNames) { + this.config.uses.addDependencyPublishesToCollection(entry.inputPath, name); + } + + if (Array.isArray(entry.data.eleventyImport?.collections)) { + for (let tag of entry.data.eleventyImport.collections) { + this.config.uses.addDependencyConsumesCollection(entry.inputPath, tag); + } + } + } + + addAllToGlobalDependencyGraph() { + for (let entry of this.map) { + this.#addEntryToGlobalDependencyGraph(entry); + } + } + + async setCollectionByTagName(tagName) { + if (this.isUserConfigCollectionName(tagName)) { + // async + this.collectionsData[tagName] = await this.getUserConfigCollection(tagName); + } else { + this.collectionsData[tagName] = this.getTaggedCollection(tagName); + } + + let precompiled = this.config.precompiledCollections; + if (precompiled?.[tagName]) { + if ( + tagName === "all" || + !Array.isArray(this.collectionsData[tagName]) || + this.collectionsData[tagName].length === 0 + ) { + this.collectionsData[tagName] = precompiled[tagName]; + } + } + } + + // TODO(slightlyoff): major bottleneck + async initDependencyMap(dependencyMap) { + let tagPrefix = TemplateMap.tagPrefix; + for (let depEntry of dependencyMap) { + if (depEntry.startsWith(tagPrefix)) { + // is a tag (collection) entry + let tagName = depEntry.slice(tagPrefix.length); + await this.setCollectionByTagName(tagName); + } else { + // is a template entry + let map = this.getMapEntryForInputPath(depEntry); + map._pages = await map.template.getTemplates(map.data); + + if (map._pages.length === 0) { + // Reminder: a serverless code path was removed here. + } else { + let counter = 0; + for (let page of map._pages) { + // Copy outputPath to map entry + // This is no longer used internally, just for backwards compatibility + // Error added in v3 for https://github.com/11ty/eleventy/issues/3183 + if (map.data.pagination) { + if (!Object.prototype.hasOwnProperty.call(map, "outputPath")) { + Object.defineProperty(map, "outputPath", { + get() { + throw new Error( + "Internal error: `.outputPath` on a paginated map entry is not consistent. Use `_pages[…].outputPath` instead.", + ); + }, + }); + } + } else if (!map.outputPath) { + map.outputPath = page.outputPath; + } + + if (counter === 0 || map.data.pagination?.addAllPagesToCollections) { + if (map.data.eleventyExcludeFromCollections !== true) { + // is in *some* collections + this.collection.add(page); + } + } + + counter++; + } + } + } + } + } + + async cache() { + debug("Caching collections objects."); + this.collectionsData = {}; + + for (let entry of this.map) { + entry.data.collections = this.collectionsData; + } + + let [dependencyMap, delayedDependencyMap, firstPaginatedDepMap, secondPaginatedDepMap] = + this.getFullTemplateMapOrder(); + + await this.initDependencyMap(dependencyMap); + await this.initDependencyMap(delayedDependencyMap); + await this.initDependencyMap(firstPaginatedDepMap); + await this.initDependencyMap(secondPaginatedDepMap); + + await this.resolveRemainingComputedData(); + + let orderedPaths = this.getOrderedInputPaths( + dependencyMap, + delayedDependencyMap, + firstPaginatedDepMap, + secondPaginatedDepMap, + ); + + let orderedMap = orderedPaths.map((inputPath) => { + return this.getMapEntryForInputPath(inputPath); + }); + + await this.config.events.emitLazy("eleventy.contentMap", () => { + return { + inputPathToUrl: this.generateInputUrlContentMap(orderedMap), + urlToInputPath: this.generateUrlMap(orderedMap), + }; + }); + + await this.runDataSchemas(orderedMap); + await this.populateContentDataInMap(orderedMap); + + this.populateCollectionsWithContent(); + this.cached = true; + + this.checkForDuplicatePermalinks(); + this.checkForMissingFileExtensions(); + + await this.config.events.emitLazy("eleventy.layouts", () => this.generateLayoutsMap()); + } + + generateInputUrlContentMap(orderedMap) { + let entries = {}; + for (let entry of orderedMap) { + entries[entry.inputPath] = entry._pages.map((entry) => entry.url); + } + return entries; + } + + generateUrlMap(orderedMap) { + let entries = {}; + for (let entry of orderedMap) { + for (let page of entry._pages) { + // duplicate urls throw an error, so we can return non array here + entries[page.url] = { + inputPath: entry.inputPath, + groupNumber: page.groupNumber, + }; + } + } + return entries; + } + + // TODO(slightlyoff): hot inner loop? + getMapEntryForInputPath(inputPath) { + for (let map of this.map) { + if (map.inputPath === inputPath) { + return map; + } + } + } + + // Filter out any tag nodes + getOrderedInputPaths(...maps) { + let orderedMap = []; + let tagPrefix = TemplateMap.tagPrefix; + + for (let map of maps) { + for (let dep of map) { + if (!dep.startsWith(tagPrefix)) { + orderedMap.push(dep); + } + } + } + return orderedMap; + } + + async runDataSchemas(orderedMap) { + for (let map of orderedMap) { + if (!map._pages) { + continue; + } + + for (let pageEntry of map._pages) { + // Data Schema callback #879 + if (typeof pageEntry.data[this.config.keys.dataSchema] === "function") { + try { + await pageEntry.data[this.config.keys.dataSchema](pageEntry.data); + } catch (e) { + throw new EleventyDataSchemaError( + `Error in the data schema for: ${map.inputPath} (via \`eleventyDataSchema\`)`, + e, + ); + } + } + } + } + } + + async populateContentDataInMap(orderedMap) { + let usedTemplateContentTooEarlyMap = []; + + // Note that empty pagination templates will be skipped here as not renderable + let filteredMap = orderedMap.filter((entry) => entry.template.isRenderable()); + + for (let map of filteredMap) { + if (!map._pages) { + throw new Error(`Internal error: _pages not found for ${map.inputPath}`); + } + + // IMPORTANT: this is where template content is rendered + try { + for (let pageEntry of map._pages) { + pageEntry.templateContent = + await pageEntry.template.renderPageEntryWithoutLayout(pageEntry); + } + } catch (e) { + if (EleventyErrorUtil.isPrematureTemplateContentError(e)) { + usedTemplateContentTooEarlyMap.push(map); + + // Reset cached render promise + for (let pageEntry of map._pages) { + pageEntry.template.resetCaches({ render: true }); + } + } else { + throw e; + } + } + debugDev("Added this.map[...].templateContent, outputPath, et al for one map entry"); + } + + for (let map of usedTemplateContentTooEarlyMap) { + try { + for (let pageEntry of map._pages) { + pageEntry.templateContent = + await pageEntry.template.renderPageEntryWithoutLayout(pageEntry); + } + } catch (e) { + if (EleventyErrorUtil.isPrematureTemplateContentError(e)) { + throw new UsingCircularTemplateContentReferenceError( + `${map.inputPath} contains a circular reference (using collections) to its own templateContent.`, + ); + } else { + // rethrow? + throw e; + } + } + } + } + + getTaggedCollection(tag) { + let result; + if (!tag || tag === "all") { + result = this.collection.getAllSorted(); + } else { + result = this.collection.getFilteredByTag(tag); + } + debug(`Collection: collections.${tag || "all"} size: ${result.length}`); + + return result; + } + + /* 3.0.0-alpha.1: setUserConfigCollections method removed (was only used for testing) */ + isUserConfigCollectionName(name) { + let collections = this.userConfig.getCollections(); + return name && !!collections[name]; + } + + getUserConfigCollectionNames() { + return Object.keys(this.userConfig.getCollections()); + } + + async getUserConfigCollection(name) { + let configCollections = this.userConfig.getCollections(); + + // This works with async now + let result = await configCollections[name](this.collection); + + debug(`Collection: collections.${name} size: ${result.length}`); + return result; + } + + populateCollectionsWithContent() { + for (let collectionName in this.collectionsData) { + // skip custom collections set in configuration files that have arbitrary types + if (!Array.isArray(this.collectionsData[collectionName])) { + continue; + } + + for (let item of this.collectionsData[collectionName]) { + // skip custom collections set in configuration files that have arbitrary types + if (!isPlainObject(item) || !("inputPath" in item)) { + continue; + } + + let entry = this.getMapEntryForInputPath(item.inputPath); + // This check skips precompiled collections + if (entry) { + let index = item.pageNumber || 0; + let content = entry._pages[index]._templateContent; + if (content !== undefined) { + item.templateContent = content; + } + } + } + } + } + + async resolveRemainingComputedData() { + let promises = []; + for (let entry of this.map) { + for (let pageEntry of entry._pages) { + if (this.config.keys.computed in pageEntry.data) { + promises.push(await pageEntry.template.resolveRemainingComputedData(pageEntry.data)); + } + } + } + return Promise.all(promises); + } + + async generateLayoutsMap() { + let layouts = {}; + + for (let entry of this.map) { + for (let page of entry._pages) { + let tmpl = page.template; + let layoutKey = page.data[this.config.keys.layout]; + if (layoutKey) { + let layout = tmpl.getLayout(layoutKey); + let layoutChain = await layout.getLayoutChain(); + let priors = []; + for (let filepath of layoutChain) { + if (!layouts[filepath]) { + layouts[filepath] = new Set(); + } + layouts[filepath].add(page.inputPath); + for (let prior of priors) { + layouts[filepath].add(prior); + } + priors.push(filepath); + } + } + } + } + + for (let key in layouts) { + layouts[key] = Array.from(layouts[key]); + } + + return layouts; + } + + #onEachPage(callback) { + for (let template of this.map) { + for (let page of template._pages) { + callback(page, template); + } + } + } + + checkForDuplicatePermalinks() { + let inputs = {}; + let permalinks = {}; + let warnings = {}; + this.#onEachPage((page, template) => { + if (page.outputPath === false || page.url === false) { + // do nothing (also serverless) + } else { + // Make sure output doesn’t overwrite input (e.g. --input=. --output=.) + // Related to https://github.com/11ty/eleventy/issues/3327 + if (page.outputPath === page.inputPath) { + throw new DuplicatePermalinkOutputError( + `The template at "${page.inputPath}" attempted to overwrite itself.`, + ); + } else if (inputs[page.outputPath]) { + throw new DuplicatePermalinkOutputError( + `The template at "${page.inputPath}" attempted to overwrite an existing template at "${page.outputPath}".`, + ); + } + inputs[page.inputPath] = true; + + if (!permalinks[page.outputPath]) { + permalinks[page.outputPath] = [template.inputPath]; + } else { + warnings[page.outputPath] = `Output conflict: multiple input files are writing to \`${ + page.outputPath + }\`. Use distinct \`permalink\` values to resolve this conflict. + 1. ${template.inputPath} +${permalinks[page.outputPath] + .map(function (inputPath, index) { + return ` ${index + 2}. ${inputPath}\n`; + }) + .join("")} +`; + permalinks[page.outputPath].push(template.inputPath); + } + } + }); + + let warningList = Object.values(warnings); + if (warningList.length) { + // throw one at a time + throw new DuplicatePermalinkOutputError(warningList[0]); + } + } + + checkForMissingFileExtensions() { + // disabled in config + if (this.userConfig?.errorReporting?.allowMissingExtensions === true) { + return; + } + + this.#onEachPage((page) => { + if ( + page.outputPath === false || + page.url === false || + page.data.eleventyAllowMissingExtension || + EXTENSIONLESS_URL_ALLOWLIST.some((url) => page.url.endsWith(url)) + ) { + // do nothing (also serverless) + } else { + if (TemplatePath.getExtension(page.outputPath) === "") { + let e = + new Error(`The template at '${page.inputPath}' attempted to write to '${page.outputPath}'${page.data.permalink ? ` (via \`permalink\` value: '${page.data.permalink}')` : ""}, which is a target on the file system that does not include a file extension. + +You *probably* want to add a file extension to your permalink so that hosts will know how to correctly serve this file to web browsers. Without a file extension, this file may not be reliably deployed without additional hosting configuration (it won’t have a mime type) and may also cause local development issues if you later attempt to write to a subdirectory of the same name. + +Learn more: https://v3.11ty.dev/docs/permalinks/#trailing-slashes + +This is usually but not *always* an error so if you’d like to disable this error message, add \`eleventyAllowMissingExtension: true\` somewhere in the data cascade for this template or use \`eleventyConfig.configureErrorReporting({ allowMissingExtensions: true });\` to disable this feature globally.`); + e.skipOriginalStack = true; + throw e; + } + } + }); + } + + // TODO move these into TemplateMapTest.js + _testGetAllTags() { + let allTags = {}; + for (let map of this.map) { + let tags = map.data.tags; + if (Array.isArray(tags)) { + for (let tag of tags) { + allTags[tag] = true; + } + } + } + return Object.keys(allTags); + } + + async _testGetUserConfigCollectionsData() { + let collections = {}; + let configCollections = this.userConfig.getCollections(); + + for (let name in configCollections) { + collections[name] = configCollections[name](this.collection); + + debug(`Collection: collections.${name} size: ${collections[name].length}`); + } + + return collections; + } + + async _testGetTaggedCollectionsData() { + let collections = {}; + collections.all = this.collection.getAllSorted(); + debug(`Collection: collections.all size: ${collections.all.length}`); + + let tags = this._testGetAllTags(); + for (let tag of tags) { + collections[tag] = this.collection.getFilteredByTag(tag); + debug(`Collection: collections.${tag} size: ${collections[tag].length}`); + } + return collections; + } + + async _testGetAllCollectionsData() { + let collections = {}; + let taggedCollections = await this._testGetTaggedCollectionsData(); + Object.assign(collections, taggedCollections); + + let userConfigCollections = await this._testGetUserConfigCollectionsData(); + Object.assign(collections, userConfigCollections); + + return collections; + } + + async _testGetCollectionsData() { + if (!this.cached) { + await this.cache(); + } + + return this.collectionsData; + } +} + +export default TemplateMap; diff --git a/node_modules/@11ty/eleventy/src/TemplatePassthrough.js b/node_modules/@11ty/eleventy/src/TemplatePassthrough.js new file mode 100644 index 0000000..c1d2fce --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplatePassthrough.js @@ -0,0 +1,339 @@ +import util from "node:util"; +import path from "node:path"; +import fs from "graceful-fs"; + +import isGlob from "is-glob"; +import copy from "@11ty/recursive-copy"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import EleventyBaseError from "./Errors/EleventyBaseError.js"; +import checkPassthroughCopyBehavior from "./Util/PassthroughCopyBehaviorCheck.js"; +import ProjectDirectories from "./Util/ProjectDirectories.js"; + +const fsExists = util.promisify(fs.exists); + +const debug = debugUtil("Eleventy:TemplatePassthrough"); + +class TemplatePassthroughError extends EleventyBaseError {} + +class TemplatePassthrough { + #isExistsCache = {}; + #isDirectoryCache = {}; + + constructor(path, eleventyConfig) { + if (!eleventyConfig || eleventyConfig.constructor.name !== "TemplateConfig") { + throw new TemplatePassthroughError( + "Missing `eleventyConfig` or was not an instance of `TemplateConfig`.", + ); + } + this.eleventyConfig = eleventyConfig; + + this.benchmarks = { + aggregate: this.config.benchmarkManager.get("Aggregate"), + }; + + this.rawPath = path; + + // inputPath is relative to the root of your project and not your Eleventy input directory. + // TODO normalize these with forward slashes + this.inputPath = this.normalizeDirectory(path.inputPath); + this.isInputPathGlob = isGlob(this.inputPath); + + this.outputPath = path.outputPath; + + this.copyOptions = path.copyOptions; // custom options for recursive-copy + + this.isDryRun = false; + this.isIncremental = false; + } + + get config() { + return this.eleventyConfig.getConfig(); + } + + get dirs() { + return this.eleventyConfig.directories; + } + + // inputDir is used when stripping from output path in `getOutputPath` + get inputDir() { + return this.dirs.input; + } + + get outputDir() { + return this.dirs.output; + } + + /* { inputPath, outputPath } though outputPath is *not* the full path: just the output directory */ + getPath() { + return this.rawPath; + } + + async getOutputPath(inputFileFromGlob) { + let { inputDir, outputDir, outputPath, inputPath } = this; + + if (outputPath === true) { + // no explicit target, implied target + if (this.isDirectory(inputPath)) { + let inputRelativePath = TemplatePath.stripLeadingSubPath( + inputFileFromGlob || inputPath, + inputDir, + ); + return ProjectDirectories.normalizeDirectory( + TemplatePath.join(outputDir, inputRelativePath), + ); + } + + return TemplatePath.normalize( + TemplatePath.join( + outputDir, + TemplatePath.stripLeadingSubPath(inputFileFromGlob || inputPath, inputDir), + ), + ); + } + + if (inputFileFromGlob) { + return this.getOutputPathForGlobFile(inputFileFromGlob); + } + + // Has explicit target + + // Bug when copying incremental file overwriting output directory (and making it a file) + // e.g. public/test.css -> _site + // https://github.com/11ty/eleventy/issues/2278 + let fullOutputPath = TemplatePath.normalize(TemplatePath.join(outputDir, outputPath)); + if (outputPath === "" || this.isDirectory(inputPath)) { + fullOutputPath = ProjectDirectories.normalizeDirectory(fullOutputPath); + } + + // TODO room for improvement here: + if ( + !this.isInputPathGlob && + (await fsExists(inputPath)) && + !this.isDirectory(inputPath) && + this.isDirectory(fullOutputPath) + ) { + let filename = path.parse(inputPath).base; + return TemplatePath.normalize(TemplatePath.join(fullOutputPath, filename)); + } + + return fullOutputPath; + } + + async getOutputPathForGlobFile(inputFileFromGlob) { + return TemplatePath.join( + await this.getOutputPath(), + TemplatePath.getLastPathSegment(inputFileFromGlob), + ); + } + + setDryRun(isDryRun) { + this.isDryRun = !!isDryRun; + } + + setRunMode(runMode) { + this.runMode = runMode; + } + + setIsIncremental(isIncremental) { + this.isIncremental = isIncremental; + } + + setFileSystemSearch(fileSystemSearch) { + this.fileSystemSearch = fileSystemSearch; + } + + async getFiles(glob) { + debug("Searching for: %o", glob); + let b = this.benchmarks.aggregate.get("Searching the file system (passthrough)"); + b.before(); + let files = TemplatePath.addLeadingDotSlashArray( + await this.fileSystemSearch.search("passthrough", glob), + ); + b.after(); + return files; + } + + isExists(dir) { + if (this.#isExistsCache[dir] === undefined) { + this.#isExistsCache[dir] = fs.existsSync(dir); + } + return this.#isExistsCache[dir]; + } + + isDirectory(dir) { + if (this.#isDirectoryCache[dir] === undefined) { + if (isGlob(this.inputPath)) { + this.#isDirectoryCache[dir] = false; + } else if (!this.isExists(dir)) { + this.#isDirectoryCache[dir] = false; + } else if (fs.statSync(dir).isDirectory()) { + this.#isDirectoryCache[dir] = true; + } else { + this.#isDirectoryCache[dir] = false; + } + } + + return this.#isDirectoryCache[dir]; + } + + // dir is guaranteed to exist by context + // dir may not be a directory + normalizeDirectory(dir) { + if (dir && typeof dir === "string") { + if (dir.endsWith(path.sep) || dir.endsWith("/")) { + return dir; + } + + // When inputPath is a directory, make sure it has a slash for passthrough copy aliasing + // https://github.com/11ty/eleventy/issues/2709 + if (this.isDirectory(dir)) { + return `${dir}/`; + } + } + + return dir; + } + + // maps input paths to output paths + async getFileMap() { + // TODO VirtualFileSystem candidate + if (!isGlob(this.inputPath) && this.isExists(this.inputPath)) { + return [ + { + inputPath: this.inputPath, + outputPath: await this.getOutputPath(), + }, + ]; + } + + let paths = []; + // If not directory or file, attempt to get globs + let files = await this.getFiles(this.inputPath); + for (let filePathFromGlob of files) { + paths.push({ + inputPath: filePathFromGlob, + outputPath: await this.getOutputPath(filePathFromGlob), + }); + } + + return paths; + } + + /* Types: + * 1. via glob, individual files found + * 2. directory, triggers an event for each file + * 3. individual file + */ + async copy(src, dest, copyOptions) { + if ( + !TemplatePath.stripLeadingDotSlash(dest).startsWith( + TemplatePath.stripLeadingDotSlash(this.outputDir), + ) + ) { + return Promise.reject( + new TemplatePassthroughError( + "Destination is not in the site output directory. Check your passthrough paths.", + ), + ); + } + + let fileCopyCount = 0; + let fileSizeCount = 0; + let map = {}; + let b = this.benchmarks.aggregate.get("Passthrough Copy File"); + // returns a promise + return copy(src, dest, copyOptions) + .on(copy.events.COPY_FILE_START, (copyOp) => { + // Access to individual files at `copyOp.src` + debug("Copying individual file %o", copyOp.src); + map[copyOp.src] = copyOp.dest; + b.before(); + }) + .on(copy.events.COPY_FILE_COMPLETE, (copyOp) => { + fileCopyCount++; + fileSizeCount += copyOp.stats.size; + b.after(); + }) + .then(() => { + return { + count: fileCopyCount, + size: fileSizeCount, + map, + }; + }); + } + + async write() { + if (this.isDryRun) { + return Promise.resolve({ + count: 0, + map: {}, + }); + } + + debug("Copying %o", this.inputPath); + let fileMap = await this.getFileMap(); + + // default options for recursive-copy + // see https://www.npmjs.com/package/recursive-copy#arguments + let copyOptionsDefault = { + overwrite: true, // overwrite output. fails when input is directory (mkdir) and output is file + dot: true, // copy dotfiles + junk: false, // copy cache files like Thumbs.db + results: false, + expand: false, // follow symlinks (matches recursive-copy default) + debug: false, // (matches recursive-copy default) + + // Note: `filter` callback function only passes in a relative path, which is unreliable + // See https://github.com/timkendrick/recursive-copy/blob/4c9a8b8a4bf573285e9c4a649a30a2b59ccf441c/lib/copy.js#L59 + // e.g. `{ filePaths: [ './img/coolkid.jpg' ], relativePaths: [ '' ] }` + }; + + let copyOptions = Object.assign(copyOptionsDefault, this.copyOptions); + + let promises = fileMap.map((entry) => { + // For-free passthrough copy + if (checkPassthroughCopyBehavior(this.config, this.runMode)) { + let aliasMap = {}; + aliasMap[entry.inputPath] = entry.outputPath; + + return Promise.resolve({ + count: 0, + map: aliasMap, + }); + } + + // Copy the files (only in build mode) + return this.copy(entry.inputPath, entry.outputPath, copyOptions); + }); + + // IMPORTANT: this returns an array of promises, does not await for promise to finish + return Promise.all(promises).then( + (results) => { + // collate the count and input/output map results from the array. + let count = 0; + let size = 0; + let map = {}; + + for (let result of results) { + count += result.count; + size += result.size; + Object.assign(map, result.map); + } + + return { + count, + size, + map, + }; + }, + (err) => { + throw new TemplatePassthroughError(`Error copying passthrough files: ${err.message}`, err); + }, + ); + } +} + +export default TemplatePassthrough; diff --git a/node_modules/@11ty/eleventy/src/TemplatePassthroughManager.js b/node_modules/@11ty/eleventy/src/TemplatePassthroughManager.js new file mode 100644 index 0000000..5599b40 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplatePassthroughManager.js @@ -0,0 +1,311 @@ +import isGlob from "is-glob"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import EleventyExtensionMap from "./EleventyExtensionMap.js"; +import EleventyBaseError from "./Errors/EleventyBaseError.js"; +import TemplatePassthrough from "./TemplatePassthrough.js"; +import checkPassthroughCopyBehavior from "./Util/PassthroughCopyBehaviorCheck.js"; +import { isGlobMatch } from "./Util/GlobMatcher.js"; + +const debug = debugUtil("Eleventy:TemplatePassthroughManager"); +const debugDev = debugUtil("Dev:Eleventy:TemplatePassthroughManager"); + +class TemplatePassthroughManagerConfigError extends EleventyBaseError {} +class TemplatePassthroughManagerCopyError extends EleventyBaseError {} + +class TemplatePassthroughManager { + constructor(eleventyConfig) { + if (!eleventyConfig || eleventyConfig.constructor.name !== "TemplateConfig") { + throw new TemplatePassthroughManagerConfigError("Missing or invalid `config` argument."); + } + this.eleventyConfig = eleventyConfig; + this.config = eleventyConfig.getConfig(); + this.reset(); + } + + reset() { + this.count = 0; + this.size = 0; + this.conflictMap = {}; + this.incrementalFile = null; + debug("Resetting counts to 0"); + } + + set extensionMap(extensionMap) { + this._extensionMap = extensionMap; + } + + get extensionMap() { + if (!this._extensionMap) { + this._extensionMap = new EleventyExtensionMap(this.eleventyConfig); + this._extensionMap.setFormats([]); + } + return this._extensionMap; + } + + get dirs() { + return this.eleventyConfig.directories; + } + + get inputDir() { + return this.dirs.input; + } + + get outputDir() { + return this.dirs.output; + } + + setDryRun(isDryRun) { + this.isDryRun = !!isDryRun; + } + + setRunMode(runMode) { + this.runMode = runMode; + } + + setIncrementalFile(path) { + if (path) { + this.incrementalFile = path; + } + } + + _normalizePaths(path, outputPath, copyOptions = {}) { + return { + inputPath: TemplatePath.addLeadingDotSlash(path), + outputPath: outputPath ? TemplatePath.stripLeadingDotSlash(outputPath) : true, + copyOptions, + }; + } + + getConfigPaths() { + let paths = []; + let pathsRaw = this.config.passthroughCopies || {}; + debug("`addPassthroughCopy` config API paths: %o", pathsRaw); + for (let [inputPath, { outputPath, copyOptions }] of Object.entries(pathsRaw)) { + paths.push(this._normalizePaths(inputPath, outputPath, copyOptions)); + } + debug("`addPassthroughCopy` config API normalized paths: %o", paths); + return paths; + } + + getConfigPathGlobs() { + return this.getConfigPaths().map((path) => { + return TemplatePath.convertToRecursiveGlobSync(path.inputPath); + }); + } + + getNonTemplatePaths(paths) { + let matches = []; + for (let path of paths) { + if (!this.extensionMap.hasEngine(path)) { + matches.push(path); + } + } + + return matches; + } + + getCopyCount() { + return this.count; + } + + getCopySize() { + return this.size; + } + + setFileSystemSearch(fileSystemSearch) { + this.fileSystemSearch = fileSystemSearch; + } + + getTemplatePassthroughForPath(path, isIncremental = false) { + let inst = new TemplatePassthrough(path, this.eleventyConfig); + + inst.setFileSystemSearch(this.fileSystemSearch); + inst.setIsIncremental(isIncremental); + inst.setDryRun(this.isDryRun); + inst.setRunMode(this.runMode); + + return inst; + } + + async copyPassthrough(pass) { + if (!(pass instanceof TemplatePassthrough)) { + throw new TemplatePassthroughManagerCopyError( + "copyPassthrough expects an instance of TemplatePassthrough", + ); + } + + let { inputPath } = pass.getPath(); + + // TODO https://github.com/11ty/eleventy/issues/2452 + // De-dupe both the input and output paired together to avoid the case + // where an input/output pair has been added via multiple passthrough methods (glob, file suffix, etc) + // Probably start with the `filter` callback in recursive-copy but it only passes relative paths + // See the note in TemplatePassthrough.js->write() + + // Also note that `recursive-copy` handles repeated overwrite copy to the same destination just fine. + // e.g. `for(let j=0, k=1000; j { + for (let src in map) { + let dest = map[src]; + if (this.conflictMap[dest]) { + if (src !== this.conflictMap[dest]) { + throw new TemplatePassthroughManagerCopyError( + `Multiple passthrough copy files are trying to write to the same output file (${dest}). ${src} and ${this.conflictMap[dest]}`, + ); + } else { + // Multiple entries from the same source + debug( + "A passthrough copy entry (%o) caused the same file (%o) to be copied more than once to the output (%o). This is atomically safe but a waste of build resources.", + inputPath, + src, + dest, + ); + } + } + + debugDev("Adding %o to passthrough copy conflict map, from %o", dest, src); + + this.conflictMap[dest] = src; + } + + if (pass.isDryRun) { + // We don’t count the skipped files as we need to iterate over them + debug( + "Skipped %o (either from --dryrun or --incremental or for-free passthrough copy)", + inputPath, + ); + } else { + if (count) { + this.count += count; + this.size += size; + debug("Copied %o (%d files, %d size)", inputPath, count || 0, size || 0); + } else { + debug("Skipped copying %o (emulated passthrough copy)", inputPath); + } + } + + return { + count, + map, + }; + }, + function (e) { + return Promise.reject( + new TemplatePassthroughManagerCopyError(`Having trouble copying '${inputPath}'`, e), + ); + }, + ); + } + + isPassthroughCopyFile(paths, changedFile) { + if (!changedFile) { + return false; + } + + // passthrough copy by non-matching engine extension (via templateFormats) + for (let path of paths) { + if (path === changedFile && !this.extensionMap.hasEngine(path)) { + return true; + } + } + + for (let path of this.getConfigPaths()) { + if (TemplatePath.startsWithSubPath(changedFile, path.inputPath)) { + return path; + } + if (changedFile && isGlob(path.inputPath) && isGlobMatch(changedFile, [path.inputPath])) { + return path; + } + } + + return false; + } + + getAllNormalizedPaths(paths) { + if (this.incrementalFile) { + let isPassthrough = this.isPassthroughCopyFile(paths, this.incrementalFile); + + if (isPassthrough) { + if (isPassthrough.outputPath) { + return [this._normalizePaths(this.incrementalFile, isPassthrough.outputPath)]; + } + + return [this._normalizePaths(this.incrementalFile)]; + } + + // Fixes https://github.com/11ty/eleventy/issues/2491 + if (!checkPassthroughCopyBehavior(this.config, this.runMode)) { + return []; + } + } + + let normalizedPaths = this.getConfigPaths(); + if (debug.enabled) { + for (let path of normalizedPaths) { + debug("TemplatePassthrough copying from config: %o", path); + } + } + + if (paths?.length) { + let passthroughPaths = this.getNonTemplatePaths(paths); + for (let path of passthroughPaths) { + let normalizedPath = this._normalizePaths(path); + + debug( + `TemplatePassthrough copying from non-matching file extension: ${normalizedPath.inputPath}`, + ); + + normalizedPaths.push(normalizedPath); + } + } + + return normalizedPaths; + } + + // keys: output + // values: input + getAliasesFromPassthroughResults(result) { + let entries = {}; + for (let entry of result) { + for (let src in entry.map) { + let dest = TemplatePath.stripLeadingSubPath(entry.map[src], this.outputDir); + entries["/" + encodeURI(dest)] = src; + } + } + return entries; + } + + // Performance note: these can actually take a fair bit of time, but aren’t a + // bottleneck to eleventy. The copies are performed asynchronously and don’t affect eleventy + // write times in a significant way. + async copyAll(templateExtensionPaths) { + debug("TemplatePassthrough copy started."); + let normalizedPaths = this.getAllNormalizedPaths(templateExtensionPaths); + + let passthroughs = normalizedPaths.map((path) => { + // if incrementalFile is set but it isn’t a passthrough copy, normalizedPaths will be an empty array + let isIncremental = !!this.incrementalFile; + + return this.getTemplatePassthroughForPath(path, isIncremental); + }); + + let promises = passthroughs.map((pass) => this.copyPassthrough(pass)); + return Promise.all(promises).then(async (results) => { + let aliases = this.getAliasesFromPassthroughResults(results); + await this.config.events.emit("eleventy.passthrough", { + map: aliases, + }); + + debug(`TemplatePassthrough copy finished. Current count: ${this.count} (size: ${this.size})`); + return results; + }); + } +} + +export default TemplatePassthroughManager; diff --git a/node_modules/@11ty/eleventy/src/TemplatePermalink.js b/node_modules/@11ty/eleventy/src/TemplatePermalink.js new file mode 100644 index 0000000..2191a51 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplatePermalink.js @@ -0,0 +1,189 @@ +import path from "node:path"; +import normalize from "normalize-path"; +import { TemplatePath, isPlainObject } from "@11ty/eleventy-utils"; + +class TemplatePermalink { + // `link` with template syntax should have already been rendered in Template.js + constructor(link, extraSubdir) { + let isLinkAnObject = isPlainObject(link); + + this._isRendered = true; + this._writeToFileSystem = true; + + let buildLink; + + if (isLinkAnObject) { + if ("build" in link) { + buildLink = link.build; + } + + // find the first string key + for (let key in link) { + if (typeof key !== "string") { + continue; + } + break; + } + } else { + buildLink = link; + } + + // permalink: false and permalink: build: false + if (typeof buildLink === "boolean") { + if (buildLink === false) { + this._writeToFileSystem = false; + } else { + throw new Error( + `\`permalink: ${ + isLinkAnObject ? "build: " : "" + }true\` is not a supported feature in Eleventy. Did you mean \`permalink: ${ + isLinkAnObject ? "build: " : "" + }false\`?`, + ); + } + } else if (buildLink) { + this.buildLink = buildLink; + } + + if (isLinkAnObject) { + // default if permalink is an Object but does not have a `build` prop + if (!("build" in link)) { + this._writeToFileSystem = false; + this._isRendered = false; + } + } + + this.extraPaginationSubdir = extraSubdir || ""; + } + + setUrlTransforms(transforms) { + this._urlTransforms = transforms; + } + + get urlTransforms() { + return this._urlTransforms || []; + } + + _addDefaultLinkFilename(link) { + return link + (link.slice(-1) === "/" ? "index.html" : ""); + } + + toOutputPath() { + if (!this.buildLink) { + // empty or false + return false; + } + + let cleanLink = this._addDefaultLinkFilename(this.buildLink); + let parsed = path.parse(cleanLink); + + return TemplatePath.join(parsed.dir, this.extraPaginationSubdir, parsed.base); + } + + // Used in url transforms feature + static getUrlStem(original) { + let subject = original; + if (original.endsWith(".html")) { + subject = original.slice(0, -1 * ".html".length); + } + return TemplatePermalink.normalizePathToUrl(subject); + } + + static normalizePathToUrl(original) { + let compare = original || ""; + + let needleHtml = "/index.html"; + let needleBareTrailingSlash = "/index/"; + let needleBare = "/index"; + if (compare.endsWith(needleHtml)) { + return compare.slice(0, compare.length - needleHtml.length) + "/"; + } else if (compare.endsWith(needleBareTrailingSlash)) { + return compare.slice(0, compare.length - needleBareTrailingSlash.length) + "/"; + } else if (compare.endsWith(needleBare)) { + return compare.slice(0, compare.length - needleBare.length) + "/"; + } + + return original; + } + + // This method is used to generate the `page.url` variable. + + // remove all index.html’s from links + // index.html becomes / + // test/index.html becomes test/ + toHref() { + if (!this.buildLink) { + // empty or false + return false; + } + + let transformedLink = this.toOutputPath(); + let original = (transformedLink.charAt(0) !== "/" ? "/" : "") + transformedLink; + + let normalized = TemplatePermalink.normalizePathToUrl(original) || ""; + for (let transform of this.urlTransforms) { + original = + transform({ + url: normalized, + urlStem: TemplatePermalink.getUrlStem(original), + }) ?? original; + } + + return TemplatePermalink.normalizePathToUrl(original); + } + + toPath(outputDir) { + if (!this.buildLink) { + return false; + } + + let uri = this.toOutputPath(); + + if (uri === false) { + return false; + } + + return normalize(outputDir + "/" + uri); + } + + toPathFromRoot() { + if (!this.buildLink) { + return false; + } + + let uri = this.toOutputPath(); + + if (uri === false) { + return false; + } + + return normalize(uri); + } + + static _hasDuplicateFolder(dir, base) { + let folders = dir.split("/"); + if (!folders[folders.length - 1]) { + folders.pop(); + } + return folders[folders.length - 1] === base; + } + + static generate(dir, filenameNoExt, extraSubdir, fileExtension = "html") { + let path; + if (fileExtension === "html") { + let hasDupeFolder = TemplatePermalink._hasDuplicateFolder(dir, filenameNoExt); + + path = + (dir ? dir + "/" : "") + + (filenameNoExt !== "index" && !hasDupeFolder ? filenameNoExt + "/" : "") + + "index" + + ".html"; + } else { + path = (dir ? dir + "/" : "") + filenameNoExt + "." + fileExtension; + } + + return new TemplatePermalink(path, extraSubdir); + } +} + +export default TemplatePermalink; diff --git a/node_modules/@11ty/eleventy/src/TemplateRender.js b/node_modules/@11ty/eleventy/src/TemplateRender.js new file mode 100644 index 0000000..4743716 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateRender.js @@ -0,0 +1,294 @@ +import EleventyBaseError from "./Errors/EleventyBaseError.js"; +import EleventyExtensionMap from "./EleventyExtensionMap.js"; +import TemplateEngineManager from "./Engines/TemplateEngineManager.js"; +import CustomEngine from "./Engines/Custom.js"; + +// import debugUtil from "debug"; +// const debug = debugUtil("Eleventy:TemplateRender"); + +class TemplateRenderConfigError extends EleventyBaseError {} +class TemplateRenderUnknownEngineError extends EleventyBaseError {} + +// works with full path names or short engine name +class TemplateRender { + constructor(tmplPath, config) { + if (!tmplPath) { + throw new Error(`TemplateRender requires a tmplPath argument, instead of ${tmplPath}`); + } + if (!config) { + throw new TemplateRenderConfigError("Missing `config` argument."); + } + if (config.constructor.name === "TemplateConfig") { + this.eleventyConfig = config; + this.config = config.getConfig(); + } else { + throw new Error("Third argument to TemplateRender must be a TemplateConfig instance."); + } + + this.engineNameOrPath = tmplPath; + + this.parseMarkdownWith = this.config.markdownTemplateEngine; + this.parseHtmlWith = this.config.htmlTemplateEngine; + } + + get dirs() { + return this.eleventyConfig.directories; + } + + get inputDir() { + return this.dirs.input; + } + + get includesDir() { + return this.dirs.includes; + } + + /* Backwards compat */ + getIncludesDir() { + return this.includesDir; + } + + get config() { + return this._config; + } + + set config(config) { + this._config = config; + } + + set extensionMap(extensionMap) { + this._extensionMap = extensionMap; + } + + get extensionMap() { + if (!this._extensionMap) { + this._extensionMap = new EleventyExtensionMap(this.eleventyConfig); + this._extensionMap.setFormats([]); + } + return this._extensionMap; + } + + async getEngineByName(name) { + let engine = await this.extensionMap.engineManager.getEngine(name, this.extensionMap); + engine.eleventyConfig = this.eleventyConfig; + + return engine; + } + + // Runs once per template + async init(engineNameOrPath) { + let name = engineNameOrPath || this.engineNameOrPath; + this.extensionMap.config = this.eleventyConfig; + + let extensionEntry = this.extensionMap.getExtensionEntry(name); + let engineName = extensionEntry?.aliasKey || extensionEntry?.key; + if (TemplateEngineManager.isSimpleAlias(extensionEntry)) { + engineName = extensionEntry?.key; + } + this._engineName = engineName; + + if (!extensionEntry || !this._engineName) { + throw new TemplateRenderUnknownEngineError( + `Unknown engine for ${name} (supported extensions: ${this.extensionMap.getReadableFileExtensions()})`, + ); + } + + this._engine = await this.getEngineByName(this._engineName); + + if (this.useMarkdown === undefined) { + this.setUseMarkdown(this._engineName === "md"); + } + } + + get engineName() { + if (!this._engineName) { + throw new Error("TemplateRender needs a call to the init() method."); + } + return this._engineName; + } + + get engine() { + if (!this._engine) { + throw new Error("TemplateRender needs a call to the init() method."); + } + return this._engine; + } + + static parseEngineOverrides(engineName) { + if (typeof (engineName || "") !== "string") { + throw new Error("Expected String passed to parseEngineOverrides. Received: " + engineName); + } + + let overlappingEngineWarningCount = 0; + let engines = []; + let uniqueLookup = {}; + let usingMarkdown = false; + (engineName || "") + .split(",") + .map((name) => { + return name.toLowerCase().trim(); + }) + .forEach((name) => { + // html is assumed (treated as plaintext by the system) + if (!name || name === "html") { + return; + } + + if (name === "md") { + usingMarkdown = true; + return; + } + + if (!uniqueLookup[name]) { + engines.push(name); + uniqueLookup[name] = true; + + // we already short circuit md and html types above + overlappingEngineWarningCount++; + } + }); + + if (overlappingEngineWarningCount > 1) { + throw new Error( + `Don’t mix multiple templating engines in your front matter overrides (exceptions for HTML and Markdown). You used: ${engineName}`, + ); + } + + // markdown should always be first + if (usingMarkdown) { + engines.unshift("md"); + } + + return engines; + } + + // used for error logging and console output. + getReadableEnginesList() { + return this.getReadableEnginesListDifferingFromFileExtension() || this.engineName; + } + + getReadableEnginesListDifferingFromFileExtension() { + let keyFromFilename = this.extensionMap.getKey(this.engineNameOrPath); + if (this.engine instanceof CustomEngine) { + if ( + this.engine.entry && + this.engine.entry.name && + keyFromFilename !== this.engine.entry.name + ) { + return this.engine.entry.name; + } else { + // We don’t have a name for it so we return nothing so we don’t misreport (per #2386) + return; + } + } + + if (this.engineName === "md" && this.useMarkdown && this.parseMarkdownWith) { + return this.parseMarkdownWith; + } + if (this.engineName === "html" && this.parseHtmlWith) { + return this.parseHtmlWith; + } + + // templateEngineOverride in play and template language differs from file extension + if (keyFromFilename !== this.engineName) { + return this.engineName; + } + } + + // TODO templateEngineOverride + getPreprocessorEngine() { + if (this.engineName === "md" && this.parseMarkdownWith) { + return this.parseMarkdownWith; + } + if (this.engineName === "html" && this.parseHtmlWith) { + return this.parseHtmlWith; + } + return this.extensionMap.getKey(this.engineNameOrPath); + } + + // We pass in templateEngineOverride here because it isn’t yet applied to templateRender + getEnginesList(engineOverride) { + if (engineOverride) { + let engines = TemplateRender.parseEngineOverrides(engineOverride).reverse(); + return engines.join(","); + } + + if (this.engineName === "md" && this.useMarkdown && this.parseMarkdownWith) { + return `${this.parseMarkdownWith},md`; + } + if (this.engineName === "html" && this.parseHtmlWith) { + return this.parseHtmlWith; + } + + // templateEngineOverride in play + return this.extensionMap.getKey(this.engineNameOrPath); + } + + async setEngineOverride(engineName, bypassMarkdown) { + let engines = TemplateRender.parseEngineOverrides(engineName); + + // when overriding, Template Engines with HTML will instead use the Template Engine as primary and output HTML + // So any HTML engine usage here will never use a preprocessor templating engine. + this.setHtmlEngine(false); + + if (!engines.length) { + await this.init("html"); + return; + } + + await this.init(engines[0]); + + let usingMarkdown = engines[0] === "md" && !bypassMarkdown; + + this.setUseMarkdown(usingMarkdown); + + if (usingMarkdown) { + // false means only parse markdown and not with a preprocessor template engine + this.setMarkdownEngine(engines.length > 1 ? engines[1] : false); + } + } + + getEngineName() { + return this.engineName; + } + + isEngine(engine) { + return this.engineName === engine; + } + + setUseMarkdown(useMarkdown) { + this.useMarkdown = !!useMarkdown; + } + + // this is only called for templateEngineOverride + setMarkdownEngine(markdownEngine) { + this.parseMarkdownWith = markdownEngine; + } + + // this is only called for templateEngineOverride + setHtmlEngine(htmlEngineName) { + this.parseHtmlWith = htmlEngineName; + } + + async _testRender(str, data) { + return this.engine._testRender(str, data); + } + + async getCompiledTemplate(str) { + // TODO refactor better, move into TemplateEngine logic + if (this.engineName === "md") { + return this.engine.compile( + str, + this.engineNameOrPath, + this.parseMarkdownWith, + !this.useMarkdown, + ); + } else if (this.engineName === "html") { + return this.engine.compile(str, this.engineNameOrPath, this.parseHtmlWith); + } else { + return this.engine.compile(str, this.engineNameOrPath); + } + } +} + +export default TemplateRender; diff --git a/node_modules/@11ty/eleventy/src/TemplateWriter.js b/node_modules/@11ty/eleventy/src/TemplateWriter.js new file mode 100755 index 0000000..fed8f17 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateWriter.js @@ -0,0 +1,518 @@ +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import Template from "./Template.js"; +import TemplateMap from "./TemplateMap.js"; +import EleventyFiles from "./EleventyFiles.js"; +import EleventyExtensionMap from "./EleventyExtensionMap.js"; +import EleventyBaseError from "./Errors/EleventyBaseError.js"; +import { EleventyErrorHandler } from "./Errors/EleventyErrorHandler.js"; +import EleventyErrorUtil from "./Errors/EleventyErrorUtil.js"; +import FileSystemSearch from "./FileSystemSearch.js"; +import ConsoleLogger from "./Util/ConsoleLogger.js"; + +const debug = debugUtil("Eleventy:TemplateWriter"); + +class TemplateWriterMissingConfigArgError extends EleventyBaseError {} +class EleventyPassthroughCopyError extends EleventyBaseError {} +class EleventyTemplateError extends EleventyBaseError {} + +class TemplateWriter { + #eleventyFiles; + + constructor( + templateFormats, // TODO remove this, see `get eleventyFiles` first + templateData, + eleventyConfig, + ) { + if (!eleventyConfig) { + throw new TemplateWriterMissingConfigArgError("Missing config argument."); + } + this.eleventyConfig = eleventyConfig; + this.config = eleventyConfig.getConfig(); + this.userConfig = eleventyConfig.userConfig; + + this.templateFormats = templateFormats; + + this.templateData = templateData; + this.isVerbose = true; + this.isDryRun = false; + this.writeCount = 0; + this.renderCount = 0; + this.skippedCount = 0; + this.isRunInitialBuild = true; + + this._templatePathCache = new Map(); + } + + get dirs() { + return this.eleventyConfig.directories; + } + + get inputDir() { + return this.dirs.input; + } + + get outputDir() { + return this.dirs.output; + } + + get templateFormats() { + return this._templateFormats; + } + + set templateFormats(value) { + this._templateFormats = value; + } + + /* Getter for error handler */ + get errorHandler() { + if (!this._errorHandler) { + this._errorHandler = new EleventyErrorHandler(); + this._errorHandler.isVerbose = this.verboseMode; + this._errorHandler.logger = this.logger; + } + + return this._errorHandler; + } + + /* Getter for Logger */ + get logger() { + if (!this._logger) { + this._logger = new ConsoleLogger(); + this._logger.isVerbose = this.verboseMode; + } + + return this._logger; + } + + /* Setter for Logger */ + set logger(logger) { + this._logger = logger; + } + + /* For testing */ + overrideConfig(config) { + this.config = config; + } + + restart() { + this.writeCount = 0; + this.renderCount = 0; + this.skippedCount = 0; + } + + set extensionMap(extensionMap) { + this._extensionMap = extensionMap; + } + + get extensionMap() { + if (!this._extensionMap) { + this._extensionMap = new EleventyExtensionMap(this.eleventyConfig); + this._extensionMap.setFormats(this.templateFormats); + } + return this._extensionMap; + } + + setEleventyFiles(eleventyFiles) { + this.#eleventyFiles = eleventyFiles; + } + + set eleventyFiles(eleventyFiles) { + this.#eleventyFiles = eleventyFiles; + } + + get eleventyFiles() { + // usually Eleventy.js will setEleventyFiles with the EleventyFiles manager + if (!this.#eleventyFiles) { + // if not, we can create one (used only by tests) + this.#eleventyFiles = new EleventyFiles(this.templateFormats, this.eleventyConfig); + + this.#eleventyFiles.setFileSystemSearch(new FileSystemSearch()); + this.#eleventyFiles.init(); + } + + return this.#eleventyFiles; + } + + async _getAllPaths() { + // this is now cached upstream by FileSystemSearch + return this.eleventyFiles.getFiles(); + } + + _createTemplate(path, to = "fs") { + let tmpl = this._templatePathCache.get(path); + let wasCached = false; + if (tmpl) { + wasCached = true; + // Update config for https://github.com/11ty/eleventy/issues/3468 + tmpl.eleventyConfig = this.eleventyConfig; + + // TODO reset other constructor things here like inputDir/outputDir/extensionMap/ + tmpl.setTemplateData(this.templateData); + } else { + tmpl = new Template(path, this.templateData, this.extensionMap, this.eleventyConfig); + + tmpl.setOutputFormat(to); + + tmpl.logger = this.logger; + this._templatePathCache.set(path, tmpl); + + /* + * Sample filter: arg str, return pretty HTML string + * function(str) { + * return pretty(str, { ocd: true }); + * } + */ + tmpl.setTransforms(this.config.transforms); + + for (let linterName in this.config.linters) { + let linter = this.config.linters[linterName]; + if (typeof linter === "function") { + tmpl.addLinter(linter); + } + } + } + + tmpl.setDryRun(this.isDryRun); + tmpl.setIsVerbose(this.isVerbose); + tmpl.reset(); + + return { + template: tmpl, + wasCached, + }; + } + + // incrementalFileShape is `template` or `copy` (for passthrough file copy) + async _addToTemplateMapIncrementalBuild(incrementalFileShape, paths, to = "fs") { + // Render overrides are only used when `--ignore-initial` is in play and an initial build is not run + let ignoreInitialBuild = !this.isRunInitialBuild; + let secondOrderRelevantLookup = {}; + let templates = []; + + let promises = []; + for (let path of paths) { + let { template: tmpl } = this._createTemplate(path, to); + + // Note: removed a fix here to fetch missing templateRender instances + // that was tested as no longer needed (Issue #3170). + + templates.push(tmpl); + + // This must happen before data is generated for the incremental file only + if (incrementalFileShape === "template" && tmpl.inputPath === this.incrementalFile) { + tmpl.resetCaches(); + } + + // IMPORTANT: This is where the data is first generated for the template + promises.push(this.templateMap.add(tmpl)); + } + + // Important to set up template dependency relationships first + await Promise.all(promises); + + // Delete incremental file from the dependency graph so we get fresh entries! + // This _must_ happen before any additions, the other ones are in Custom.js and GlobalDependencyMap.js (from the eleventy.layouts Event) + this.config.uses.resetNode(this.incrementalFile); + + // write new template relationships to the global dependency graph for next time + this.templateMap.addAllToGlobalDependencyGraph(); + + // Always disable render for --ignore-initial + if (ignoreInitialBuild) { + for (let tmpl of templates) { + tmpl.setRenderableOverride(false); // disable render + } + return; + } + + for (let tmpl of templates) { + if (incrementalFileShape === "template" && tmpl.inputPath === this.incrementalFile) { + tmpl.setRenderableOverride(undefined); // unset, probably render + } else if ( + tmpl.isFileRelevantToThisTemplate(this.incrementalFile, { + isFullTemplate: incrementalFileShape === "template", + }) + ) { + // changed file is used by template + // template uses the changed file + tmpl.setRenderableOverride(undefined); // unset, probably render + secondOrderRelevantLookup[tmpl.inputPath] = true; + } else if (this.config.uses.isFileUsedBy(this.incrementalFile, tmpl.inputPath)) { + // changed file uses this template + tmpl.setRenderableOverride("optional"); + } else { + // For incremental, always disable render on irrelevant templates + tmpl.setRenderableOverride(false); // disable render + } + } + + let secondOrderRelevantArray = this.config.uses + .getTemplatesRelevantToTemplateList(Object.keys(secondOrderRelevantLookup)) + .map((entry) => TemplatePath.addLeadingDotSlash(entry)); + let secondOrderTemplates = Object.fromEntries( + Object.entries(secondOrderRelevantArray).map(([index, value]) => [value, true]), + ); + + for (let tmpl of templates) { + // second order templates must also be rendered if not yet already rendered at least once and available in cache. + if (secondOrderTemplates[tmpl.inputPath]) { + if (tmpl.isRenderableDisabled()) { + tmpl.setRenderableOverride("optional"); + } + } + } + + // Order of templates does not matter here, they’re reordered later based on dependencies in TemplateMap.js + for (let tmpl of templates) { + if (incrementalFileShape === "template" && tmpl.inputPath === this.incrementalFile) { + // Cache is reset above (to invalidate data cache at the right time) + tmpl.setDryRunViaIncremental(false); + } else if (!tmpl.isRenderableDisabled() && !tmpl.isRenderableOptional()) { + // Related to the template but not the template (reset the render cache, not the read cache) + tmpl.resetCaches({ + data: true, + render: true, + }); + + tmpl.setDryRunViaIncremental(false); + } else { + // During incremental we only reset the data cache for non-matching templates, see https://github.com/11ty/eleventy/issues/2710 + // Keep caches for read/render + tmpl.resetCaches({ + data: true, + }); + + tmpl.setDryRunViaIncremental(true); + + this.skippedCount++; + } + } + } + + _addToTemplateMapFullBuild(paths, to = "fs") { + if (this.incrementalFile) { + return []; + } + + let ignoreInitialBuild = !this.isRunInitialBuild; + let promises = []; + for (let path of paths) { + let { template: tmpl, wasCached } = this._createTemplate(path, to); + + // Render overrides are only used when `--ignore-initial` is in play and an initial build is not run + if (ignoreInitialBuild) { + tmpl.setRenderableOverride(false); // disable render + } else { + tmpl.setRenderableOverride(undefined); // unset, render + } + + if (wasCached) { + tmpl.resetCaches(); + } + + // IMPORTANT: This is where the data is first generated for the template + promises.push(this.templateMap.add(tmpl)); + } + + return Promise.all(promises); + } + + async _addToTemplateMap(paths, to = "fs") { + let incrementalFileShape = this.eleventyFiles.getFileShape(paths, this.incrementalFile); + + // Filter out passthrough copy files + paths = paths.filter((path) => { + if (!this.extensionMap.hasEngine(path)) { + return false; + } + if (incrementalFileShape === "copy") { + this.skippedCount++; + // Filters out templates if the incremental file is a passthrough copy file + return false; + } + return true; + }); + + // Full Build + if (!this.incrementalFile) { + let ret = await this._addToTemplateMapFullBuild(paths, to); + + // write new template relationships to the global dependency graph for next time + this.templateMap.addAllToGlobalDependencyGraph(); + + return ret; + } + + // Top level async to get at the promises returned. + return await this._addToTemplateMapIncrementalBuild(incrementalFileShape, paths, to); + } + + async _createTemplateMap(paths, to) { + this.templateMap = new TemplateMap(this.eleventyConfig); + + await this._addToTemplateMap(paths, to); + await this.templateMap.cache(); + + return this.templateMap; + } + + async _generateTemplate(mapEntry, to) { + let tmpl = mapEntry.template; + + return tmpl.generateMapEntry(mapEntry, to).then((pages) => { + this.renderCount += tmpl.getRenderCount(); + this.writeCount += tmpl.getWriteCount(); + return pages; + }); + } + + async writePassthroughCopy(templateExtensionPaths) { + let passthroughManager = this.eleventyFiles.getPassthroughManager(); + passthroughManager.setIncrementalFile(this.incrementalFile); + + return passthroughManager.copyAll(templateExtensionPaths).catch((e) => { + this.errorHandler.warn(e, "Error with passthrough copy"); + return Promise.reject(new EleventyPassthroughCopyError("Having trouble copying", e)); + }); + } + + async generateTemplates(paths, to = "fs") { + let promises = []; + + // console.time("generateTemplates:_createTemplateMap"); + // TODO optimize await here + await this._createTemplateMap(paths, to); + // console.timeEnd("generateTemplates:_createTemplateMap"); + debug("Template map created."); + + let usedTemplateContentTooEarlyMap = []; + for (let mapEntry of this.templateMap.getMap()) { + promises.push( + this._generateTemplate(mapEntry, to).catch(function (e) { + // Premature templateContent in layout render, this also happens in + // TemplateMap.populateContentDataInMap for non-layout content + if (EleventyErrorUtil.isPrematureTemplateContentError(e)) { + usedTemplateContentTooEarlyMap.push(mapEntry); + } else { + let outputPaths = `"${mapEntry._pages.map((page) => page.outputPath).join(`", "`)}"`; + return Promise.reject( + new EleventyTemplateError( + `Having trouble writing to ${outputPaths} from "${mapEntry.inputPath}"`, + e, + ), + ); + } + }), + ); + } + + for (let mapEntry of usedTemplateContentTooEarlyMap) { + promises.push( + this._generateTemplate(mapEntry, to).catch(function (e) { + return Promise.reject( + new EleventyTemplateError( + `Having trouble writing to (second pass) "${mapEntry.outputPath}" from "${mapEntry.inputPath}"`, + e, + ), + ); + }), + ); + } + + return promises; + } + + async write() { + let paths = await this._getAllPaths(); + let promises = []; + + // The ordering here is important to destructuring in Eleventy->_watch + promises.push(this.writePassthroughCopy(paths)); + + promises.push(...(await this.generateTemplates(paths))); + + return Promise.all(promises).then( + ([passthroughCopyResults, ...templateResults]) => { + return { + passthroughCopy: passthroughCopyResults, + // New in 3.0: flatten and filter out falsy templates + templates: templateResults.flat().filter(Boolean), + }; + }, + (e) => { + return Promise.reject(e); + }, + ); + } + + // Passthrough copy not supported in JSON output. + // --incremental not supported in JSON output. + async getJSON(to = "json") { + let paths = await this._getAllPaths(); + let promises = await this.generateTemplates(paths, to); + + return Promise.all(promises).then( + (templateResults) => { + return { + // New in 3.0: flatten and filter out falsy templates + templates: templateResults.flat().filter(Boolean), + }; + }, + (e) => { + return Promise.reject(e); + }, + ); + } + + setVerboseOutput(isVerbose) { + this.isVerbose = isVerbose; + this.errorHandler.isVerbose = isVerbose; + } + + setDryRun(isDryRun) { + this.isDryRun = !!isDryRun; + + this.eleventyFiles.getPassthroughManager().setDryRun(this.isDryRun); + } + + setRunInitialBuild(runInitialBuild) { + this.isRunInitialBuild = runInitialBuild; + } + setIncrementalBuild(isIncremental) { + this.isIncremental = isIncremental; + } + setIncrementalFile(incrementalFile) { + this.incrementalFile = incrementalFile; + } + resetIncrementalFile() { + this.incrementalFile = null; + } + + getCopyCount() { + return this.eleventyFiles.getPassthroughManager().getCopyCount(); + } + + getCopySize() { + return this.eleventyFiles.getPassthroughManager().getCopySize(); + } + + getRenderCount() { + return this.renderCount; + } + + getWriteCount() { + return this.writeCount; + } + + getSkippedCount() { + return this.skippedCount; + } + + get caches() { + return ["_templatePathCache"]; + } +} + +export default TemplateWriter; diff --git a/node_modules/@11ty/eleventy/src/UserConfig.js b/node_modules/@11ty/eleventy/src/UserConfig.js new file mode 100644 index 0000000..12f2ba4 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/UserConfig.js @@ -0,0 +1,1292 @@ +import chalk from "kleur"; +import { DateTime } from "luxon"; +import yaml from "js-yaml"; +import matter from "gray-matter"; +import debugUtil from "debug"; + +import { DeepCopy, TemplatePath, isPlainObject } from "@11ty/eleventy-utils"; + +import HtmlBasePlugin from "./Plugins/HtmlBasePlugin.js"; +import RenderPlugin from "./Plugins/RenderPlugin.js"; +import InputPathToUrlPlugin from "./Plugins/InputPathToUrl.js"; + +import isAsyncFunction from "./Util/IsAsyncFunction.js"; +import objectFilter from "./Util/Objects/ObjectFilter.js"; +import AsyncEventEmitter from "./Util/AsyncEventEmitter.js"; +import EleventyCompatibility from "./Util/Compatibility.js"; +import EleventyBaseError from "./Errors/EleventyBaseError.js"; +import BenchmarkManager from "./Benchmark/BenchmarkManager.js"; +import JavaScriptFrontMatter from "./Engines/FrontMatter/JavaScript.js"; +import { augmentFunction } from "./Engines/Util/ContextAugmenter.js"; + +const debug = debugUtil("Eleventy:UserConfig"); + +class UserConfigError extends EleventyBaseError {} + +/** + * Eleventy’s user-land Configuration API + * @module 11ty/eleventy/UserConfig + */ +class UserConfig { + /** @type {boolean} */ + #pluginExecution = false; + /** @type {boolean} */ + #quietModeLocked = false; + /** @type {boolean} */ + #dataDeepMergeModified = false; + /** @type {number|undefined} */ + #uniqueId; + + constructor() { + // These are completely unnecessary lines to satisfy TypeScript + this.plugins = []; + this.templateFormatsAdded = []; + this.additionalWatchTargets = []; + this.watchTargetsConfigReset = new Set(); + this.extensionMap = new Set(); + this.dataExtensions = new Map(); + this.urlTransforms = []; + this.customDateParsingCallbacks = new Set(); + this.ignores = new Set(); + this.events = new AsyncEventEmitter(); + + /** @type {object} */ + this.directories = {}; + /** @type {undefined} */ + this.logger; + /** @type {string} */ + this.dir; + /** @type {string} */ + this.pathPrefix; + /** @type {object} */ + this.errorReporting = {}; + + this.reset(); + this.#uniqueId = Math.random(); + } + + // Internally used in TemplateContent for cache keys + _getUniqueId() { + return this.#uniqueId; + } + + reset() { + debug("Resetting EleventyConfig to initial values."); + + /** @type {AsyncEventEmitter} */ + this.events = new AsyncEventEmitter(); + + /** @type {BenchmarkManager} */ + this.benchmarkManager = new BenchmarkManager(); + + /** @type {object} */ + this.benchmarks = { + /** @type {import('./Benchmark/BenchmarkGroup.js')} */ + config: this.benchmarkManager.get("Configuration"), + /** @type {import('./Benchmark/BenchmarkGroup.js')} */ + aggregate: this.benchmarkManager.get("Aggregate"), + }; + + /** @type {object} */ + this.directoryAssignments = {}; + /** @type {object} */ + this.collections = {}; + /** @type {object} */ + this.precompiledCollections = {}; + this.templateFormats = undefined; + this.templateFormatsAdded = []; + + /** @type {object} */ + this.universal = { + filters: {}, + shortcodes: {}, + pairedShortcodes: {}, + }; + + /** @type {object} */ + this.liquid = { + options: {}, + tags: {}, + filters: {}, + shortcodes: {}, + pairedShortcodes: {}, + parameterParsing: "legacy", // or builtin + }; + + /** @type {object} */ + this.nunjucks = { + // `dev: true` gives us better error messaging + environmentOptions: { dev: true }, + precompiledTemplates: {}, + filters: {}, + asyncFilters: {}, + tags: {}, + globals: {}, + shortcodes: {}, + pairedShortcodes: {}, + asyncShortcodes: {}, + asyncPairedShortcodes: {}, + }; + + /** @type {object} */ + this.javascript = { + functions: {}, + filters: {}, + shortcodes: {}, + pairedShortcodes: {}, + }; + + this.markdownHighlighter = null; + + /** @type {object} */ + this.libraryOverrides = {}; + + /** @type {object} */ + this.passthroughCopies = {}; + + /** @type {object} */ + this.layoutAliases = {}; + this.layoutResolution = true; // extension-less layout files + + /** @type {object} */ + this.linters = {}; + /** @type {object} */ + this.transforms = {}; + /** @type {object} */ + this.preprocessors = {}; + + this.activeNamespace = ""; + this.DateTime = DateTime; + this.dynamicPermalinks = true; + + this.useGitIgnore = true; + + let defaultIgnores = new Set(); + defaultIgnores.add("**/node_modules/**"); + defaultIgnores.add(".git/**"); + this.ignores = new Set(defaultIgnores); + this.watchIgnores = new Set(defaultIgnores); + + this.dataDeepMerge = true; + this.extensionMap = new Set(); + /** @type {object} */ + this.extensionConflictMap = {}; + this.watchJavaScriptDependencies = true; + this.additionalWatchTargets = []; + this.watchTargetsConfigReset = new Set(); + /** @type {object} */ + this.serverOptions = {}; + /** @type {object} */ + this.globalData = {}; + /** @type {object} */ + this.chokidarConfig = {}; + this.watchThrottleWaitTime = 0; //ms + + // using Map to preserve insertion order + this.dataExtensions = new Map(); + + this.quietMode = false; + + this.plugins = []; + + this.useTemplateCache = true; + this.dataFilterSelectors = new Set(); + + /** @type {object} */ + this.libraryAmendments = {}; + this.serverPassthroughCopyBehavior = "copy"; // or "passthrough" + this.urlTransforms = []; + + // Defaults in `defaultConfig.js` + this.dataFileSuffixesOverride = false; + this.dataFileDirBaseNameOverride = false; + + /** @type {object} */ + this.frontMatterParsingOptions = { + // Set a project-wide default. + // language: "yaml", + + // Supplementary engines + engines: { + yaml: yaml.load.bind(yaml), + + // Backwards compatible with `js` object front matter + // https://github.com/11ty/eleventy/issues/2819 + javascript: JavaScriptFrontMatter, + + // Needed for fallback behavior in the new `javascript` engine + // @ts-ignore + jsLegacy: matter.engines.javascript, + + node: function () { + throw new Error( + "The `node` front matter type was a 3.0.0-alpha.x only feature, removed for stable release. Rename to `js` or `javascript` instead!", + ); + }, + }, + }; + + /** @type {object} */ + this.virtualTemplates = {}; + this.freezeReservedData = true; + this.customDateParsingCallbacks = new Set(); + + /** @type {object} */ + this.errorReporting = {}; + } + + // compatibleRange is optional in 2.0.0-beta.2 + versionCheck(compatibleRange) { + let compat = new EleventyCompatibility(compatibleRange); + + if (!compat.isCompatible()) { + throw new UserConfigError(compat.getErrorMessage()); + } + } + + /* + * Events + */ + + // Duplicate event bindings are avoided with the `reset` method above. + // A new EventEmitter instance is created when the config is reset. + on(eventName, callback) { + return this.events.on(eventName, callback); + } + + once(eventName, callback) { + return this.events.once(eventName, callback); + } + + emit(eventName, ...args) { + return this.events.emit(eventName, ...args); + } + + setEventEmitterMode(mode) { + this.events.setHandlerMode(mode); + } + + /* + * Universal getters + */ + getFilter(name) { + // JavaScript functions are included here for backwards compatibility https://github.com/11ty/eleventy/issues/3365 + return this.universal.filters[name] || this.javascript.functions[name]; + } + + getFilters(options = {}) { + if (options.type) { + return objectFilter( + this.universal.filters, + (entry) => entry.__eleventyInternal?.type === options.type, + ); + } + + return this.universal.filters; + } + + getShortcode(name) { + return this.universal.shortcodes[name]; + } + + getShortcodes(options = {}) { + if (options.type) { + return objectFilter( + this.universal.shortcodes, + (entry) => entry.__eleventyInternal?.type === options.type, + ); + } + + return this.universal.shortcodes; + } + + getPairedShortcode(name) { + return this.universal.pairedShortcodes[name]; + } + + getPairedShortcodes(options = {}) { + if (options.type) { + return objectFilter( + this.universal.pairedShortcodes, + (entry) => entry.__eleventyInternal?.type === options.type, + ); + } + return this.universal.pairedShortcodes; + } + + /* + * Private utilities + */ + #add(target, originalName, callback, options) { + let { description, functionName } = options; + + if (typeof callback !== "function") { + throw new Error(`Invalid definition for "${originalName}" ${description}.`); + } + + let name = this.getNamespacedName(originalName); + + if (target[name]) { + debug( + chalk.yellow(`Warning, overwriting previous ${description} "%o" via \`%o(%o)\``), + name, + functionName, + originalName, + ); + } else { + debug(`Adding new ${description} "%o" via \`%o(%o)\``, name, functionName, originalName); + } + + target[name] = this.#decorateCallback(`"${name}" ${description}`, callback); + } + + #decorateCallback(type, callback) { + return this.benchmarks.config.add(type, callback); + } + + /* + * Markdown + */ + + // This is a method for plugins, probably shouldn’t use this in projects. + // Projects should use `setLibrary` as documented here: + // https://github.com/11ty/eleventy/blob/master/docs/engines/markdown.md#use-your-own-options + addMarkdownHighlighter(highlightFn) { + this.markdownHighlighter = highlightFn; + } + + /* + * Filters + */ + + addLiquidFilter(name, callback) { + this.#add(this.liquid.filters, name, callback, { + description: "Liquid Filter", + functionName: "addLiquidFilter", + }); + } + + addNunjucksAsyncFilter(name, callback) { + this.#add(this.nunjucks.asyncFilters, name, callback, { + description: "Nunjucks Filter", + functionName: "addNunjucksAsyncFilter", + }); + } + + // Support the nunjucks style syntax for asynchronous filter add + addNunjucksFilter(name, callback, isAsync = false) { + if (isAsync) { + // namespacing happens downstream + this.addNunjucksAsyncFilter(name, callback); + } else { + this.#add(this.nunjucks.filters, name, callback, { + description: "Nunjucks Filter", + functionName: "addNunjucksFilter", + }); + } + } + + addJavaScriptFilter(name, callback) { + this.#add(this.javascript.filters, name, callback, { + description: "JavaScript Filter", + functionName: "addJavaScriptFilter", + }); + + // Backwards compat for a time before `addJavaScriptFilter` existed. + this.addJavaScriptFunction(name, callback); + } + + addFilter(name, callback) { + // This method *requires* `async function` and will not work with `function` that returns a promise + if (isAsyncFunction(callback)) { + this.addAsyncFilter(name, callback); + return; + } + + // namespacing happens downstream + this.#add(this.universal.filters, name, callback, { + description: "Universal Filter", + functionName: "addFilter", + }); + + this.addLiquidFilter(name, callback); + this.addJavaScriptFilter(name, callback); + this.addNunjucksFilter( + name, + /** @this {any} */ + function (...args) { + // Note that `callback` is already a function as the `#add` method throws an error if not. + let ret = callback.call(this, ...args); + if (ret instanceof Promise) { + throw new Error( + `Nunjucks *is* async-friendly with \`addFilter("${name}", async function() {})\` but you need to supply an \`async function\`. You returned a promise from \`addFilter("${name}", function() {})\`. Alternatively, use the \`addAsyncFilter("${name}")\` configuration API method.`, + ); + } + return ret; + }, + ); + } + + // Liquid, Nunjucks, and JS only + addAsyncFilter(name, callback) { + // namespacing happens downstream + this.#add(this.universal.filters, name, callback, { + description: "Universal Filter", + functionName: "addAsyncFilter", + }); + + this.addLiquidFilter(name, callback); + this.addJavaScriptFilter(name, callback); + this.addNunjucksAsyncFilter( + name, + /** @this {any} */ + async function (...args) { + let cb = args.pop(); + // Note that `callback` is already a function as the `#add` method throws an error if not. + let ret = await callback.call(this, ...args); + cb(null, ret); + }, + ); + } + + /* + * Shortcodes + */ + + addShortcode(name, callback) { + // This method *requires* `async function` and will not work with `function` that returns a promise + if (isAsyncFunction(callback)) { + this.addAsyncShortcode(name, callback); + return; + } + + this.#add(this.universal.shortcodes, name, callback, { + description: "Universal Shortcode", + functionName: "addShortcode", + }); + + this.addLiquidShortcode(name, callback); + this.addJavaScriptShortcode(name, callback); + this.addNunjucksShortcode(name, callback); + } + + addAsyncShortcode(name, callback) { + this.#add(this.universal.shortcodes, name, callback, { + description: "Universal Shortcode", + functionName: "addAsyncShortcode", + }); + + // Related: #498 + this.addNunjucksAsyncShortcode(name, callback); + this.addLiquidShortcode(name, callback); + this.addJavaScriptShortcode(name, callback); + } + + addNunjucksAsyncShortcode(name, callback) { + this.#add(this.nunjucks.asyncShortcodes, name, callback, { + description: "Nunjucks Async Shortcode", + functionName: "addNunjucksAsyncShortcode", + }); + } + + addNunjucksShortcode(name, callback, isAsync = false) { + if (isAsync) { + this.addNunjucksAsyncShortcode(name, callback); + } else { + this.#add(this.nunjucks.shortcodes, name, callback, { + description: "Nunjucks Shortcode", + functionName: "addNunjucksShortcode", + }); + } + } + + addLiquidShortcode(name, callback) { + this.#add(this.liquid.shortcodes, name, callback, { + description: "Liquid Shortcode", + functionName: "addLiquidShortcode", + }); + } + + addPairedShortcode(name, callback) { + // This method *requires* `async function` and will not work with `function` that returns a promise + if (isAsyncFunction(callback)) { + this.addPairedAsyncShortcode(name, callback); + return; + } + + this.#add(this.universal.pairedShortcodes, name, callback, { + description: "Universal Paired Shortcode", + functionName: "addPairedShortcode", + }); + + this.addPairedNunjucksShortcode(name, callback); + this.addPairedLiquidShortcode(name, callback); + this.addPairedJavaScriptShortcode(name, callback); + } + + // Related: #498 + addPairedAsyncShortcode(name, callback) { + this.#add(this.universal.pairedShortcodes, name, callback, { + description: "Universal Paired Async Shortcode", + functionName: "addPairedAsyncShortcode", + }); + + this.addPairedNunjucksAsyncShortcode(name, callback); + this.addPairedLiquidShortcode(name, callback); + this.addPairedJavaScriptShortcode(name, callback); + } + + addPairedNunjucksAsyncShortcode(name, callback) { + this.#add(this.nunjucks.asyncPairedShortcodes, name, callback, { + description: "Nunjucks Async Paired Shortcode", + functionName: "addPairedNunjucksAsyncShortcode", + }); + } + + addPairedNunjucksShortcode(name, callback, isAsync = false) { + if (isAsync) { + this.addPairedNunjucksAsyncShortcode(name, callback); + } else { + this.#add(this.nunjucks.pairedShortcodes, name, callback, { + description: "Nunjucks Paired Shortcode", + functionName: "addPairedNunjucksShortcode", + }); + } + } + + addPairedLiquidShortcode(name, callback) { + this.#add(this.liquid.pairedShortcodes, name, callback, { + description: "Liquid Paired Shortcode", + functionName: "addPairedLiquidShortcode", + }); + } + + addJavaScriptShortcode(name, callback) { + this.#add(this.javascript.shortcodes, name, callback, { + description: "JavaScript Shortcode", + functionName: "addJavaScriptShortcode", + }); + + // Backwards compat for a time before `addJavaScriptShortcode` existed. + this.addJavaScriptFunction(name, callback); + } + + addPairedJavaScriptShortcode(name, callback) { + this.#add(this.javascript.pairedShortcodes, name, callback, { + description: "JavaScript Paired Shortcode", + functionName: "addPairedJavaScriptShortcode", + }); + + // Backwards compat for a time before `addJavaScriptShortcode` existed. + this.addJavaScriptFunction(name, callback); + } + + // Both Filters and shortcodes feed into this + addJavaScriptFunction(name, callback) { + this.#add(this.javascript.functions, name, callback, { + description: "JavaScript Function", + functionName: "addJavaScriptFunction", + }); + } + + /* + * Custom Tags + */ + + // tagCallback: function(liquidEngine) { return { parse: …, render: … }} }; + addLiquidTag(name, tagFn) { + if (typeof tagFn !== "function") { + throw new UserConfigError( + `EleventyConfig.addLiquidTag expects a callback function to be passed in for ${name}: addLiquidTag(name, function(liquidEngine) { return { parse: …, render: … } })`, + ); + } + + this.#add(this.liquid.tags, name, tagFn, { + description: "Liquid Custom Tag", + functionName: "addLiquidTag", + }); + } + + addNunjucksTag(name, tagFn) { + if (typeof tagFn !== "function") { + throw new UserConfigError( + `EleventyConfig.addNunjucksTag expects a callback function to be passed in for ${name}: addNunjucksTag(name, function(nunjucksEngine) {})`, + ); + } + + this.#add(this.nunjucks.tags, name, tagFn, { + description: "Nunjucks Custom Tag", + functionName: "addNunjucksTag", + }); + } + + /* + * Plugins + */ + + // Internal method + _enablePluginExecution() { + this.#pluginExecution = true; + } + + // Internal method + _disablePluginExecution() { + this.#pluginExecution = false; + } + + /* Config is executed in two stages and plugins are the second stage—are we in the plugins stage? */ + isPluginExecution() { + return this.#pluginExecution; + } + + /** + * @typedef {function|Promise|object} PluginDefinition + * @property {Function} [configFunction] + * @property {string} [eleventyPackage] + * @property {object} [eleventyPluginOptions={}] + * @property {boolean} [eleventyPluginOptions.unique] + */ + + /** + * addPlugin: async friendly in 3.0 + * + * @param {PluginDefinition} plugin + */ + addPlugin(plugin, options = {}) { + // First addPlugin of a unique plugin wins + if (plugin?.eleventyPluginOptions?.unique && this.hasPlugin(plugin)) { + debug("Skipping duplicate unique addPlugin for %o", this._getPluginName(plugin)); + return; + } + + if (this.isPluginExecution() || options?.immediate) { + // this might return a promise + return this._executePlugin(plugin, options); + } else { + this.plugins.push({ + plugin, + options, + pluginNamespace: this.activeNamespace, + }); + } + } + + /** @param {string} name */ + resolvePlugin(name) { + let filenameLookup = { + "@11ty/eleventy/html-base-plugin": HtmlBasePlugin, + "@11ty/eleventy/render-plugin": RenderPlugin, + "@11ty/eleventy/inputpath-to-url-plugin": InputPathToUrlPlugin, + + // Async plugins: + // requires e.g. `await resolvePlugin("@11ty/eleventy/i18n-plugin")` to avoid preloading i18n dependencies. + // see https://github.com/11ty/eleventy-plugin-rss/issues/52 + "@11ty/eleventy/i18n-plugin": "./Plugins/I18nPlugin.js", + }; + + if (!filenameLookup[name]) { + throw new Error( + `Invalid name "${name}" passed to resolvePlugin. Valid options: ${Object.keys(filenameLookup).join(", ")}`, + ); + } + + // Future improvement: add support for any npm package name? + if (typeof filenameLookup[name] === "string") { + // returns promise + return import(filenameLookup[name]).then((plugin) => plugin.default); + } + + // return reference + return filenameLookup[name]; + } + + /** @param {string|PluginDefinition} plugin */ + hasPlugin(plugin) { + let pluginName; + if (typeof plugin === "string") { + pluginName = plugin; + } else { + pluginName = this._getPluginName(plugin); + } + + return this.plugins.some((entry) => this._getPluginName(entry.plugin) === pluginName); + } + + // Using Function.name https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#examples + /** @param {PluginDefinition} plugin */ + _getPluginName(plugin) { + if (plugin?.eleventyPackage) { + return plugin.eleventyPackage; + } + if (typeof plugin === "function") { + return plugin.name; + } + if (plugin?.configFunction && typeof plugin.configFunction === "function") { + return plugin.configFunction.name; + } + } + + // Starting in 3.0 the plugin callback might be asynchronous! + _executePlugin(plugin, options) { + let name = this._getPluginName(plugin); + let ret; + debug(`Adding %o plugin`, name || "anonymous"); + let pluginBenchmark = this.benchmarks.aggregate.get("Configuration addPlugin"); + + if (typeof plugin === "function") { + pluginBenchmark.before(); + this.benchmarks.config; + let configFunction = plugin; + ret = configFunction(this, options); + pluginBenchmark.after(); + } else if (plugin?.configFunction) { + pluginBenchmark.before(); + + if (options && typeof options.init === "function") { + // init is not yet async-friendly but it’s also barely used + options.init.call(this, plugin.initArguments || {}); + } + + ret = plugin.configFunction(this, options); + pluginBenchmark.after(); + } else { + throw new UserConfigError( + "Invalid EleventyConfig.addPlugin signature. Should be a function or a valid Eleventy plugin object.", + ); + } + return ret; + } + + /** @param {string} name */ + getNamespacedName(name) { + return this.activeNamespace + name; + } + + async namespace(pluginNamespace, callback) { + let validNamespace = pluginNamespace && typeof pluginNamespace === "string"; + if (validNamespace) { + this.activeNamespace = pluginNamespace || ""; + } + + await callback(this); + + if (validNamespace) { + this.activeNamespace = ""; + } + } + + /** + * Adds a path to a file or directory to the list of pass-through copies + * which are copied as-is to the output. + * + * @param {string|object} fileOrDir The path to the file or directory that should + * be copied. OR an object where the key is the input glob and the property is the output directory + * @param {object} copyOptions options for recursive-copy. + * see https://www.npmjs.com/package/recursive-copy#arguments + * default options are defined in TemplatePassthrough copyOptionsDefault + * @returns {any} a reference to the `EleventyConfig` object. + */ + addPassthroughCopy(fileOrDir, copyOptions = {}) { + if (typeof fileOrDir === "string") { + this.passthroughCopies[fileOrDir] = { outputPath: true, copyOptions }; + } else { + for (let [inputPath, outputPath] of Object.entries(fileOrDir)) { + this.passthroughCopies[inputPath] = { outputPath, copyOptions }; + } + } + + return this; + } + + /* + * Template Formats + */ + _normalizeTemplateFormats() { + throw new Error("The internal _normalizeTemplateFormats() method was removed in Eleventy 3.0"); + } + + setTemplateFormats(templateFormats) { + this.templateFormats = templateFormats; + } + + // additive, usually for plugins + addTemplateFormats(templateFormats) { + this.templateFormatsAdded.push(templateFormats); + } + + /* + * Library Overrides and Options + */ + setLibrary(engineName, libraryInstance) { + if (engineName === "liquid" && Object.keys(this.liquid.options).length) { + debug( + "WARNING: using `eleventyConfig.setLibrary` will override any configuration set using `.setLiquidOptions` via the config API. You’ll need to pass these options to the library yourself.", + ); + } else if (engineName === "njk" && Object.keys(this.nunjucks.environmentOptions).length) { + debug( + "WARNING: using `eleventyConfig.setLibrary` will override any configuration set using `.setNunjucksEnvironmentOptions` via the config API. You’ll need to pass these options to the library yourself.", + ); + } + + this.libraryOverrides[engineName.toLowerCase()] = libraryInstance; + } + + /* These callbacks run on both libraryOverrides and default library instances */ + amendLibrary(engineName, callback) { + let name = engineName.toLowerCase(); + if (!this.libraryAmendments[name]) { + this.libraryAmendments[name] = []; + } + + this.libraryAmendments[name].push(callback); + } + + setLiquidOptions(options) { + this.liquid.options = options; + } + + setLiquidParameterParsing(behavior) { + if (behavior !== "legacy" && behavior !== "builtin") { + throw new Error( + `Invalid argument passed to \`setLiquidParameterParsing\`. Expected one of "legacy" or "builtin".`, + ); + } + this.liquid.parameterParsing = behavior; + } + + setNunjucksEnvironmentOptions(options) { + this.nunjucks.environmentOptions = options; + } + + setNunjucksPrecompiledTemplates(templates) { + this.nunjucks.precompiledTemplates = templates; + } + + setDynamicPermalinks(enabled) { + this.dynamicPermalinks = !!enabled; + } + + setUseGitIgnore(enabled) { + this.useGitIgnore = !!enabled; + } + + setDataDeepMerge(deepMerge) { + this.#dataDeepMergeModified = true; + this.dataDeepMerge = !!deepMerge; + } + + // Used by the Upgrade Helper Plugin + isDataDeepMergeModified() { + return this.#dataDeepMergeModified; + } + + addWatchTarget(additionalWatchTargets, options = {}) { + // Reset the config when the target path changes + if (options.resetConfig) { + this.watchTargetsConfigReset.add(additionalWatchTargets); + } + + this.additionalWatchTargets.push(additionalWatchTargets); + } + + setWatchJavaScriptDependencies(watchEnabled) { + this.watchJavaScriptDependencies = !!watchEnabled; + } + + setServerOptions(options = {}, override = false) { + if (override) { + this.serverOptions = options; + } else { + this.serverOptions = DeepCopy(this.serverOptions, options); + } + } + + setBrowserSyncConfig() { + this._attemptedBrowserSyncUse = true; + debug( + "The `setBrowserSyncConfig` method was removed in Eleventy 2.0.0. Use `setServerOptions` with the new Eleventy development server or the `@11ty/eleventy-browser-sync` plugin moving forward.", + ); + } + + setChokidarConfig(options = {}) { + this.chokidarConfig = options; + } + + setWatchThrottleWaitTime(time = 0) { + this.watchThrottleWaitTime = time; + } + + // 3.0 change: this does a top level merge instead of reset. + setFrontMatterParsingOptions(options = {}) { + DeepCopy(this.frontMatterParsingOptions, options); + } + + /* Internal method for CLI --quiet */ + _setQuietModeOverride(quietMode) { + this.setQuietMode(quietMode); + this.#quietModeLocked = true; + } + + setQuietMode(quietMode) { + if (this.#quietModeLocked) { + debug( + "Attempt to `setQuietMode(%o)` ignored, --quiet command line argument override in place.", + !!quietMode, + ); + // override via CLI takes precedence + return; + } + + this.quietMode = !!quietMode; + } + + addExtension(fileExtension, options = {}) { + let extensions; + + // Array support added in 2.0.0-canary.19 + if (Array.isArray(fileExtension)) { + extensions = fileExtension; + } else { + // single string + extensions = [fileExtension]; + } + + for (let extension of extensions) { + if (this.extensionConflictMap[extension]) { + throw new Error( + `An attempt was made to override the "${extension}" template syntax twice (via the \`addExtension\` configuration API). A maximum of one override is currently supported.`, + ); + } + this.extensionConflictMap[extension] = true; + + /** @type {object} */ + let extensionOptions = Object.assign( + { + // Might be overridden for aliasing in options.key + key: extension, + extension: extension, + }, + options, + ); + + if (extensionOptions.key !== extensionOptions.extension) { + extensionOptions.aliasKey = extensionOptions.extension; + } + + this.extensionMap.add(extensionOptions); + } + } + + addDataExtension(extensionList, parser) { + let options = {}; + // second argument is an object with a `parser` callback + if (typeof parser !== "function") { + if (!("parser" in parser)) { + throw new Error( + "Expected `parser` property in second argument object to `eleventyConfig.addDataExtension`", + ); + } + + options = parser; + parser = options.parser; + } + + let extensions = extensionList.split(",").map((s) => s.trim()); + for (let extension of extensions) { + this.dataExtensions.set(extension, { + extension, + parser, + options, + }); + } + } + + setUseTemplateCache(bypass) { + this.useTemplateCache = !!bypass; + } + + setPrecompiledCollections(collections) { + this.precompiledCollections = collections; + } + + // "passthrough" is the default, no other value is explicitly required in code + // but opt-out via "copy" is suggested + setServerPassthroughCopyBehavior(behavior) { + this.serverPassthroughCopyBehavior = behavior; + } + + // Url transforms change page.url and work good with server side content-negotiation (e.g. i18n plugin) + addUrlTransform(callback) { + this.urlTransforms.push(callback); + } + + setDataFileSuffixes(suffixArray) { + this.dataFileSuffixesOverride = suffixArray; + } + + setDataFileBaseName(baseName) { + this.dataFileDirBaseNameOverride = baseName; + } + + addTemplate(virtualInputPath, content, data) { + // Lookups keys must be normalized + virtualInputPath = TemplatePath.stripLeadingDotSlash( + TemplatePath.standardizeFilePath(virtualInputPath), + ); + if (this.virtualTemplates[virtualInputPath]) { + throw new Error( + "Virtual template conflict: you can’t add multiple virtual templates that have the same inputPath: " + + virtualInputPath, + ); + } + + this.virtualTemplates[virtualInputPath] = { + inputPath: virtualInputPath, + data, + content, + }; + } + + isVirtualTemplate(virtualInputPath) { + return Boolean(this.virtualTemplates[virtualInputPath]); + } + + #setDirectory(key, dir) { + if (this.isPluginExecution()) { + throw new Error( + "The `set*Directory` configuration API methods are not yet allowed in plugins.", + ); + } + this.directoryAssignments[key] = dir; + } + + setInputDirectory(dir) { + this.#setDirectory("input", dir); + } + + setOutputDirectory(dir) { + this.#setDirectory("output", dir); + } + + setDataDirectory(dir) { + this.#setDirectory("data", dir); + } + + setIncludesDirectory(dir) { + this.#setDirectory("includes", dir); + } + + setLayoutsDirectory(dir) { + this.#setDirectory("layouts", dir); + } + + // Some data keywords in Eleventy are reserved, throw an error if an application tries to set these. + setFreezeReservedData(bool) { + this.freezeReservedData = !!bool; + } + + addDateParsing(callback) { + if (typeof callback === "function") { + this.customDateParsingCallbacks.add(callback); + } else { + throw new Error("addDateParsing expects a function argument."); + } + } + + // 3.0.0-alpha.18 started merging conflicts here (when possible), issue #3389 + addGlobalData(name, data) { + name = this.getNamespacedName(name); + if (this.globalData[name]) { + if (isPlainObject(this.globalData[name]) && isPlainObject(data)) { + DeepCopy(this.globalData[name], data); + } else { + debug("Warning: overwriting a previous value set with addGlobalData(%o)", name); + this.globalData[name] = data; + } + } else { + this.globalData[name] = data; + } + return this; + } + + addNunjucksGlobal(name, globalType) { + name = this.getNamespacedName(name); + + if (this.nunjucks.globals[name]) { + debug( + chalk.yellow("Warning, overwriting a Nunjucks global with `addNunjucksGlobal(%o)`"), + name, + ); + } + + if (typeof globalType === "function") { + this.nunjucks.globals[name] = this.#decorateCallback(`"${name}" Nunjucks Global`, globalType); + } else { + this.nunjucks.globals[name] = globalType; + } + } + + addTransform(name, callback) { + name = this.getNamespacedName(name); + + this.transforms[name] = this.#decorateCallback(`"${name}" Transform`, callback); + } + + addPreprocessor(name, fileExtensions, callback) { + name = this.getNamespacedName(name); + + this.preprocessors[name] = { + filter: fileExtensions, + callback: this.#decorateCallback(`"${name}" Preprocessor`, callback), + }; + } + + addLinter(name, callback) { + name = this.getNamespacedName(name); + + this.linters[name] = this.#decorateCallback(`"${name}" Linter`, callback); + } + + addLayoutAlias(from, to) { + this.layoutAliases[from] = to; + } + + setLayoutResolution(resolution) { + this.layoutResolution = !!resolution; + } + + // compat + enableLayoutResolution() { + this.layoutResolution = true; + } + + configureErrorReporting(options = {}) { + // allowMissingExtensions: true + Object.assign(this.errorReporting, options); + } + + /* + * Collections + */ + + // get config defined collections + getCollections() { + return this.collections; + } + + addCollection(name, callback) { + name = this.getNamespacedName(name); + + if (this.collections[name]) { + throw new UserConfigError( + `config.addCollection(${name}) already exists. Try a different name for your collection.`, + ); + } + + this.collections[name] = callback; + } + + augmentFunctionContext(fn, options) { + let t = typeof fn; + if (t !== "function") { + throw new UserConfigError( + "Invalid type passed to `augmentFunctionContext`—function was expected and received: " + t, + ); + } + + return augmentFunction(fn, options); + } + + getMergingConfigObject() { + let obj = { + // filters removed in 1.0 (use addTransform instead) + transforms: this.transforms, + linters: this.linters, + preprocessors: this.preprocessors, + globalData: this.globalData, + layoutAliases: this.layoutAliases, + layoutResolution: this.layoutResolution, + passthroughCopies: this.passthroughCopies, + + // Liquid + liquidOptions: this.liquid.options, + liquidTags: this.liquid.tags, + liquidFilters: this.liquid.filters, + liquidShortcodes: this.liquid.shortcodes, + liquidPairedShortcodes: this.liquid.pairedShortcodes, + liquidParameterParsing: this.liquid.parameterParsing, + + // Nunjucks + nunjucksEnvironmentOptions: this.nunjucks.environmentOptions, + nunjucksPrecompiledTemplates: this.nunjucks.precompiledTemplates, + nunjucksFilters: this.nunjucks.filters, + nunjucksAsyncFilters: this.nunjucks.asyncFilters, + nunjucksTags: this.nunjucks.tags, + nunjucksGlobals: this.nunjucks.globals, + nunjucksAsyncShortcodes: this.nunjucks.asyncShortcodes, + nunjucksShortcodes: this.nunjucks.shortcodes, + nunjucksAsyncPairedShortcodes: this.nunjucks.asyncPairedShortcodes, + nunjucksPairedShortcodes: this.nunjucks.pairedShortcodes, + + // 11ty.js + javascriptFunctions: this.javascript.functions, // filters and shortcodes, combined + javascriptShortcodes: this.javascript.shortcodes, + javascriptPairedShortcodes: this.javascript.pairedShortcodes, + javascriptFilters: this.javascript.filters, + + // Markdown + markdownHighlighter: this.markdownHighlighter, + + libraryOverrides: this.libraryOverrides, + dynamicPermalinks: this.dynamicPermalinks, + useGitIgnore: this.useGitIgnore, + ignores: this.ignores, + watchIgnores: this.watchIgnores, + dataDeepMerge: this.dataDeepMerge, + watchJavaScriptDependencies: this.watchJavaScriptDependencies, + additionalWatchTargets: this.additionalWatchTargets, + watchTargetsConfigReset: this.watchTargetsConfigReset, + serverOptions: this.serverOptions, + chokidarConfig: this.chokidarConfig, + watchThrottleWaitTime: this.watchThrottleWaitTime, + frontMatterParsingOptions: this.frontMatterParsingOptions, + dataExtensions: this.dataExtensions, + extensionMap: this.extensionMap, + quietMode: this.quietMode, + events: this.events, + benchmarkManager: this.benchmarkManager, + plugins: this.plugins, + useTemplateCache: this.useTemplateCache, + precompiledCollections: this.precompiledCollections, + dataFilterSelectors: this.dataFilterSelectors, + libraryAmendments: this.libraryAmendments, + serverPassthroughCopyBehavior: this.serverPassthroughCopyBehavior, + urlTransforms: this.urlTransforms, + virtualTemplates: this.virtualTemplates, + // `directories` and `directoryAssignments` are merged manually prior to plugin processing + freezeReservedData: this.freezeReservedData, + customDateParsing: this.customDateParsingCallbacks, + errorReporting: this.errorReporting, + }; + + if (Array.isArray(this.dataFileSuffixesOverride)) { + // no upstream merging of this array, so we add the override: prefix + obj["override:dataFileSuffixes"] = this.dataFileSuffixesOverride; + } + + if (this.dataFileDirBaseNameOverride) { + obj.dataFileDirBaseNameOverride = this.dataFileDirBaseNameOverride; + } + + return obj; + } + + // No-op functions for backwards compat + addHandlebarsHelper() {} + setPugOptions() {} + setEjsOptions() {} + addHandlebarsShortcode() {} + addPairedHandlebarsShortcode() {} +} + +export default UserConfig; diff --git a/node_modules/@11ty/eleventy/src/Util/AsyncEventEmitter.js b/node_modules/@11ty/eleventy/src/Util/AsyncEventEmitter.js new file mode 100644 index 0000000..cb3dd3d --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/AsyncEventEmitter.js @@ -0,0 +1,75 @@ +import { EventEmitter } from "node:events"; + +/** + * This class emits events asynchronously. + * It can be used for time measurements during a build. + */ +class AsyncEventEmitter extends EventEmitter { + #handlerMode = "parallel"; + + // TypeScript slop + constructor(...args) { + super(...args); + } + + /** + * @param {string} type - The event name to emit. + * @param {...*} args - Additional arguments that get passed to listeners. + * @returns {Promise} - Promise resolves once all listeners were invoked + */ + /** @ts-expect-error */ + async emit(type, ...args) { + let listeners = this.listeners(type); + if (listeners.length === 0) { + return []; + } + + if (this.#handlerMode == "sequential") { + const result = []; + for (const listener of listeners) { + const returnValue = await listener.apply(this, args); + result.push(returnValue); + } + return result; + } else { + return Promise.all( + listeners.map((listener) => { + return listener.apply(this, args); + }), + ); + } + } + + /** + * @param {string} type - The event name to emit. + * @param {...*} args - Additional lazy-executed function arguments that get passed to listeners. + * @returns {Promise} - Promise resolves once all listeners were invoked + */ + async emitLazy(type, ...args) { + let listeners = this.listeners(type); + if (listeners.length === 0) { + return []; + } + + let argsMap = []; + for (let arg of args) { + if (typeof arg === "function") { + let r = arg(); + if (r instanceof Promise) { + r = await r; + } + argsMap.push(r); + } else { + argsMap.push(arg); + } + } + + return this.emit.call(this, type, ...argsMap); + } + + setHandlerMode(mode) { + this.#handlerMode = mode; + } +} + +export default AsyncEventEmitter; diff --git a/node_modules/@11ty/eleventy/src/Util/Compatibility.js b/node_modules/@11ty/eleventy/src/Util/Compatibility.js new file mode 100644 index 0000000..514217e --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/Compatibility.js @@ -0,0 +1,55 @@ +import semver from "semver"; +import debugUtil from "debug"; + +import { getEleventyPackageJson, getWorkingProjectPackageJson } from "./ImportJsonSync.js"; + +const pkg = getEleventyPackageJson(); +const debug = debugUtil("Eleventy:Compatibility"); + +// Used in user config versionCheck method. +class Compatibility { + static NORMALIZE_PRERELEASE_REGEX = /-canary\b/g; + + constructor(compatibleRange) { + this.compatibleRange = Compatibility.getCompatibilityValue(compatibleRange); + } + + static normalizeIdentifier(identifier) { + return identifier.replace(Compatibility.NORMALIZE_PRERELEASE_REGEX, "-alpha"); + } + + static getCompatibilityValue(compatibleRange) { + if (compatibleRange) { + return compatibleRange; + } + + try { + // fetch from project’s package.json + let projectPackageJson = getWorkingProjectPackageJson(); + return projectPackageJson["11ty"]?.compatibility; + } catch (e) { + debug("Could not find a project package.json for compatibility version check: %O", e); + return; // do nothing, no compatibility information to check + } + } + + isCompatible() { + return Compatibility.satisfies(pkg.version, this.compatibleRange); + } + + static satisfies(version, compatibleRange) { + return semver.satisfies( + Compatibility.normalizeIdentifier(version), + Compatibility.normalizeIdentifier(compatibleRange), + { + includePrerelease: true, + }, + ); + } + + getErrorMessage() { + return `We found Eleventy version '${pkg.version}' which does not meet the required version range: '${this.compatibleRange}'. Use \`npm install @11ty/eleventy\` to upgrade your local project to the latest Eleventy version (or \`npm install @11ty/eleventy -g\` to upgrade the globally installed version).`; + } +} + +export default Compatibility; diff --git a/node_modules/@11ty/eleventy/src/Util/ConsoleLogger.js b/node_modules/@11ty/eleventy/src/Util/ConsoleLogger.js new file mode 100644 index 0000000..7ac5f4d --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/ConsoleLogger.js @@ -0,0 +1,126 @@ +import { Readable } from "node:stream"; +import chalk from "kleur"; +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:Logger"); + +/** + * Logger implementation that logs to STDOUT. + * @typedef {'error'|'log'|'warn'|'info'} LogType + */ +class ConsoleLogger { + /** @type {boolean} */ + #isVerbose = true; + /** @type {boolean} */ + #isChalkEnabled = true; + /** @type {object|boolean|undefined} */ + #logger; + + constructor() { + this.outputStream = new Readable({ + read() {}, + }); + } + + get isVerbose() { + return this.#isVerbose; + } + + set isVerbose(verbose) { + this.#isVerbose = !!verbose; + } + + get isChalkEnabled() { + return this.#isChalkEnabled; + } + + set isChalkEnabled(enabled) { + this.#isChalkEnabled = !!enabled; + } + + overrideLogger(logger) { + this.#logger = logger; + } + + get logger() { + return this.#logger || console; + } + + /** @param {string} msg */ + log(msg) { + this.message(msg); + } + + /** + * @typedef LogOptions + * @property {string} message + * @property {string=} prefix + * @property {LogType=} type + * @property {string=} color + * @property {boolean=} force + * @param {LogOptions} options + */ + logWithOptions({ message, type, prefix, color, force }) { + this.message(message, type, color, force, prefix); + } + + /** @param {string} msg */ + forceLog(msg) { + this.message(msg, undefined, undefined, true); + } + + /** @param {string} msg */ + info(msg) { + this.message(msg, "warn", "blue"); + } + + /** @param {string} msg */ + warn(msg) { + this.message(msg, "warn", "yellow"); + } + + /** @param {string} msg */ + error(msg) { + this.message(msg, "error", "red"); + } + + /** @param {string} msg */ + toStream(msg) { + this.outputStream.push(msg); + } + + closeStream() { + this.outputStream.push(null); + return this.outputStream; + } + + /** + * Formats the message to log. + * + * @param {string} message - The raw message to log. + * @param {LogType} [type='log'] - The error level to log. + * @param {string|undefined} [chalkColor=undefined] - Color name or falsy to disable + * @param {boolean} [forceToConsole=false] - Enforce a log on console instead of specified target. + */ + message( + message, + type = "log", + chalkColor = undefined, + forceToConsole = false, + prefix = "[11ty]", + ) { + if (!forceToConsole && (!this.isVerbose || process.env.DEBUG)) { + debug(message); + } else if (this.#logger !== false) { + message = `${chalk.gray(prefix)} ${message.split("\n").join(`\n${chalk.gray(prefix)} `)}`; + + if (chalkColor && this.isChalkEnabled) { + this.logger[type](chalk[chalkColor](message)); + } else { + this.logger[type](message); + } + } + } +} + +export default ConsoleLogger; diff --git a/node_modules/@11ty/eleventy/src/Util/DateGitFirstAdded.js b/node_modules/@11ty/eleventy/src/Util/DateGitFirstAdded.js new file mode 100644 index 0000000..da2488f --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/DateGitFirstAdded.js @@ -0,0 +1,24 @@ +import spawn from "cross-spawn"; + +function getGitFirstAddedTimeStamp(filePath) { + return ( + parseInt( + spawn + .sync( + "git", + // Formats https://www.git-scm.com/docs/git-log#_pretty_formats + // %at author date, UNIX timestamp + ["log", "--diff-filter=A", "--follow", "-1", "--format=%at", filePath], + ) + .stdout.toString("utf-8"), + ) * 1000 + ); +} + +// return a Date +export default function (inputPath) { + let timestamp = getGitFirstAddedTimeStamp(inputPath); + if (timestamp) { + return new Date(timestamp); + } +} diff --git a/node_modules/@11ty/eleventy/src/Util/DateGitLastUpdated.js b/node_modules/@11ty/eleventy/src/Util/DateGitLastUpdated.js new file mode 100644 index 0000000..b06d182 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/DateGitLastUpdated.js @@ -0,0 +1,28 @@ +import spawn from "cross-spawn"; + +/* Thank you to Vuepress! + * https://github.com/vuejs/vuepress/blob/89440ce552675859189ed4ab254ce19c4bba5447/packages/%40vuepress/plugin-last-updated/index.js + * MIT licensed: https://github.com/vuejs/vuepress/blob/89440ce552675859189ed4ab254ce19c4bba5447/LICENSE + */ +function getGitLastUpdatedTimeStamp(filePath) { + return ( + parseInt( + spawn + .sync( + "git", + // Formats https://www.git-scm.com/docs/git-log#_pretty_formats + // %at author date, UNIX timestamp + ["log", "-1", "--format=%at", filePath], + ) + .stdout.toString("utf-8"), + ) * 1000 + ); +} + +// return a Date +export default function (inputPath) { + let timestamp = getGitLastUpdatedTimeStamp(inputPath); + if (timestamp) { + return new Date(timestamp); + } +} diff --git a/node_modules/@11ty/eleventy/src/Util/DirContains.js b/node_modules/@11ty/eleventy/src/Util/DirContains.js new file mode 100644 index 0000000..580d330 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/DirContains.js @@ -0,0 +1,9 @@ +import path from "node:path"; + +// Returns true if subfolder is in parent (accepts absolute or relative paths for both) +export default function (parent, subfolder) { + if (path.resolve(subfolder).startsWith(path.resolve(parent))) { + return true; + } + return false; +} diff --git a/node_modules/@11ty/eleventy/src/Util/EsmResolver.js b/node_modules/@11ty/eleventy/src/Util/EsmResolver.js new file mode 100644 index 0000000..d42b88b --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/EsmResolver.js @@ -0,0 +1,51 @@ +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:EsmResolver"); + +let lastModifiedPaths = new Map(); +export async function initialize({ port }) { + // From `eleventy.importCacheReset` event in Require.js + port.on("message", ({ path, newDate }) => { + lastModifiedPaths.set(path, newDate); + }); +} + +// Fixes issue https://github.com/11ty/eleventy/issues/3270 +// Docs: https://nodejs.org/docs/latest/api/module.html#resolvespecifier-context-nextresolve +export async function resolve(specifier, context, nextResolve) { + try { + // Not a relative import and not a file import + // Or from node_modules (perhaps better to check if the specifier is in the project directory instead) + if ( + (!specifier.startsWith("../") && + !specifier.startsWith("./") && + !specifier.startsWith("file:")) || + context.parentURL.includes("/node_modules/") + ) { + return nextResolve(specifier); + } + + let fileUrl = new URL(specifier, context.parentURL); + if (fileUrl.searchParams.has("_cache_bust")) { + // already is cache busted outside resolver (wider compat, url was changed prior to import, probably in Require.js) + return nextResolve(specifier); + } + + let absolutePath = fileUrl.pathname; + // Bust the import cache if this is a recently modified file + if (lastModifiedPaths.has(absolutePath)) { + fileUrl.search = ""; // delete existing searchparams + fileUrl.searchParams.set("_cache_bust", lastModifiedPaths.get(absolutePath)); + debug("Cache busting %o to %o", specifier, fileUrl.toString()); + + return nextResolve(fileUrl.toString()); + } + } catch (e) { + debug("EsmResolver Error parsing specifier (%o): %o", specifier, e); + } + + return nextResolve(specifier); +} + +// export async function load(url, context, nextLoad) { +// } diff --git a/node_modules/@11ty/eleventy/src/Util/EventBusUtil.js b/node_modules/@11ty/eleventy/src/Util/EventBusUtil.js new file mode 100644 index 0000000..2e54c14 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/EventBusUtil.js @@ -0,0 +1,26 @@ +import eventBus from "../EventBus.js"; +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:EventBus"); + +class EventBusUtil { + // Used for non-global subscriptions that will blow away the previous listener + static soloOn(name, callback) { + eventBus.off(name, callback); + eventBus.on(name, callback); + } + + static resetForConfig() { + this.debug(); + debug("Config reset (removing eleventy.templateModified listeners)."); + eventBus.removeAllListeners("eleventy.templateModified"); + } + + static debug() { + for (let name of eventBus.eventNames()) { + debug("Listeners for %o: %o", name, eventBus.listenerCount(name)); + } + } +} + +export default EventBusUtil; diff --git a/node_modules/@11ty/eleventy/src/Util/ExistsCache.js b/node_modules/@11ty/eleventy/src/Util/ExistsCache.js new file mode 100644 index 0000000..558933f --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/ExistsCache.js @@ -0,0 +1,82 @@ +import fs from "graceful-fs"; +import PathNormalizer from "./PathNormalizer.js"; + +// Checks both files and directories +class ExistsCache { + constructor() { + this._cache = new Map(); + this.lookupCount = 0; + } + + setDirectoryCheck(check) { + this.cacheDirectories = !!check; + } + + get size() { + return this._cache.size; + } + + parentsDoNotExist(path) { + if (!this.cacheDirectories) { + return false; + } + + let allPaths = PathNormalizer.getAllPaths(path).filter((entry) => entry !== path); + for (let parentPath of allPaths) { + if (this._cache.has(parentPath)) { + if (this._cache.get(parentPath) === false) { + return true; // we know this parent doesn’t exist + } + } + } + + // if you’ve made it here: we don’t know if the parents exist or not + return false; + } + + has(path) { + return this._cache.has(path); + } + + exists(path) { + path = PathNormalizer.fullNormalization(path); + + let exists = this._cache.get(path); + if (this.parentsDoNotExist(path)) { + // we don’t need to check if a parent directory does not exist + exists = false; + } else if (!this.has(path)) { + exists = fs.existsSync(path); + this.markExistsWithParentDirectories(path, exists); + this.lookupCount++; + } + + return exists; + } + + // if a file exists, we can mark the parent directories as existing also + // if a file does not exist, we don’t know if the parent directories exist or not (yet) + markExistsWithParentDirectories(path, exists = true) { + path = PathNormalizer.fullNormalization(path); + + if (!this.cacheDirectories || !exists) { + this.markExists(path, false, true); + return; + } + + let paths = PathNormalizer.getAllPaths(path); + for (let fullpath of paths) { + this.markExists(fullpath, true, true); + } + } + + markExists(path, exists = true, alreadyNormalized = false) { + if (!alreadyNormalized) { + path = PathNormalizer.fullNormalization(path); + } + + this._cache.set(path, !!exists); + } +} + +export default ExistsCache; diff --git a/node_modules/@11ty/eleventy/src/Util/FilePathUtil.js b/node_modules/@11ty/eleventy/src/Util/FilePathUtil.js new file mode 100644 index 0000000..1675e8e --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/FilePathUtil.js @@ -0,0 +1,19 @@ +class FilePathUtil { + static isMatchingExtension(filepath, fileExtension) { + if (!fileExtension) { + return false; + } + + if (!(fileExtension || "").startsWith(".")) { + fileExtension = "." + fileExtension; + } + + return filepath.endsWith(fileExtension); + } + + static getFileExtension(filepath) { + return (filepath || "").split(".").pop(); + } +} + +export { FilePathUtil }; diff --git a/node_modules/@11ty/eleventy/src/Util/GetJavaScriptData.js b/node_modules/@11ty/eleventy/src/Util/GetJavaScriptData.js new file mode 100644 index 0000000..7d72a64 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/GetJavaScriptData.js @@ -0,0 +1,30 @@ +import EleventyBaseError from "../Errors/EleventyBaseError.js"; + +class JavaScriptInvalidDataFormatError extends EleventyBaseError {} + +export default async function (inst, inputPath, key = "data", options = {}) { + let { mixins, isObjectRequired } = Object.assign( + { + mixins: {}, + isObjectRequired: true, + }, + options, + ); + + if (inst && key in inst) { + // get extra data from `data` method, + // either as a function or getter or object literal + let result = await (typeof inst[key] === "function" + ? Object.keys(mixins).length > 0 + ? inst[key].call(mixins) + : inst[key]() + : inst[key]); + + if (isObjectRequired && typeof result !== "object") { + throw new JavaScriptInvalidDataFormatError( + `Invalid data format returned from ${inputPath}: typeof ${typeof result}`, + ); + } + return result; + } +} diff --git a/node_modules/@11ty/eleventy/src/Util/GlobMatcher.js b/node_modules/@11ty/eleventy/src/Util/GlobMatcher.js new file mode 100644 index 0000000..8af0879 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/GlobMatcher.js @@ -0,0 +1,21 @@ +import micromatch from "micromatch"; +import { TemplatePath } from "@11ty/eleventy-utils"; + +function isGlobMatch(filepath, globs = [], options = undefined) { + if (!filepath || !Array.isArray(globs) || globs.length === 0) { + return false; + } + + let inputPath = TemplatePath.stripLeadingDotSlash(filepath); + let opts = Object.assign( + { + dot: true, + nocase: true, // insensitive + }, + options, + ); + + return micromatch.isMatch(inputPath, globs, opts); +} + +export { isGlobMatch }; diff --git a/node_modules/@11ty/eleventy/src/Util/HtmlTransformer.js b/node_modules/@11ty/eleventy/src/Util/HtmlTransformer.js new file mode 100644 index 0000000..e755b14 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/HtmlTransformer.js @@ -0,0 +1,158 @@ +import posthtml from "posthtml"; +import urls from "@11ty/posthtml-urls"; +import { FilePathUtil } from "./FilePathUtil.js"; + +class HtmlTransformer { + // feature test for Eleventy Bundle Plugin + static SUPPORTS_PLUGINS_ENABLED_CALLBACK = true; + + constructor() { + // execution order is important (not order of addition/object key order) + this.callbacks = {}; + this.posthtmlProcessOptions = {}; + this.plugins = {}; + } + + get aggregateBench() { + if (!this.userConfig) { + throw new Error("Internal error: Missing `userConfig` in HtmlTransformer."); + } + return this.userConfig.benchmarkManager.get("Aggregate"); + } + + setUserConfig(config) { + this.userConfig = config; + } + + static prioritySort(a, b) { + if (b.priority > a.priority) { + return 1; + } + if (a.priority > b.priority) { + return -1; + } + return 0; + } + + // context is important as it is used in html base plugin for page specific URL + static _getPosthtmlInstance(callbacks = [], plugins = [], context = {}) { + let inst = posthtml(); + + // already sorted by priority when added + for (let { fn: plugin, options } of plugins) { + inst.use(plugin(Object.assign({}, context, options))); + } + + // Run the built-ins last + if (callbacks.length > 0) { + inst.use( + urls({ + eachURL: (url) => { + // and: attrName, tagName + for (let { fn: callback } of callbacks) { + // already sorted by priority when added + url = callback.call(context, url); + } + + return url; + }, + }), + ); + } + + return inst; + } + + _add(extensions, addType, value, options = {}) { + options = Object.assign( + { + priority: 0, + }, + options, + ); + + let extensionsArray = (extensions || "").split(","); + for (let ext of extensionsArray) { + let target = this[addType]; + if (!target[ext]) { + target[ext] = []; + } + + target[ext].push({ + fn: value, // callback or plugin + priority: options.priority, + enabled: options.enabled || (() => true), + options: options.pluginOptions, + }); + + target[ext].sort(HtmlTransformer.prioritySort); + } + } + + addPosthtmlPlugin(extensions, plugin, options = {}) { + this._add(extensions, "plugins", plugin, options); + } + + addUrlTransform(extensions, callback, options = {}) { + this._add(extensions, "callbacks", callback, options); + } + + setPosthtmlProcessOptions(options) { + Object.assign(this.posthtmlProcessOptions, options); + } + + isTransformable(extension, context) { + return ( + this.getCallbacks(extension, context).length > 0 || this.getPlugins(extension).length > 0 + ); + } + + getCallbacks(extension, context) { + let callbacks = this.callbacks[extension] || []; + return callbacks.filter(({ enabled }) => { + if (!enabled || typeof enabled !== "function") { + return true; + } + return enabled(context); + }); + } + + getPlugins(extension) { + let plugins = this.plugins[extension] || []; + return plugins.filter(({ enabled }) => { + if (!enabled || typeof enabled !== "function") { + return true; + } + return enabled(); + }); + } + + static async transformStandalone(content, callback, posthtmlProcessOptions = {}) { + let posthtmlInstance = this._getPosthtmlInstance([ + { + fn: callback, + enabled: () => true, + }, + ]); + let result = await posthtmlInstance.process(content, posthtmlProcessOptions); + return result.html; + } + + async transformContent(outputPath, content, context) { + let extension = FilePathUtil.getFileExtension(outputPath); + if (!this.isTransformable(extension, context)) { + return content; + } + + let bench = this.aggregateBench.get(`Transforming \`${extension}\` with posthtml`); + bench.before(); + let callbacks = this.getCallbacks(extension, context); + let plugins = this.getPlugins(extension); + let posthtmlInstance = HtmlTransformer._getPosthtmlInstance(callbacks, plugins, context); + let result = await posthtmlInstance.process(content, this.posthtmlProcessOptions); + bench.after(); + return result.html; + } +} + +export { HtmlTransformer }; diff --git a/node_modules/@11ty/eleventy/src/Util/ImportJsonSync.js b/node_modules/@11ty/eleventy/src/Util/ImportJsonSync.js new file mode 100644 index 0000000..9cdeb06 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/ImportJsonSync.js @@ -0,0 +1,64 @@ +import fs from "node:fs"; +import { createRequire } from "node:module"; +import debugUtil from "debug"; + +import { TemplatePath } from "@11ty/eleventy-utils"; + +import { normalizeFilePathInEleventyPackage } from "./Require.js"; + +const debug = debugUtil("Eleventy:ImportJsonSync"); +const require = createRequire(import.meta.url); + +function findFilePathInParentDirs(dir, filename) { + // `package.json` searches look in parent dirs: + // https://docs.npmjs.com/cli/v7/configuring-npm/folders#more-information + // Fixes issue #3178, limited to working dir paths only + let workingDir = TemplatePath.getWorkingDir(); + let allDirs = TemplatePath.getAllDirs(dir).filter((entry) => entry.startsWith(workingDir)); + + for (let dir of allDirs) { + let newPath = TemplatePath.join(dir, filename); + if (fs.existsSync(newPath)) { + debug("Found %o searching parent directories at: %o", filename, dir); + return newPath; + } + } +} + +function importJsonSync(filePath) { + if (!filePath.endsWith(".json")) { + throw new Error(`importJsonSync expects a .json file extension (received: ${filePath})`); + } + + try { + // TODO clear require.cache when these files change + return require(filePath); + } catch (e) { + debug("Attempted to import %o, received this error: %o", filePath, e); + // if file does not exist, return nothing + } +} + +function getEleventyPackageJson() { + let filePath = normalizeFilePathInEleventyPackage("package.json"); + return importJsonSync(filePath); +} + +function getModulePackageJson(dir) { + let filePath = findFilePathInParentDirs(TemplatePath.absolutePath(dir), "package.json"); + return importJsonSync(filePath); +} + +function getWorkingProjectPackageJson() { + let dir = TemplatePath.absolutePath(TemplatePath.getWorkingDir()); + let filePath = findFilePathInParentDirs(dir, "package.json"); + return importJsonSync(filePath); +} + +export { + importJsonSync, + findFilePathInParentDirs, + getEleventyPackageJson, + getModulePackageJson, + getWorkingProjectPackageJson, +}; diff --git a/node_modules/@11ty/eleventy/src/Util/IsAsyncFunction.js b/node_modules/@11ty/eleventy/src/Util/IsAsyncFunction.js new file mode 100644 index 0000000..3c4dc65 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/IsAsyncFunction.js @@ -0,0 +1,5 @@ +const ComparisonAsyncFunction = (async () => {}).constructor; + +export default function isAsyncFunction(fn) { + return fn instanceof ComparisonAsyncFunction; +} diff --git a/node_modules/@11ty/eleventy/src/Util/JavaScriptDependencies.js b/node_modules/@11ty/eleventy/src/Util/JavaScriptDependencies.js new file mode 100644 index 0000000..7f6e809 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/JavaScriptDependencies.js @@ -0,0 +1,55 @@ +import dependencyTree from "@11ty/dependency-tree"; +import { find } from "@11ty/dependency-tree-esm"; +import { TemplatePath } from "@11ty/eleventy-utils"; + +import EleventyBaseError from "../Errors/EleventyBaseError.js"; + +class JavaScriptDependencies { + static getErrorMessage(file, type) { + return `A problem was encountered looking for JavaScript dependencies in ${type} file: ${file}. This only affects --watch and --serve behavior and does not affect your build.`; + } + + static async getDependencies(inputFiles, isProjectUsingEsm) { + let depSet = new Set(); + + // TODO does this need to work with aliasing? what other JS extensions will have deps? + let commonJsFiles = inputFiles.filter( + (file) => (!isProjectUsingEsm && file.endsWith(".js")) || file.endsWith(".cjs"), + ); + + for (let file of commonJsFiles) { + try { + let modules = dependencyTree(file, { + nodeModuleNames: "exclude", + allowNotFound: true, + }).map((dependency) => { + return TemplatePath.addLeadingDotSlash(TemplatePath.relativePath(dependency)); + }); + + for (let dep of modules) { + depSet.add(dep); + } + } catch (e) { + throw new EleventyBaseError(this.getErrorMessage(file, "CommonJS"), e); + } + } + + let esmFiles = inputFiles.filter( + (file) => (isProjectUsingEsm && file.endsWith(".js")) || file.endsWith(".mjs"), + ); + for (let file of esmFiles) { + try { + let modules = await find(file); + for (let dep of modules) { + depSet.add(dep); + } + } catch (e) { + throw new EleventyBaseError(this.getErrorMessage(file, "ESM"), e); + } + } + + return Array.from(depSet).sort(); + } +} + +export default JavaScriptDependencies; diff --git a/node_modules/@11ty/eleventy/src/Util/MemoizeFunction.js b/node_modules/@11ty/eleventy/src/Util/MemoizeFunction.js new file mode 100644 index 0000000..f66a155 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/MemoizeFunction.js @@ -0,0 +1,26 @@ +export default function (callback, options = {}) { + let { bench, name } = options; + let cache = new Map(); + + return (...args) => { + // Only supports single-arg functions for now. + if (args.filter(Boolean).length > 1) { + bench?.get(`(count) ${name} Not valid for memoize`).incrementCount(); + return callback(...args); + } + + let [cacheKey] = args; + + if (!cache.has(cacheKey)) { + cache.set(cacheKey, callback(...args)); + + bench?.get(`(count) ${name} memoize miss`).incrementCount(); + + return cache.get(cacheKey); + } + + bench?.get(`(count) ${name} memoize hit`).incrementCount(); + + return cache.get(cacheKey); + }; +} diff --git a/node_modules/@11ty/eleventy/src/Util/Objects/DeepFreeze.js b/node_modules/@11ty/eleventy/src/Util/Objects/DeepFreeze.js new file mode 100644 index 0000000..88e2847 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/Objects/DeepFreeze.js @@ -0,0 +1,20 @@ +import { isPlainObject } from "@11ty/eleventy-utils"; + +// via https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze + +function DeepFreeze(obj, topLevelExceptions) { + for (let name of Reflect.ownKeys(obj)) { + if ((topLevelExceptions || []).find((key) => key === name)) { + continue; + } + + const value = obj[name]; + if (isPlainObject(value)) { + DeepFreeze(value); + } + } + + return Object.freeze(obj); +} + +export { DeepFreeze }; diff --git a/node_modules/@11ty/eleventy/src/Util/Objects/ObjectFilter.js b/node_modules/@11ty/eleventy/src/Util/Objects/ObjectFilter.js new file mode 100644 index 0000000..9ce8737 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/Objects/ObjectFilter.js @@ -0,0 +1,9 @@ +export default function objectFilter(obj, callback) { + let newObject = {}; + for (let [key, value] of Object.entries(obj || {})) { + if (callback(value, key)) { + newObject[key] = value; + } + } + return newObject; +} diff --git a/node_modules/@11ty/eleventy/src/Util/Objects/ProxyWrap.js b/node_modules/@11ty/eleventy/src/Util/Objects/ProxyWrap.js new file mode 100644 index 0000000..3f880db --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/Objects/ProxyWrap.js @@ -0,0 +1,111 @@ +import types from "node:util/types"; +import debugUtil from "debug"; +import { isPlainObject } from "@11ty/eleventy-utils"; + +const debug = debugUtil("Dev:Eleventy:Proxy"); + +function wrapObject(target, fallback) { + if (Object.isFrozen(target)) { + return target; + } + + return new Proxy(target, { + getOwnPropertyDescriptor(target, prop) { + let ret; + + if (Reflect.has(target, prop)) { + ret = Reflect.getOwnPropertyDescriptor(target, prop); + } else if (Reflect.has(fallback, prop)) { + ret = Reflect.getOwnPropertyDescriptor(fallback, prop); + } + + return ret; + }, + has(target, prop) { + if (Reflect.has(target, prop)) { + return true; + } + + return Reflect.has(fallback, prop); + }, + ownKeys(target) { + let s = new Set(); + for (let k of Reflect.ownKeys(target)) { + s.add(k); + } + if (isPlainObject(fallback)) { + for (let k of Reflect.ownKeys(fallback)) { + s.add(k); + } + } + return Array.from(s); + }, + get(target, prop) { + debug("handler:get", prop); + + let value = Reflect.get(target, prop); + + if (Reflect.has(target, prop)) { + // Already proxied + if (types.isProxy(value)) { + return value; + } + + if (isPlainObject(value) && Reflect.has(fallback, prop)) { + if (Object.isFrozen(value)) { + return value; + } + + let ret = wrapObject(value, Reflect.get(fallback, prop)); + debug("handler:get (primary, object)", prop); + return ret; + } + + debug("handler:get (primary)", prop); + return value; + } + + // Does not exist in primary + if (Reflect.has(fallback, prop)) { + // fallback has prop + let fallbackValue = Reflect.get(fallback, prop); + + if (isPlainObject(fallbackValue)) { + if (Object.isFrozen(fallbackValue)) { + return fallbackValue; + } + + debug("handler:get (fallback, object)", prop); + // set empty object on primary + let emptyObject = {}; + Reflect.set(target, prop, emptyObject); + + return wrapObject(emptyObject, fallbackValue); + } + + debug("handler:get (fallback)", prop); + return fallbackValue; + } + + // primary *and* fallback do _not_ have prop + debug("handler:get (not on primary or fallback)", prop); + + return value; + }, + set(target, prop, value) { + debug("handler:set", prop); + + return Reflect.set(target, prop, value); + }, + }); +} + +function ProxyWrap(target, fallback) { + if (!isPlainObject(target) || !isPlainObject(fallback)) { + throw new Error("ProxyWrap expects objects for both the target and fallback"); + } + + return wrapObject(target, fallback); +} + +export { ProxyWrap }; diff --git a/node_modules/@11ty/eleventy/src/Util/Objects/SampleModule.mjs b/node_modules/@11ty/eleventy/src/Util/Objects/SampleModule.mjs new file mode 100644 index 0000000..ff8b4c5 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/Objects/SampleModule.mjs @@ -0,0 +1 @@ +export default {}; diff --git a/node_modules/@11ty/eleventy/src/Util/Objects/Sortable.js b/node_modules/@11ty/eleventy/src/Util/Objects/Sortable.js new file mode 100644 index 0000000..a23d4c9 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/Objects/Sortable.js @@ -0,0 +1,136 @@ +class Sortable { + constructor() { + this.isSortAscending = true; + this.isSortNumeric = false; + this.items = []; + this._dirty = true; + + this.sortFunctionStringMap = { + "A-Z": "sortFunctionAscending", + "Z-A": "sortFunctionDescending", + "0-9": "sortFunctionNumericAscending", + "9-0": "sortFunctionNumericDescending", + }; + } + + get length() { + return this.items.length; + } + + add(item) { + this._dirty = true; + this.items.push(item); + } + + sort(sortFunction) { + if (!sortFunction) { + sortFunction = this.getSortFunction(); + } else if (typeof sortFunction === "string") { + let key = sortFunction; + let name; + if (key in this.sortFunctionStringMap) { + name = this.sortFunctionStringMap[key]; + } + if (Sortable[name]) { + sortFunction = Sortable[name]; + } else { + throw new Error( + `Invalid String argument for sort(). Received \`${key}\`. Valid values: ${Object.keys( + this.sortFunctionStringMap, + )}`, + ); + } + } + + return this.items.slice().sort(sortFunction); + } + + sortAscending() { + return this.sort(this.getSortFunctionAscending()); + } + + sortDescending() { + return this.sort(this.getSortFunctionDescending()); + } + + setSortDescending(isDescending = true) { + this.isSortAscending = !isDescending; + } + + setSortAscending(isAscending = true) { + this.isSortAscending = isAscending; + } + + setSortNumeric(isNumeric) { + this.isSortNumeric = isNumeric; + } + + /* Sort functions */ + static sortFunctionNumericAscending(a, b) { + return a - b; + } + + static sortFunctionNumericDescending(a, b) { + return b - a; + } + + static sortFunctionAscending(a, b) { + if (a > b) { + return 1; + } else if (a < b) { + return -1; + } + return 0; + } + + static sortFunctionDescending(a, b) { + return Sortable.sortFunctionAscending(b, a); + } + + static sortFunctionAlphabeticAscending(a, b) { + return Sortable.sortFunctionAscending(a, b); + } + + static sortFunctionAlphabeticDescending(a, b) { + return Sortable.sortFunctionAscending(b, a); + } + + static sortFunctionDate(mapA, mapB) { + return Sortable.sortFunctionNumericAscending(mapA.date.getTime(), mapB.date.getTime()); + } + + static sortFunctionDateInputPath(mapA, mapB) { + let sortDate = Sortable.sortFunctionNumericAscending(mapA.date.getTime(), mapB.date.getTime()); + if (sortDate === 0) { + return Sortable.sortFunctionAlphabeticAscending(mapA.inputPath, mapB.inputPath); + } + return sortDate; + } + /* End sort functions */ + + getSortFunction() { + if (this.isSortAscending) { + return this.getSortFunctionAscending(); + } else { + return this.getSortFunctionDescending(); + } + } + + getSortFunctionAscending() { + if (this.isSortNumeric) { + return Sortable.sortFunctionNumericAscending; + } else { + return Sortable.sortFunctionAlphabeticAscending; + } + } + + getSortFunctionDescending() { + if (this.isSortNumeric) { + return Sortable.sortFunctionNumericDescending; + } else { + return Sortable.sortFunctionAlphabeticDescending; + } + } +} + +export default Sortable; diff --git a/node_modules/@11ty/eleventy/src/Util/Objects/Unique.js b/node_modules/@11ty/eleventy/src/Util/Objects/Unique.js new file mode 100644 index 0000000..8570c0c --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/Objects/Unique.js @@ -0,0 +1,3 @@ +export default function Unique(arr) { + return Array.from(new Set(arr)); +} diff --git a/node_modules/@11ty/eleventy/src/Util/PassthroughCopyBehaviorCheck.js b/node_modules/@11ty/eleventy/src/Util/PassthroughCopyBehaviorCheck.js new file mode 100644 index 0000000..3dc1abb --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/PassthroughCopyBehaviorCheck.js @@ -0,0 +1,16 @@ +function isUsingEleventyDevServer(config) { + return ( + !config.serverOptions.module || config.serverOptions.module === "@11ty/eleventy-dev-server" + ); +} + +// Config opt-out via serverPassthroughCopyBehavior +// False when other server is used +// False when runMode is "build" or "watch" +export default function (config, runMode) { + return ( + config.serverPassthroughCopyBehavior === "passthrough" && + isUsingEleventyDevServer(config) && + runMode === "serve" + ); +} diff --git a/node_modules/@11ty/eleventy/src/Util/PathNormalizer.js b/node_modules/@11ty/eleventy/src/Util/PathNormalizer.js new file mode 100644 index 0000000..0e46fb9 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/PathNormalizer.js @@ -0,0 +1,60 @@ +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { TemplatePath } from "@11ty/eleventy-utils"; + +class PathNormalizer { + static getParts(inputPath) { + if (!inputPath) { + return []; + } + + let separator = "/"; + if (inputPath.includes(path.sep)) { + separator = path.sep; + } + + return inputPath.split(separator).filter((entry) => entry !== "."); + } + + // order is important here: the top-most directory returns first + // array of file and all parent directories + static getAllPaths(inputPath) { + let parts = this.getParts(inputPath); + let allPaths = []; + + let fullpath = ""; + for (let part of parts) { + fullpath += (fullpath.length > 0 ? "/" : "") + part; + allPaths.push(fullpath); + } + + return allPaths; + } + + static normalizeSeperator(inputPath) { + if (!inputPath) { + return inputPath; + } + return inputPath.split(path.sep).join("/"); + } + + static fullNormalization(inputPath) { + if (typeof inputPath !== "string") { + return inputPath; + } + + // Fix file:///Users/ or file:///C:/ paths passed in + if (inputPath.startsWith("file://")) { + inputPath = fileURLToPath(inputPath); + } + + // Paths should not be absolute (we convert absolute paths to relative) + // Paths should not have a leading dot slash + // Paths should always be `/` independent of OS path separator + return TemplatePath.stripLeadingDotSlash( + this.normalizeSeperator(TemplatePath.relativePath(inputPath)), + ); + } +} + +export default PathNormalizer; diff --git a/node_modules/@11ty/eleventy/src/Util/PathPrefixer.js b/node_modules/@11ty/eleventy/src/Util/PathPrefixer.js new file mode 100644 index 0000000..abd5582 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/PathPrefixer.js @@ -0,0 +1,21 @@ +import path from "node:path"; + +import PathNormalizer from "./PathNormalizer.js"; + +class PathPrefixer { + static normalizePathPrefix(pathPrefix) { + if (pathPrefix) { + // add leading / (for browsersync), see #1454 + // path.join uses \\ for Windows so we split and rejoin + return PathPrefixer.joinUrlParts("/", pathPrefix); + } + + return "/"; + } + + static joinUrlParts(...parts) { + return PathNormalizer.normalizeSeperator(path.join(...parts)); + } +} + +export default PathPrefixer; diff --git a/node_modules/@11ty/eleventy/src/Util/Pluralize.js b/node_modules/@11ty/eleventy/src/Util/Pluralize.js new file mode 100644 index 0000000..d35f1dd --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/Pluralize.js @@ -0,0 +1,3 @@ +export default function (count, singleWord, pluralWord) { + return count === 1 ? singleWord : pluralWord; +} diff --git a/node_modules/@11ty/eleventy/src/Util/ProjectDirectories.js b/node_modules/@11ty/eleventy/src/Util/ProjectDirectories.js new file mode 100644 index 0000000..5c4a999 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/ProjectDirectories.js @@ -0,0 +1,344 @@ +import fs from "node:fs"; +import path from "node:path"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import isGlob from "is-glob"; + +/* Directories internally should always use *nix forward slashes */ +class ProjectDirectories { + static defaults = { + input: "./", + data: "./_data/", // Relative to input directory + includes: "./_includes/", // Relative to input directory + layouts: "./_layouts/", // Relative to input directory + output: "./_site/", + }; + + // no updates allowed, input/output set via CLI + #frozen = false; + + #raw = {}; + + #dirs = {}; + + inputFile = undefined; + inputGlob = undefined; + + // Add leading dot slash + // Use forward slashes + static normalizePath(fileOrDir) { + return TemplatePath.standardizeFilePath(fileOrDir); + } + + // Must be a directory + // Always include a trailing slash + static normalizeDirectory(dir) { + return this.addTrailingSlash(this.normalizePath(dir)); + } + + normalizeDirectoryPathRelativeToInputDirectory(filePath) { + return ProjectDirectories.normalizeDirectory(path.join(this.input, filePath)); + } + + static addTrailingSlash(path) { + if (path.slice(-1) === "/") { + return path; + } + return path + "/"; + } + + // If input/output are set via CLI, they take precedence over all other configuration values. + freeze() { + this.#frozen = true; + } + + setViaConfigObject(configDirs = {}) { + // input must come last + let inputChanged = false; + if ( + configDirs.input && + ProjectDirectories.normalizeDirectory(configDirs.input) !== this.input + ) { + this.#setInputRaw(configDirs.input); + inputChanged = true; + } + + // If falsy or an empty string, the current directory is used. + if (configDirs.output !== undefined) { + if (ProjectDirectories.normalizeDirectory(configDirs.output) !== this.output) { + this.setOutput(configDirs.output); + } + } + + // Input relative directory, if falsy or an empty string, inputDir is used! + // Always set if input changed, e.g. input is `src` and data is `../_data` (resulting in `./_data`) we still want to set data to this new value + if (configDirs.data !== undefined) { + if ( + inputChanged || + this.normalizeDirectoryPathRelativeToInputDirectory(configDirs.data || "") !== this.data + ) { + this.setData(configDirs.data); + } + } + + // Input relative directory, if falsy or an empty string, inputDir is used! + if (configDirs.includes !== undefined) { + if ( + inputChanged || + this.normalizeDirectoryPathRelativeToInputDirectory(configDirs.includes || "") !== + this.includes + ) { + this.setIncludes(configDirs.includes); + } + } + + // Input relative directory, if falsy or an empty string, inputDir is used! + if (configDirs.layouts !== undefined) { + if ( + inputChanged || + this.normalizeDirectoryPathRelativeToInputDirectory(configDirs.layouts || "") !== + this.layouts + ) { + this.setLayouts(configDirs.layouts); + } + } + + if (inputChanged) { + this.updateInputDependencies(); + } + } + + updateInputDependencies() { + // raw first, fall back to Eleventy defaults if not yet set + this.setData(this.#raw.data ?? ProjectDirectories.defaults.data); + this.setIncludes(this.#raw.includes ?? ProjectDirectories.defaults.includes); + + // Should not include this if not explicitly opted-in + if (this.#raw.layouts !== undefined) { + this.setLayouts(this.#raw.layouts ?? ProjectDirectories.defaults.layouts); + } + } + + /* Relative to project root, must exist */ + #setInputRaw(dirOrFile, inputDir = undefined) { + // is frozen and was defined previously + if (this.#frozen && this.#raw.input !== undefined) { + return; + } + + this.#raw.input = dirOrFile; + + if (!dirOrFile) { + // input must exist if inputDir is not set. + return; + } + + // Input has to exist (assumed glob if it does not exist) + let inputExists = fs.existsSync(dirOrFile); + let inputExistsAndIsDirectory = inputExists && fs.statSync(dirOrFile).isDirectory(); + + if (inputExistsAndIsDirectory) { + // is not a file or glob + this.#dirs.input = ProjectDirectories.normalizeDirectory(dirOrFile); + } else { + if (inputExists) { + this.inputFile = ProjectDirectories.normalizePath(dirOrFile); + } else { + if (!isGlob(dirOrFile)) { + throw new Error( + `The "${dirOrFile}" \`input\` parameter (directory or file path) must exist on the file system (unless detected as a glob by the \`is-glob\` package)`, + ); + } + + this.inputGlob = dirOrFile; + } + + // Explicit Eleventy option for inputDir + if (inputDir) { + // Changed in 3.0: must exist + if (!fs.existsSync(inputDir)) { + throw new Error("Directory must exist (via inputDir option to Eleventy constructor)."); + } + + this.#dirs.input = ProjectDirectories.normalizeDirectory(inputDir); + } else { + // the input directory is implied to be the parent directory of the + // file, unless inputDir is explicitly specified (via Eleventy constructor `options`) + this.#dirs.input = ProjectDirectories.normalizeDirectory( + TemplatePath.getDirFromFilePath(dirOrFile), // works with globs + ); + } + } + } + + setInput(dirOrFile, inputDir = undefined) { + this.#setInputRaw(dirOrFile, inputDir); // does not update + this.updateInputDependencies(); + } + + /* Relative to input dir */ + setIncludes(dir) { + if (dir !== undefined) { + // falsy or an empty string is valid (falls back to input dir) + this.#raw.includes = dir; + this.#dirs.includes = ProjectDirectories.normalizeDirectory( + TemplatePath.join(this.input, dir || ""), + ); + } + } + + /* Relative to input dir */ + /* Optional */ + setLayouts(dir) { + if (dir !== undefined) { + // falsy or an empty string is valid (falls back to input dir) + this.#raw.layouts = dir; + this.#dirs.layouts = ProjectDirectories.normalizeDirectory( + TemplatePath.join(this.input, dir || ""), + ); + } + } + + /* Relative to input dir */ + setData(dir) { + if (dir !== undefined) { + // falsy or an empty string is valid (falls back to input dir) + // TODO must exist if specified + this.#raw.data = dir; + this.#dirs.data = ProjectDirectories.normalizeDirectory( + TemplatePath.join(this.input, dir || ""), + ); + } + } + + /* Relative to project root */ + setOutput(dir) { + // is frozen and was defined previously + if (this.#frozen && this.#raw.output !== undefined) { + return; + } + + if (dir !== undefined) { + this.#raw.output = dir; + this.#dirs.output = ProjectDirectories.normalizeDirectory(dir || ""); + } + } + + get input() { + return this.#dirs.input || ProjectDirectories.defaults.input; + } + + get data() { + return this.#dirs.data || ProjectDirectories.defaults.data; + } + + get includes() { + return this.#dirs.includes || ProjectDirectories.defaults.includes; + } + + get layouts() { + // explicit opt-in, no fallback. + return this.#dirs.layouts; + } + + get output() { + return this.#dirs.output || ProjectDirectories.defaults.output; + } + + isTemplateFile(filePath) { + let inputPath = this.getInputPath(filePath); + if (this.layouts && inputPath.startsWith(this.layouts)) { + return false; + } + + if (inputPath.startsWith(this.includes)) { + return false; + } + + return inputPath.startsWith(this.input); + } + + // for a hypothetical template file + getInputPath(filePathRelativeToInputDir) { + // TODO change ~/ to project root dir + return TemplatePath.addLeadingDotSlash( + TemplatePath.join(this.input, TemplatePath.standardizeFilePath(filePathRelativeToInputDir)), + ); + } + + // Inverse of getInputPath + // Removes input dir from path + getInputPathRelativeToInputDirectory(filePathRelativeToInputDir) { + let inputDir = TemplatePath.addLeadingDotSlash(TemplatePath.join(this.input)); + + // No leading dot slash + return TemplatePath.stripLeadingSubPath(filePathRelativeToInputDir, inputDir); + } + + // for a hypothetical Eleventy layout file + getLayoutPath(filePathRelativeToLayoutDir) { + return TemplatePath.addLeadingDotSlash( + TemplatePath.join( + this.layouts || this.includes, + TemplatePath.standardizeFilePath(filePathRelativeToLayoutDir), + ), + ); + } + + // Removes layout dir from path + getLayoutPathRelativeToInputDirectory(filePathRelativeToLayoutDir) { + let layoutPath = this.getLayoutPath(filePathRelativeToLayoutDir); + let inputDir = TemplatePath.addLeadingDotSlash(TemplatePath.join(this.input)); + + // No leading dot slash + return TemplatePath.stripLeadingSubPath(layoutPath, inputDir); + } + + getProjectPath(filePath) { + return TemplatePath.addLeadingDotSlash( + TemplatePath.join(".", TemplatePath.standardizeFilePath(filePath)), + ); + } + + // Access the data without being able to set the data. + getUserspaceInstance() { + let d = this; + + return { + get input() { + return d.input; + }, + get inputFile() { + return d.inputFile; + }, + get inputGlob() { + return d.inputGlob; + }, + get data() { + return d.data; + }, + get includes() { + return d.includes; + }, + get layouts() { + return d.layouts; + }, + get output() { + return d.output; + }, + }; + } + + toString() { + return { + input: this.input, + inputFile: this.inputFile, + inputGlob: this.inputGlob, + data: this.data, + includes: this.includes, + layouts: this.layouts, + output: this.output, + }; + } +} + +export default ProjectDirectories; diff --git a/node_modules/@11ty/eleventy/src/Util/ProjectTemplateFormats.js b/node_modules/@11ty/eleventy/src/Util/ProjectTemplateFormats.js new file mode 100644 index 0000000..f37040e --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/ProjectTemplateFormats.js @@ -0,0 +1,134 @@ +import debugUtil from "debug"; +const debug = debugUtil("Eleventy:Util:ProjectTemplateFormats"); + +class ProjectTemplateFormats { + #useAll = {}; + #raw = {}; + + #values = {}; // Set objects + + static union(...sets) { + let s = new Set(); + + for (let set of sets) { + if (!set || typeof set[Symbol.iterator] !== "function") { + continue; + } + for (let v of set) { + s.add(v); + } + } + + return s; + } + + #normalize(formats) { + if (Array.isArray(formats)) { + formats = "" + formats.join(","); + } + + if (typeof formats !== "string") { + throw new Error( + `Invalid formats (expect String, Array) passed to ProjectTemplateFormats->normalize: ${formats}`, + ); + } + + let final = new Set(); + for (let format of formats.split(",")) { + format = format.trim(); + if (format && format !== "*") { + final.add(format); + } + } + + return final; + } + + isWildcard() { + return this.#useAll.cli || this.#useAll.config || false; + } + + /** @returns {boolean} */ + #isUseAll(rawFormats) { + if (rawFormats === "") { + return false; + } + + if (typeof rawFormats === "string") { + rawFormats = rawFormats.split(","); + } + + if (Array.isArray(rawFormats)) { + return rawFormats.find((entry) => entry === "*") !== undefined; + } + + return false; + } + + // 3.x Breaking: "" now means no formats. In 2.x and prior it meant "*" + setViaCommandLine(formats) { + if (formats === undefined) { + return; + } + + this.#useAll.cli = this.#isUseAll(formats); + this.#raw.cli = formats; + this.#values.cli = this.#normalize(formats); + } + + // 3.x Breaking: "" now means no formats—in 2.x and prior it meant "*" + // 3.x Adds support for comma separated string—in 2.x this required an Array + setViaConfig(formats) { + if (formats === undefined) { + return; + } + + // "*" is supported + this.#useAll.config = this.#isUseAll(formats); + this.#raw.config = formats; + this.#values.config = this.#normalize(formats); + } + + addViaConfig(formats) { + if (!formats) { + return; + } + + if (this.#isUseAll(formats)) { + throw new Error( + `\`addTemplateFormats("*")\` is not supported for project template syntaxes.`, + ); + } + + // "*" not supported here + this.#raw.configAdd = formats; + this.#values.configAdd = this.#normalize(formats); + } + + getAllTemplateFormats() { + return Array.from(ProjectTemplateFormats.union(this.#values.config, this.#values.configAdd)); + } + + getTemplateFormats() { + if (this.#useAll.cli) { + let v = this.getAllTemplateFormats(); + debug("Using CLI --formats='*': %o", v); + return v; + } + + if (this.#raw.cli !== undefined) { + let v = Array.from(this.#values.cli); + debug("Using CLI --formats: %o", v); + return v; + } + + let v = this.getAllTemplateFormats(); + debug( + "Using configuration `templateFormats`, `setTemplateFormats()`, `addTemplateFormats()`: %o", + v, + ); + return v; + } +} + +export default ProjectTemplateFormats; diff --git a/node_modules/@11ty/eleventy/src/Util/Require.js b/node_modules/@11ty/eleventy/src/Util/Require.js new file mode 100644 index 0000000..6fd20d4 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/Require.js @@ -0,0 +1,206 @@ +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import module from "node:module"; +import { MessageChannel } from "node:worker_threads"; + +import { TemplatePath } from "@11ty/eleventy-utils"; + +import eventBus from "../EventBus.js"; + +const { port1, port2 } = new MessageChannel(); + +// ESM Cache Buster is an enhancement that works in Node 18.19+ +// https://nodejs.org/docs/latest/api/module.html#moduleregisterspecifier-parenturl-options +// Fixes https://github.com/11ty/eleventy/issues/3270 +// ENV variable for https://github.com/11ty/eleventy/issues/3371 +if ("register" in module && !process?.env?.ELEVENTY_SKIP_ESM_RESOLVER) { + module.register("./EsmResolver.js", import.meta.url, { + parentURL: import.meta.url, + data: { + port: port2, + }, + transferList: [port2], + }); +} + +// important to clear the require.cache in CJS projects +const require = module.createRequire(import.meta.url); + +const requestPromiseCache = new Map(); + +// Used for JSON imports, suffering from Node warning that import assertions experimental but also +// throwing an error if you try to import() a JSON file without an import assertion. +/** + * + * @returns {string|undefined} + */ +function loadContents(path, options = {}) { + let rawInput; + /** @type {string} */ + let encoding = "utf8"; // JSON is utf8 + if (options?.encoding || options?.encoding === null) { + encoding = options.encoding; + } + + try { + // @ts-expect-error This is an error in the upstream types + rawInput = fs.readFileSync(path, encoding); + } catch (e) { + // if file does not exist, return nothing + } + + // Can return a buffer, string, etc + if (typeof rawInput === "string") { + rawInput = rawInput.trim(); + } + + return rawInput; +} + +let lastModifiedPaths = new Map(); +eventBus.on("eleventy.importCacheReset", (fileQueue) => { + for (let filePath of fileQueue) { + let absolutePath = TemplatePath.absolutePath(filePath); + let newDate = Date.now(); + lastModifiedPaths.set(absolutePath, newDate); + + // post to EsmResolver worker thread + if (port1) { + port1.postMessage({ path: absolutePath, newDate }); + } + + // ESM Eleventy when using `import()` on a CJS project file still adds to require.cache + if (absolutePath in (require?.cache || {})) { + delete require.cache[absolutePath]; + } + } +}); + +async function dynamicImportAbsolutePath(absolutePath, type, returnRaw = false) { + if (absolutePath.endsWith(".json") || type === "json") { + // https://v8.dev/features/import-assertions#dynamic-import() is still experimental in Node 20 + let rawInput = loadContents(absolutePath); + if (!rawInput) { + return; + } + return JSON.parse(rawInput); + } + + let urlPath; + try { + let u = new URL(`file:${absolutePath}`); + + // Bust the import cache if this is the last modified file + if (lastModifiedPaths.has(absolutePath)) { + u.searchParams.set("_cache_bust", lastModifiedPaths.get(absolutePath)); + } + + urlPath = u.toString(); + } catch (e) { + urlPath = absolutePath; + } + + let promise; + if (requestPromiseCache.has(urlPath)) { + promise = requestPromiseCache.get(urlPath); + } else { + promise = import(urlPath); + requestPromiseCache.set(urlPath, promise); + } + + if (returnRaw) { + return promise; + } + + return promise.then((target) => { + // If the only export is `default`, elevate to top (for ESM and CJS) + if (Object.keys(target).length === 1 && "default" in target) { + return target.default; + } + + // When using import() on a CommonJS file that exports an object sometimes it + // returns duplicated values in `default` key, e.g. `{ default: {key: value}, key: value }` + + // A few examples: + // module.exports = { key: false }; + // returns `{ default: {key: false}, key: false }` as not expected. + // module.exports = { key: true }; + // module.exports = { key: null }; + // module.exports = { key: undefined }; + // module.exports = { key: class {} }; + + // A few examples where it does not duplicate: + // module.exports = { key: 1 }; + // returns `{ default: {key: 1} }` as expected. + // module.exports = { key: "value" }; + // module.exports = { key: {} }; + // module.exports = { key: [] }; + + if (type === "cjs" && "default" in target) { + let match = true; + for (let key in target) { + if (key === "default") { + continue; + } + if (target[key] !== target.default[key]) { + match = false; + } + } + + if (match) { + return target.default; + } + } + + // Otherwise return { default: value, named: value } + // Object.assign here so we can add things to it in JavaScript.js + return Object.assign({}, target); + }); +} + +function normalizeFilePathInEleventyPackage(file) { + // Back up relative paths from ./src/Util/Require.js + return path.resolve(fileURLToPath(import.meta.url), "../../../", file); +} + +async function dynamicImportFromEleventyPackage(file) { + // points to files relative to the top level Eleventy directory + let filePath = normalizeFilePathInEleventyPackage(file); + + // Returns promise + return dynamicImportAbsolutePath(filePath, "esm"); +} + +async function dynamicImport(localPath, type) { + let absolutePath = TemplatePath.absolutePath(localPath); + + // Returns promise + return dynamicImportAbsolutePath(absolutePath, type); +} + +/* Used to import default Eleventy configuration file, raw means we don’t normalize away the `default` export */ +async function dynamicImportRawFromEleventyPackage(file) { + // points to files relative to the top level Eleventy directory + let filePath = normalizeFilePathInEleventyPackage(file); + + // Returns promise + return dynamicImportAbsolutePath(filePath, "esm", true); +} + +/* Used to import project configuration files, raw means we don’t normalize away the `default` export */ +async function dynamicImportRaw(localPath, type) { + let absolutePath = TemplatePath.absolutePath(localPath); + + // Returns promise + return dynamicImportAbsolutePath(absolutePath, type, true); +} + +export { + loadContents as EleventyLoadContent, + dynamicImport as EleventyImport, + dynamicImportRaw as EleventyImportRaw, + dynamicImportFromEleventyPackage as EleventyImportFromEleventy, + dynamicImportRawFromEleventyPackage as EleventyImportRawFromEleventy, + normalizeFilePathInEleventyPackage, +}; diff --git a/node_modules/@11ty/eleventy/src/Util/ReservedData.js b/node_modules/@11ty/eleventy/src/Util/ReservedData.js new file mode 100644 index 0000000..d726c73 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/ReservedData.js @@ -0,0 +1,69 @@ +class EleventyReservedDataError extends TypeError {} + +class ReservedData { + static properties = [ + // "pkg", // Object.freeze’d upstream + // "eleventy", // Object.freeze’d upstream + // "page" is only frozen for specific subproperties below + "content", + "collections", + ]; + + static pageProperties = [ + "date", + "inputPath", + "fileSlug", + "filePathStem", + "outputFileExtension", + "templateSyntax", + "url", + "outputPath", + // not yet `excerpt` or `lang` set via front matter and computed data + ]; + + // Check in the data cascade for reserved data properties. + static getReservedKeys(data) { + if (!data) { + return []; + } + + let keys = this.properties.filter((key) => { + return key in data; + }); + + if ("page" in data) { + if (typeof data.page === "object") { + for (let key of this.pageProperties) { + if (key in data.page) { + keys.push(`page.${key}`); + } + } + } else { + // fail `page` when set to non-object values. + keys.push("page"); + } + } + return keys; + } + + static check(data) { + let reserved = ReservedData.getReservedKeys(data); + if (reserved.length === 0) { + return; + } + + let error = new EleventyReservedDataError( + `Cannot override reserved Eleventy properties: ${reserved.join(", ")}`, + ); + + error.reservedNames = reserved; + + throw error; + } + + static isReservedDataError(e) { + return e instanceof EleventyReservedDataError; + } +} + +export default ReservedData; diff --git a/node_modules/@11ty/eleventy/src/Util/SetUnion.js b/node_modules/@11ty/eleventy/src/Util/SetUnion.js new file mode 100644 index 0000000..50e6b9c --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/SetUnion.js @@ -0,0 +1,11 @@ +function setUnion(...sets) { + let root = new Set(); + for (let set of sets) { + for (let entry of set) { + root.add(entry); + } + } + return root; +} + +export { setUnion }; diff --git a/node_modules/@11ty/eleventy/src/Util/TransformsUtil.js b/node_modules/@11ty/eleventy/src/Util/TransformsUtil.js new file mode 100644 index 0000000..3ba8ab0 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/TransformsUtil.js @@ -0,0 +1,70 @@ +import EleventyBaseError from "../Errors/EleventyBaseError.js"; +import { isPlainObject } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:Transforms"); + +class EleventyTransformError extends EleventyBaseError {} + +class TransformsUtil { + static changeTransformsToArray(transformsObj) { + let transforms = []; + for (let name in transformsObj) { + transforms.push({ + name: name, + callback: transformsObj[name], + }); + } + return transforms; + } + + static async runAll(content, pageData, transforms = {}, options = {}) { + let { baseHrefOverride, logger } = options; + let { inputPath, outputPath, url } = pageData; + + if (!isPlainObject(transforms)) { + throw new Error("Object of transforms expected."); + } + + let transformsArray = this.changeTransformsToArray(transforms); + + for (let { callback, name } of transformsArray) { + debug("Running %o transform on %o: %o", name, inputPath, outputPath); + + try { + let hadContentBefore = !!content; + + content = await callback.call( + { + inputPath, + outputPath, + url, + page: pageData, + baseHref: baseHrefOverride, + }, + content, + outputPath, + ); + + if (hadContentBefore && !content) { + if (!logger || !logger.warn) { + throw new Error("Internal error: missing `logger` instance."); + } + + logger.warn( + `Warning: Transform \`${name}\` returned empty when writing ${outputPath} from ${inputPath}.`, + ); + } + } catch (e) { + throw new EleventyTransformError( + `Transform \`${name}\` encountered an error when transforming ${inputPath}.`, + e, + ); + } + } + + return content; + } +} + +export default TransformsUtil; diff --git a/node_modules/@11ty/eleventy/src/Util/ValidUrl.js b/node_modules/@11ty/eleventy/src/Util/ValidUrl.js new file mode 100644 index 0000000..9d0f59b --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/ValidUrl.js @@ -0,0 +1,9 @@ +export default function isValidUrl(url) { + try { + new URL(url); + return true; + } catch (e) { + // invalid url OR local path + return false; + } +} diff --git a/node_modules/@11ty/eleventy/src/defaultConfig.js b/node_modules/@11ty/eleventy/src/defaultConfig.js new file mode 100644 index 0000000..8cd985f --- /dev/null +++ b/node_modules/@11ty/eleventy/src/defaultConfig.js @@ -0,0 +1,168 @@ +import bundlePlugin from "@11ty/eleventy-plugin-bundle"; + +import urlFilter from "./Filters/Url.js"; +import slugFilter from "./Filters/Slug.js"; +import slugifyFilter from "./Filters/Slugify.js"; +import getLocaleCollectionItem from "./Filters/GetLocaleCollectionItem.js"; +import getCollectionItemIndex from "./Filters/GetCollectionItemIndex.js"; +import { FilterPlugin as InputPathToUrlFilterPlugin } from "./Plugins/InputPathToUrl.js"; +import { HtmlTransformer } from "./Util/HtmlTransformer.js"; +import TransformsUtil from "./Util/TransformsUtil.js"; +import MemoizeUtil from "./Util/MemoizeFunction.js"; + +/** + * @module 11ty/eleventy/defaultConfig + */ + +/** + * @callback addFilter - Register a global filter. + * @param {string} name - Register a template filter by this name. + * @param {function} callback - The filter logic. + */ + +/** + * @typedef {object} config + * @property {addFilter} addFilter - Register a new global filter. + */ + +/** + * @typedef {object} defaultConfig + * @property {Array} templateFormats - An array of accepted template formats. + * @property {string} [pathPrefix='/'] - The directory under which all output files should be written to. + * @property {string} [markdownTemplateEngine='liquid'] - Template engine to process markdown files with. + * @property {string} [htmlTemplateEngine='liquid'] - Template engine to process html files with. + * @property {boolean} [dataTemplateEngine=false] - Changed in v1.0 + * @property {string} [jsDataFileSuffix='.11tydata'] - File suffix for jsData files. + * @property {object} keys + * @property {string} [keys.package='pkg'] - Global data property for package.json data + * @property {string} [keys.layout='layout'] + * @property {string} [keys.permalink='permalink'] + * @property {string} [keys.permalinkRoot='permalinkBypassOutputDir'] + * @property {string} [keys.engineOverride='templateEngineOverride'] + * @property {string} [keys.computed='eleventyComputed'] + * @property {object} dir + * @property {string} [dir.input='.'] + * @property {string} [dir.includes='_includes'] + * @property {string} [dir.data='_data'] + * @property {string} [dir.output='_site'] + * @deprecated handlebarsHelpers + * @deprecated nunjucksFilters + */ + +/** + * Default configuration object factory. + * + * @param {config} config - Eleventy configuration object. + * @returns {defaultConfig} + */ +export default function (config) { + let templateConfig = this; + + // Used for the HTML , InputPathToUrl, Image transform plugins + let ut = new HtmlTransformer(); + ut.setUserConfig(config); + + // This needs to be assigned before bundlePlugin is added below. + config.htmlTransformer = ut; + + config.addPlugin(bundlePlugin, { + bundles: false, // no default bundles included—must be opt-in. + immediate: true, + }); + + // Filter: Maps an input path to output URL + config.addPlugin(InputPathToUrlFilterPlugin, { + immediate: true, + }); + + let memoizeBench = config.benchmarkManager.get("Configuration"); + config.addFilter("slug", MemoizeUtil(slugFilter, { name: "slug", bench: memoizeBench })); + config.addFilter("slugify", MemoizeUtil(slugifyFilter, { name: "slugify", bench: memoizeBench })); + + // Deprecated, use HtmlBasePlugin instead. + // Adds a pathPrefix manually to a URL string + config.addFilter("url", function addPathPrefixFilter(url, pathPrefixOverride) { + let pathPrefix; + if (pathPrefixOverride && typeof pathPrefixOverride === "string") { + pathPrefix = pathPrefixOverride; + } else { + pathPrefix = templateConfig.getPathPrefix(); + } + + return urlFilter.call(this, url, pathPrefix); + }); + + config.addFilter("log", (input, ...messages) => { + console.log(input, ...messages); + return input; + }); + + config.addFilter("getCollectionItemIndex", function (collection, pageOverride) { + return getCollectionItemIndex.call(this, collection, pageOverride); + }); + config.addFilter("getCollectionItem", function (collection, pageOverride, langCode) { + return getLocaleCollectionItem.call(this, config, collection, pageOverride, langCode, 0); + }); + config.addFilter("getPreviousCollectionItem", function (collection, pageOverride, langCode) { + return getLocaleCollectionItem.call(this, config, collection, pageOverride, langCode, -1); + }); + config.addFilter("getNextCollectionItem", function (collection, pageOverride, langCode) { + return getLocaleCollectionItem.call(this, config, collection, pageOverride, langCode, 1); + }); + + // Process arbitrary content with transforms + config.addFilter( + "renderTransforms", + async function transformsFilter(content, pageEntryOverride, baseHrefOverride) { + return TransformsUtil.runAll(content, pageEntryOverride || this.page, config.transforms, { + baseHrefOverride, + logger: config.logger, + }); + }, + ); + + // Run the `htmlTransformer` transform + config.addTransform("@11ty/eleventy/html-transformer", async function (content) { + return ut.transformContent(this.outputPath, content, this); + }); + + return { + templateFormats: ["liquid", "md", "njk", "html", "11ty.js"], + // if your site deploys to a subdirectory, change this + pathPrefix: "/", + markdownTemplateEngine: "liquid", + htmlTemplateEngine: "liquid", + + // Renamed from `jsDataFileSuffix` in 2.0 (and swapped to an Array) + // If you remove "" we won’t look for dir/dir.json or file.json + dataFileSuffixes: [".11tydata", ""], + + // "index" will look for `directory/index.*` directory data files instead of `directory/directory.*` + dataFileDirBaseNameOverride: false, + + keys: { + // TODO breaking: use `false` by default + package: "pkg", // supports `false` + layout: "layout", + permalink: "permalink", + permalinkRoot: "permalinkBypassOutputDir", + engineOverride: "templateEngineOverride", + computed: "eleventyComputed", + dataSchema: "eleventyDataSchema", + }, + + // Deprecated, define using `export const directories = {}` instead. + // Reference values using `eleventyConfig.directories` instead. + dir: { + // These values here aren’t used internally either (except by a few tests), instead we’re using `ProjectDirectories.defaults`. + // These are kept in place for backwards compat with `eleventyConfig.dir` references in project config code and plugins. + input: ".", + includes: "_includes", + data: "_data", + output: "_site", + }, + + // deprecated, use config.addNunjucksFilter + nunjucksFilters: {}, + }; +} diff --git a/node_modules/@11ty/eleventy/tsconfig.json b/node_modules/@11ty/eleventy/tsconfig.json new file mode 100644 index 0000000..a01ba08 --- /dev/null +++ b/node_modules/@11ty/eleventy/tsconfig.json @@ -0,0 +1,117 @@ +{ + "include": [ + // "src/Eleventy.js", + "src/UserConfig.js", + "src/Util/ConsoleLogger.js", + ], + "exclude": [], + + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "ES2021", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + "lib": ["ES2021"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "Node16", /* Specify what module code is generated. */ + // "rootDir": "./src/", /* Specify the root folder within your source files. */ + "moduleResolution": "Node16", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + "types": ["node"], /* Specify type package names to be included without being referenced in a source file. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ + // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ + // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ + // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + + // WARNING: this causes missing `node` types even with "types": ["node"] + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 0, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + // "outDir": "./types/", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./types/", /* Specify the output directory for generated declaration files. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ + // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + // "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + "noImplicitAny": false, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + // "skipLibCheck": true /* Skip type checking all .d.ts files. */ + } +} diff --git a/node_modules/@11ty/lodash-custom/README.md b/node_modules/@11ty/lodash-custom/README.md new file mode 100644 index 0000000..e45d1a9 --- /dev/null +++ b/node_modules/@11ty/lodash-custom/README.md @@ -0,0 +1,14 @@ +# @11ty/lodash-custom + +Eleventy uses 3 small `lodash` functions: + +* [`get`](https://lodash.com/docs/4#get) +* [`set`](https://lodash.com/docs/4#set) +* [`chunk`](https://lodash.com/docs/4#chunk) + +## Why? + +1. The top level `lodash` package includes all of `lodash` and is a hefty 5 MB. +1. Using the individual, modularized `lodash.get`, `lodash.set`, `lodash.chunk` packages are a much smaller 106 KB but do contain duplicated code. More problematically, these are not being maintained/updated with the newest versions of `lodash`. + +This package creates one focused custom dependency using the tools that `lodash` provides to do custom builds ([`lodash-cli`](https://lodash.com/custom-builds)) for these three `lodash` functions with updated versions of `lodash`. \ No newline at end of file diff --git a/node_modules/@11ty/lodash-custom/lodash.custom.js b/node_modules/@11ty/lodash-custom/lodash.custom.js new file mode 100644 index 0000000..037cfef --- /dev/null +++ b/node_modules/@11ty/lodash-custom/lodash.custom.js @@ -0,0 +1,1704 @@ +/** + * @license + * Lodash (Custom Build) + * Build: `lodash exports="node" include="get,set,chunk"` + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +;(function() { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** Used as the semantic version number. */ + var VERSION = '4.17.21'; + + /** Error message constants. */ + var FUNC_ERROR_TEXT = 'Expected a function'; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; + + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + + /** `Object#toString` result references. */ + var asyncTag = '[object AsyncFunction]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + nullTag = '[object Null]', + proxyTag = '[object Proxy]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]'; + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + + /** Used to match leading whitespace. */ + var reTrimStart = /^\s+/; + + /** Used to match a single whitespace character. */ + var reWhitespace = /\s/; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** Built-in method references without a dependency on `root`. */ + var freeParseInt = parseInt; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + /** Detect free variable `exports`. */ + var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + + /*--------------------------------------------------------------------------*/ + + /** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + + /** + * The base implementation of `_.trim`. + * + * @private + * @param {string} string The string to trim. + * @returns {string} Returns the trimmed string. + */ + function baseTrim(string) { + return string + ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') + : string; + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace + * character of `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the index of the last non-whitespace character. + */ + function trimmedEndIndex(string) { + var index = string.length; + + while (index-- && reWhitespace.test(string.charAt(index))) {} + return index; + } + + /*--------------------------------------------------------------------------*/ + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + + /** Used to detect overreaching core-js shims. */ + var coreJsData = root['__core-js_shared__']; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var nativeObjectToString = objectProto.toString; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** Built-in value references. */ + var Symbol = root.Symbol, + splice = arrayProto.splice, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; + + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeCeil = Math.ceil, + nativeMax = Math.max; + + /* Built-in method references that are verified to be native. */ + var Map = getNative(root, 'Map'), + nativeCreate = getNative(Object, 'create'); + + /** Used to lookup unminified function names. */ + var realNames = {}; + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. + * + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array and iteratees accept only + * one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash() { + // No operation performed. + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; + } + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); + } + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } + } + + /** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; + } + + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); + } + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + /** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (key === '__proto__' || key === 'constructor' || key === 'prototype') { + return object; + } + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; + } + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + + /** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ + function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + /** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; + } + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + /** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; + } + + /** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString.call(value); + } + + /** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of elements split into groups the length of `size`. + * If `array` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the new array of chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ + function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; + } else { + size = nativeMax(toInteger(size), 0); + } + var length = array == null ? 0 : array.length; + if (!length || size < 1) { + return []; + } + var index = 0, + resIndex = 0, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); + } + return result; + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; + } + + // Expose `MapCache`. + memoize.Cache = MapCache; + + /*------------------------------------------------------------------------*/ + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + /** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); + } + + /** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; + } + + /** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ + function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; + } + + /** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ + function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = baseTrim(value); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); + } + + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString(value) { + return value == null ? '' : baseToString(value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; + } + + /** + * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, + * it's created. Arrays are created for missing index properties while objects + * are created for all other missing properties. Use `_.setWith` to customize + * `path` creation. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 + * + * _.set(object, ['x', '0', 'y', 'z'], 5); + * console.log(object.x[0].y.z); + * // => 5 + */ + function set(object, path, value) { + return object == null ? object : baseSet(object, path, value); + } + + /*------------------------------------------------------------------------*/ + + // Add methods that return wrapped values in chain sequences. + lodash.chunk = chunk; + lodash.memoize = memoize; + lodash.set = set; + + /*------------------------------------------------------------------------*/ + + // Add methods that return unwrapped values in chain sequences. + lodash.eq = eq; + lodash.get = get; + lodash.isArray = isArray; + lodash.isArrayLike = isArrayLike; + lodash.isFunction = isFunction; + lodash.isLength = isLength; + lodash.isObject = isObject; + lodash.isObjectLike = isObjectLike; + lodash.isSymbol = isSymbol; + lodash.toFinite = toFinite; + lodash.toInteger = toInteger; + lodash.toNumber = toNumber; + lodash.toString = toString; + + /*------------------------------------------------------------------------*/ + + /** + * The semantic version number. + * + * @static + * @memberOf _ + * @type {string} + */ + lodash.VERSION = VERSION; + + /*--------------------------------------------------------------------------*/ + + if (freeModule) { + // Export for Node.js. + (freeModule.exports = lodash)._ = lodash; + // Export for CommonJS support. + freeExports._ = lodash; + } +}.call(this)); diff --git a/node_modules/@11ty/lodash-custom/package.json b/node_modules/@11ty/lodash-custom/package.json new file mode 100644 index 0000000..99d2eed --- /dev/null +++ b/node_modules/@11ty/lodash-custom/package.json @@ -0,0 +1,38 @@ +{ + "name": "@11ty/lodash-custom", + "version": "4.17.21", + "description": "A custom, focused build of lodash exclusively for use internally in Eleventy.", + "main": "lodash.custom.js", + "scripts": { + "build": "npx lodash exports=node include=get,set,chunk && rm lodash.custom.min.js" + }, + "publishConfig": { + "access": "public" + }, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + }, + "author": { + "name": "Zach Leatherman", + "email": "zachleatherman@gmail.com", + "url": "https://zachleat.com/" + }, + "repository": { + "type": "git", + "url": "git://github.com/11ty/lodash-custom.git" + }, + "bugs": "https://github.com/11ty/lodash-custom/issues", + "homepage": "https://github.com/11ty/lodash-custom/", + "devDependencies": { + "ava": "^5.2.0", + "lodash-cli": "^4.17.5" + }, + "overrides": { + "lodash": "4.17.21" + } +} diff --git a/node_modules/@11ty/posthtml-urls/LICENSE b/node_modules/@11ty/posthtml-urls/LICENSE new file mode 100644 index 0000000..16736bd --- /dev/null +++ b/node_modules/@11ty/posthtml-urls/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Steven Vachon + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@11ty/posthtml-urls/README.md b/node_modules/@11ty/posthtml-urls/README.md new file mode 100644 index 0000000..a0f1344 --- /dev/null +++ b/node_modules/@11ty/posthtml-urls/README.md @@ -0,0 +1,48 @@ +# `@11ty/posthtml-urls` + +PostHTML plugin for transforming URLs. This is a fork of [`posthtml/posthtml-urls`](https://github.com/posthtml/posthtml-urls). + + +## Installation + +[Node.js](http://nodejs.org) `>= 6` is required. To install, type this at the command line: + +```shell +npm install @11ty/posthtml-urls +``` + + +## Usage + +```js +const posthtml = require('posthtml'); +const urls = require('posthtml-urls'); + +const options = { + eachURL: (url, attr, element) => `http://domain.com/${url}` +}; + +posthtml() + .use( urls(options) ) + .process('link') + .then(result => console.log(result.html)); +//-> link +``` + + +## Options + +### `eachURL` +Type: `Function` +Default value: `undefined` +A callback function ran for each URL value found. You can return either a synchronous value or a `Promise`. + +### `filter` +Type: `Object` +Default value: [`{…}`](https://github.com/posthtml/posthtml-urls/blob/master/lib/defaultOptions.js) +The elements and attributes for which to search. An attribute value can optionally be a function, for deeper filtering. + + +## FAQ +1. **How can I filter `' + * ) + * document.type //=> 'document' + * document.nodes.length //=> 2 + * ``` + */ +declare class Document_ extends Container { + nodes: Root[] + parent: undefined + type: 'document' + + constructor(defaults?: Document.DocumentProps) + + assign(overrides: Document.DocumentProps | object): this + clone(overrides?: Partial): this + cloneAfter(overrides?: Partial): this + cloneBefore(overrides?: Partial): this + + /** + * Returns a `Result` instance representing the document’s CSS roots. + * + * ```js + * const root1 = postcss.parse(css1, { from: 'a.css' }) + * const root2 = postcss.parse(css2, { from: 'b.css' }) + * const document = postcss.document() + * document.append(root1) + * document.append(root2) + * const result = document.toResult({ to: 'all.css', map: true }) + * ``` + * + * @param opts Options. + * @return Result with current document’s CSS. + */ + toResult(options?: ProcessOptions): Result +} + +declare class Document extends Document_ {} + +export = Document diff --git a/node_modules/postcss/lib/document.js b/node_modules/postcss/lib/document.js new file mode 100644 index 0000000..4468991 --- /dev/null +++ b/node_modules/postcss/lib/document.js @@ -0,0 +1,33 @@ +'use strict' + +let Container = require('./container') + +let LazyResult, Processor + +class Document extends Container { + constructor(defaults) { + // type needs to be passed to super, otherwise child roots won't be normalized correctly + super({ type: 'document', ...defaults }) + + if (!this.nodes) { + this.nodes = [] + } + } + + toResult(opts = {}) { + let lazy = new LazyResult(new Processor(), this, opts) + + return lazy.stringify() + } +} + +Document.registerLazyResult = dependant => { + LazyResult = dependant +} + +Document.registerProcessor = dependant => { + Processor = dependant +} + +module.exports = Document +Document.default = Document diff --git a/node_modules/postcss/lib/fromJSON.d.ts b/node_modules/postcss/lib/fromJSON.d.ts new file mode 100644 index 0000000..e1deedb --- /dev/null +++ b/node_modules/postcss/lib/fromJSON.d.ts @@ -0,0 +1,9 @@ +import { JSONHydrator } from './postcss.js' + +interface FromJSON extends JSONHydrator { + default: FromJSON +} + +declare const fromJSON: FromJSON + +export = fromJSON diff --git a/node_modules/postcss/lib/fromJSON.js b/node_modules/postcss/lib/fromJSON.js new file mode 100644 index 0000000..c9ac1a8 --- /dev/null +++ b/node_modules/postcss/lib/fromJSON.js @@ -0,0 +1,54 @@ +'use strict' + +let AtRule = require('./at-rule') +let Comment = require('./comment') +let Declaration = require('./declaration') +let Input = require('./input') +let PreviousMap = require('./previous-map') +let Root = require('./root') +let Rule = require('./rule') + +function fromJSON(json, inputs) { + if (Array.isArray(json)) return json.map(n => fromJSON(n)) + + let { inputs: ownInputs, ...defaults } = json + if (ownInputs) { + inputs = [] + for (let input of ownInputs) { + let inputHydrated = { ...input, __proto__: Input.prototype } + if (inputHydrated.map) { + inputHydrated.map = { + ...inputHydrated.map, + __proto__: PreviousMap.prototype + } + } + inputs.push(inputHydrated) + } + } + if (defaults.nodes) { + defaults.nodes = json.nodes.map(n => fromJSON(n, inputs)) + } + if (defaults.source) { + let { inputId, ...source } = defaults.source + defaults.source = source + if (inputId != null) { + defaults.source.input = inputs[inputId] + } + } + if (defaults.type === 'root') { + return new Root(defaults) + } else if (defaults.type === 'decl') { + return new Declaration(defaults) + } else if (defaults.type === 'rule') { + return new Rule(defaults) + } else if (defaults.type === 'comment') { + return new Comment(defaults) + } else if (defaults.type === 'atrule') { + return new AtRule(defaults) + } else { + throw new Error('Unknown node type: ' + json.type) + } +} + +module.exports = fromJSON +fromJSON.default = fromJSON diff --git a/node_modules/postcss/lib/input.d.ts b/node_modules/postcss/lib/input.d.ts new file mode 100644 index 0000000..46ded09 --- /dev/null +++ b/node_modules/postcss/lib/input.d.ts @@ -0,0 +1,197 @@ +import { CssSyntaxError, ProcessOptions } from './postcss.js' +import PreviousMap from './previous-map.js' + +declare namespace Input { + export interface FilePosition { + /** + * Column of inclusive start position in source file. + */ + column: number + + /** + * Column of exclusive end position in source file. + */ + endColumn?: number + + /** + * Line of exclusive end position in source file. + */ + endLine?: number + + /** + * Absolute path to the source file. + */ + file?: string + + /** + * Line of inclusive start position in source file. + */ + line: number + + /** + * Source code. + */ + source?: string + + /** + * URL for the source file. + */ + url: string + } + + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { Input_ as default } +} + +/** + * Represents the source CSS. + * + * ```js + * const root = postcss.parse(css, { from: file }) + * const input = root.source.input + * ``` + */ +declare class Input_ { + /** + * Input CSS source. + * + * ```js + * const input = postcss.parse('a{}', { from: file }).input + * input.css //=> "a{}" + * ``` + */ + css: string + + /** + * The absolute path to the CSS source file defined + * with the `from` option. + * + * ```js + * const root = postcss.parse(css, { from: 'a.css' }) + * root.source.input.file //=> '/home/ai/a.css' + * ``` + */ + file?: string + + /** + * The flag to indicate whether or not the source code has Unicode BOM. + */ + hasBOM: boolean + + /** + * The unique ID of the CSS source. It will be created if `from` option + * is not provided (because PostCSS does not know the file path). + * + * ```js + * const root = postcss.parse(css) + * root.source.input.file //=> undefined + * root.source.input.id //=> "" + * ``` + */ + id?: string + + /** + * The input source map passed from a compilation step before PostCSS + * (for example, from Sass compiler). + * + * ```js + * root.source.input.map.consumer().sources //=> ['a.sass'] + * ``` + */ + map: PreviousMap + + /** + * @param css Input CSS source. + * @param opts Process options. + */ + constructor(css: string, opts?: ProcessOptions) + + error( + message: string, + start: + | { + column: number + line: number + } + | { + offset: number + }, + end: + | { + column: number + line: number + } + | { + offset: number + }, + opts?: { plugin?: CssSyntaxError['plugin'] } + ): CssSyntaxError + + /** + * Returns `CssSyntaxError` with information about the error and its position. + */ + error( + message: string, + line: number, + column: number, + opts?: { plugin?: CssSyntaxError['plugin'] } + ): CssSyntaxError + + error( + message: string, + offset: number, + opts?: { plugin?: CssSyntaxError['plugin'] } + ): CssSyntaxError + + /** + * Converts source offset to line and column. + * + * @param offset Source offset. + */ + fromOffset(offset: number): { col: number; line: number } | null + /** + * Reads the input source map and returns a symbol position + * in the input source (e.g., in a Sass file that was compiled + * to CSS before being passed to PostCSS). Optionally takes an + * end position, exclusive. + * + * ```js + * root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 } + * root.source.input.origin(1, 1, 1, 4) + * //=> { file: 'a.css', line: 3, column: 1, endLine: 3, endColumn: 4 } + * ``` + * + * @param line Line for inclusive start position in input CSS. + * @param column Column for inclusive start position in input CSS. + * @param endLine Line for exclusive end position in input CSS. + * @param endColumn Column for exclusive end position in input CSS. + * + * @return Position in input source. + */ + origin( + line: number, + column: number, + endLine?: number, + endColumn?: number + ): false | Input.FilePosition + /** Converts this to a JSON-friendly object representation. */ + toJSON(): object + + /** + * The CSS source identifier. Contains `Input#file` if the user + * set the `from` option, or `Input#id` if they did not. + * + * ```js + * const root = postcss.parse(css, { from: 'a.css' }) + * root.source.input.from //=> "/home/ai/a.css" + * + * const root = postcss.parse(css) + * root.source.input.from //=> "" + * ``` + */ + get from(): string +} + +declare class Input extends Input_ {} + +export = Input diff --git a/node_modules/postcss/lib/input.js b/node_modules/postcss/lib/input.js new file mode 100644 index 0000000..685bce7 --- /dev/null +++ b/node_modules/postcss/lib/input.js @@ -0,0 +1,248 @@ +'use strict' + +let { nanoid } = require('nanoid/non-secure') +let { isAbsolute, resolve } = require('path') +let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js') +let { fileURLToPath, pathToFileURL } = require('url') + +let CssSyntaxError = require('./css-syntax-error') +let PreviousMap = require('./previous-map') +let terminalHighlight = require('./terminal-highlight') + +let fromOffsetCache = Symbol('fromOffsetCache') + +let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator) +let pathAvailable = Boolean(resolve && isAbsolute) + +class Input { + constructor(css, opts = {}) { + if ( + css === null || + typeof css === 'undefined' || + (typeof css === 'object' && !css.toString) + ) { + throw new Error(`PostCSS received ${css} instead of CSS string`) + } + + this.css = css.toString() + + if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') { + this.hasBOM = true + this.css = this.css.slice(1) + } else { + this.hasBOM = false + } + + if (opts.from) { + if ( + !pathAvailable || + /^\w+:\/\//.test(opts.from) || + isAbsolute(opts.from) + ) { + this.file = opts.from + } else { + this.file = resolve(opts.from) + } + } + + if (pathAvailable && sourceMapAvailable) { + let map = new PreviousMap(this.css, opts) + if (map.text) { + this.map = map + let file = map.consumer().file + if (!this.file && file) this.file = this.mapResolve(file) + } + } + + if (!this.file) { + this.id = '' + } + if (this.map) this.map.file = this.from + } + + error(message, line, column, opts = {}) { + let endColumn, endLine, result + + if (line && typeof line === 'object') { + let start = line + let end = column + if (typeof start.offset === 'number') { + let pos = this.fromOffset(start.offset) + line = pos.line + column = pos.col + } else { + line = start.line + column = start.column + } + if (typeof end.offset === 'number') { + let pos = this.fromOffset(end.offset) + endLine = pos.line + endColumn = pos.col + } else { + endLine = end.line + endColumn = end.column + } + } else if (!column) { + let pos = this.fromOffset(line) + line = pos.line + column = pos.col + } + + let origin = this.origin(line, column, endLine, endColumn) + if (origin) { + result = new CssSyntaxError( + message, + origin.endLine === undefined + ? origin.line + : { column: origin.column, line: origin.line }, + origin.endLine === undefined + ? origin.column + : { column: origin.endColumn, line: origin.endLine }, + origin.source, + origin.file, + opts.plugin + ) + } else { + result = new CssSyntaxError( + message, + endLine === undefined ? line : { column, line }, + endLine === undefined ? column : { column: endColumn, line: endLine }, + this.css, + this.file, + opts.plugin + ) + } + + result.input = { column, endColumn, endLine, line, source: this.css } + if (this.file) { + if (pathToFileURL) { + result.input.url = pathToFileURL(this.file).toString() + } + result.input.file = this.file + } + + return result + } + + fromOffset(offset) { + let lastLine, lineToIndex + if (!this[fromOffsetCache]) { + let lines = this.css.split('\n') + lineToIndex = new Array(lines.length) + let prevIndex = 0 + + for (let i = 0, l = lines.length; i < l; i++) { + lineToIndex[i] = prevIndex + prevIndex += lines[i].length + 1 + } + + this[fromOffsetCache] = lineToIndex + } else { + lineToIndex = this[fromOffsetCache] + } + lastLine = lineToIndex[lineToIndex.length - 1] + + let min = 0 + if (offset >= lastLine) { + min = lineToIndex.length - 1 + } else { + let max = lineToIndex.length - 2 + let mid + while (min < max) { + mid = min + ((max - min) >> 1) + if (offset < lineToIndex[mid]) { + max = mid - 1 + } else if (offset >= lineToIndex[mid + 1]) { + min = mid + 1 + } else { + min = mid + break + } + } + } + return { + col: offset - lineToIndex[min] + 1, + line: min + 1 + } + } + + mapResolve(file) { + if (/^\w+:\/\//.test(file)) { + return file + } + return resolve(this.map.consumer().sourceRoot || this.map.root || '.', file) + } + + origin(line, column, endLine, endColumn) { + if (!this.map) return false + let consumer = this.map.consumer() + + let from = consumer.originalPositionFor({ column, line }) + if (!from.source) return false + + let to + if (typeof endLine === 'number') { + to = consumer.originalPositionFor({ column: endColumn, line: endLine }) + } + + let fromUrl + + if (isAbsolute(from.source)) { + fromUrl = pathToFileURL(from.source) + } else { + fromUrl = new URL( + from.source, + this.map.consumer().sourceRoot || pathToFileURL(this.map.mapFile) + ) + } + + let result = { + column: from.column, + endColumn: to && to.column, + endLine: to && to.line, + line: from.line, + url: fromUrl.toString() + } + + if (fromUrl.protocol === 'file:') { + if (fileURLToPath) { + result.file = fileURLToPath(fromUrl) + } else { + /* c8 ignore next 2 */ + throw new Error(`file: protocol is not available in this PostCSS build`) + } + } + + let source = consumer.sourceContentFor(from.source) + if (source) result.source = source + + return result + } + + toJSON() { + let json = {} + for (let name of ['hasBOM', 'css', 'file', 'id']) { + if (this[name] != null) { + json[name] = this[name] + } + } + if (this.map) { + json.map = { ...this.map } + if (json.map.consumerCache) { + json.map.consumerCache = undefined + } + } + return json + } + + get from() { + return this.file || this.id + } +} + +module.exports = Input +Input.default = Input + +if (terminalHighlight && terminalHighlight.registerInput) { + terminalHighlight.registerInput(Input) +} diff --git a/node_modules/postcss/lib/lazy-result.d.ts b/node_modules/postcss/lib/lazy-result.d.ts new file mode 100644 index 0000000..dd291aa --- /dev/null +++ b/node_modules/postcss/lib/lazy-result.d.ts @@ -0,0 +1,190 @@ +import Document from './document.js' +import { SourceMap } from './postcss.js' +import Processor from './processor.js' +import Result, { Message, ResultOptions } from './result.js' +import Root from './root.js' +import Warning from './warning.js' + +declare namespace LazyResult { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { LazyResult_ as default } +} + +/** + * A Promise proxy for the result of PostCSS transformations. + * + * A `LazyResult` instance is returned by `Processor#process`. + * + * ```js + * const lazy = postcss([autoprefixer]).process(css) + * ``` + */ +declare class LazyResult_ + implements PromiseLike> +{ + /** + * Processes input CSS through synchronous and asynchronous plugins + * and calls onRejected for each error thrown in any plugin. + * + * It implements standard Promise API. + * + * ```js + * postcss([autoprefixer]).process(css).then(result => { + * console.log(result.css) + * }).catch(error => { + * console.error(error) + * }) + * ``` + */ + catch: Promise>['catch'] + + /** + * Processes input CSS through synchronous and asynchronous plugins + * and calls onFinally on any error or when all plugins will finish work. + * + * It implements standard Promise API. + * + * ```js + * postcss([autoprefixer]).process(css).finally(() => { + * console.log('processing ended') + * }) + * ``` + */ + finally: Promise>['finally'] + + /** + * Processes input CSS through synchronous and asynchronous plugins + * and calls `onFulfilled` with a Result instance. If a plugin throws + * an error, the `onRejected` callback will be executed. + * + * It implements standard Promise API. + * + * ```js + * postcss([autoprefixer]).process(css, { from: cssPath }).then(result => { + * console.log(result.css) + * }) + * ``` + */ + then: Promise>['then'] + + /** + * @param processor Processor used for this transformation. + * @param css CSS to parse and transform. + * @param opts Options from the `Processor#process` or `Root#toResult`. + */ + constructor(processor: Processor, css: string, opts: ResultOptions) + + /** + * Run plugin in async way and return `Result`. + * + * @return Result with output content. + */ + async(): Promise> + + /** + * Run plugin in sync way and return `Result`. + * + * @return Result with output content. + */ + sync(): Result + + /** + * Alias for the `LazyResult#css` property. + * + * ```js + * lazy + '' === lazy.css + * ``` + * + * @return Output CSS. + */ + toString(): string + + /** + * Processes input CSS through synchronous plugins + * and calls `Result#warnings`. + * + * @return Warnings from plugins. + */ + warnings(): Warning[] + + /** + * An alias for the `css` property. Use it with syntaxes + * that generate non-CSS output. + * + * This property will only work with synchronous plugins. + * If the processor contains any asynchronous plugins + * it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get content(): string + + /** + * Processes input CSS through synchronous plugins, converts `Root` + * to a CSS string and returns `Result#css`. + * + * This property will only work with synchronous plugins. + * If the processor contains any asynchronous plugins + * it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get css(): string + + /** + * Processes input CSS through synchronous plugins + * and returns `Result#map`. + * + * This property will only work with synchronous plugins. + * If the processor contains any asynchronous plugins + * it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get map(): SourceMap + + /** + * Processes input CSS through synchronous plugins + * and returns `Result#messages`. + * + * This property will only work with synchronous plugins. If the processor + * contains any asynchronous plugins it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get messages(): Message[] + + /** + * Options from the `Processor#process` call. + */ + get opts(): ResultOptions + + /** + * Returns a `Processor` instance, which will be used + * for CSS transformations. + */ + get processor(): Processor + + /** + * Processes input CSS through synchronous plugins + * and returns `Result#root`. + * + * This property will only work with synchronous plugins. If the processor + * contains any asynchronous plugins it will throw an error. + * + * PostCSS runners should always use `LazyResult#then`. + */ + get root(): RootNode + + /** + * Returns the default string description of an object. + * Required to implement the Promise interface. + */ + get [Symbol.toStringTag](): string +} + +declare class LazyResult< + RootNode = Document | Root +> extends LazyResult_ {} + +export = LazyResult diff --git a/node_modules/postcss/lib/lazy-result.js b/node_modules/postcss/lib/lazy-result.js new file mode 100644 index 0000000..e27701d --- /dev/null +++ b/node_modules/postcss/lib/lazy-result.js @@ -0,0 +1,550 @@ +'use strict' + +let Container = require('./container') +let Document = require('./document') +let MapGenerator = require('./map-generator') +let parse = require('./parse') +let Result = require('./result') +let Root = require('./root') +let stringify = require('./stringify') +let { isClean, my } = require('./symbols') +let warnOnce = require('./warn-once') + +const TYPE_TO_CLASS_NAME = { + atrule: 'AtRule', + comment: 'Comment', + decl: 'Declaration', + document: 'Document', + root: 'Root', + rule: 'Rule' +} + +const PLUGIN_PROPS = { + AtRule: true, + AtRuleExit: true, + Comment: true, + CommentExit: true, + Declaration: true, + DeclarationExit: true, + Document: true, + DocumentExit: true, + Once: true, + OnceExit: true, + postcssPlugin: true, + prepare: true, + Root: true, + RootExit: true, + Rule: true, + RuleExit: true +} + +const NOT_VISITORS = { + Once: true, + postcssPlugin: true, + prepare: true +} + +const CHILDREN = 0 + +function isPromise(obj) { + return typeof obj === 'object' && typeof obj.then === 'function' +} + +function getEvents(node) { + let key = false + let type = TYPE_TO_CLASS_NAME[node.type] + if (node.type === 'decl') { + key = node.prop.toLowerCase() + } else if (node.type === 'atrule') { + key = node.name.toLowerCase() + } + + if (key && node.append) { + return [ + type, + type + '-' + key, + CHILDREN, + type + 'Exit', + type + 'Exit-' + key + ] + } else if (key) { + return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key] + } else if (node.append) { + return [type, CHILDREN, type + 'Exit'] + } else { + return [type, type + 'Exit'] + } +} + +function toStack(node) { + let events + if (node.type === 'document') { + events = ['Document', CHILDREN, 'DocumentExit'] + } else if (node.type === 'root') { + events = ['Root', CHILDREN, 'RootExit'] + } else { + events = getEvents(node) + } + + return { + eventIndex: 0, + events, + iterator: 0, + node, + visitorIndex: 0, + visitors: [] + } +} + +function cleanMarks(node) { + node[isClean] = false + if (node.nodes) node.nodes.forEach(i => cleanMarks(i)) + return node +} + +let postcss = {} + +class LazyResult { + constructor(processor, css, opts) { + this.stringified = false + this.processed = false + + let root + if ( + typeof css === 'object' && + css !== null && + (css.type === 'root' || css.type === 'document') + ) { + root = cleanMarks(css) + } else if (css instanceof LazyResult || css instanceof Result) { + root = cleanMarks(css.root) + if (css.map) { + if (typeof opts.map === 'undefined') opts.map = {} + if (!opts.map.inline) opts.map.inline = false + opts.map.prev = css.map + } + } else { + let parser = parse + if (opts.syntax) parser = opts.syntax.parse + if (opts.parser) parser = opts.parser + if (parser.parse) parser = parser.parse + + try { + root = parser(css, opts) + } catch (error) { + this.processed = true + this.error = error + } + + if (root && !root[my]) { + /* c8 ignore next 2 */ + Container.rebuild(root) + } + } + + this.result = new Result(processor, root, opts) + this.helpers = { ...postcss, postcss, result: this.result } + this.plugins = this.processor.plugins.map(plugin => { + if (typeof plugin === 'object' && plugin.prepare) { + return { ...plugin, ...plugin.prepare(this.result) } + } else { + return plugin + } + }) + } + + async() { + if (this.error) return Promise.reject(this.error) + if (this.processed) return Promise.resolve(this.result) + if (!this.processing) { + this.processing = this.runAsync() + } + return this.processing + } + + catch(onRejected) { + return this.async().catch(onRejected) + } + + finally(onFinally) { + return this.async().then(onFinally, onFinally) + } + + getAsyncError() { + throw new Error('Use process(css).then(cb) to work with async plugins') + } + + handleError(error, node) { + let plugin = this.result.lastPlugin + try { + if (node) node.addToError(error) + this.error = error + if (error.name === 'CssSyntaxError' && !error.plugin) { + error.plugin = plugin.postcssPlugin + error.setMessage() + } else if (plugin.postcssVersion) { + if (process.env.NODE_ENV !== 'production') { + let pluginName = plugin.postcssPlugin + let pluginVer = plugin.postcssVersion + let runtimeVer = this.result.processor.version + let a = pluginVer.split('.') + let b = runtimeVer.split('.') + + if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) { + // eslint-disable-next-line no-console + console.error( + 'Unknown error from PostCSS plugin. Your current PostCSS ' + + 'version is ' + + runtimeVer + + ', but ' + + pluginName + + ' uses ' + + pluginVer + + '. Perhaps this is the source of the error below.' + ) + } + } + } + } catch (err) { + /* c8 ignore next 3 */ + // eslint-disable-next-line no-console + if (console && console.error) console.error(err) + } + return error + } + + prepareVisitors() { + this.listeners = {} + let add = (plugin, type, cb) => { + if (!this.listeners[type]) this.listeners[type] = [] + this.listeners[type].push([plugin, cb]) + } + for (let plugin of this.plugins) { + if (typeof plugin === 'object') { + for (let event in plugin) { + if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) { + throw new Error( + `Unknown event ${event} in ${plugin.postcssPlugin}. ` + + `Try to update PostCSS (${this.processor.version} now).` + ) + } + if (!NOT_VISITORS[event]) { + if (typeof plugin[event] === 'object') { + for (let filter in plugin[event]) { + if (filter === '*') { + add(plugin, event, plugin[event][filter]) + } else { + add( + plugin, + event + '-' + filter.toLowerCase(), + plugin[event][filter] + ) + } + } + } else if (typeof plugin[event] === 'function') { + add(plugin, event, plugin[event]) + } + } + } + } + } + this.hasListener = Object.keys(this.listeners).length > 0 + } + + async runAsync() { + this.plugin = 0 + for (let i = 0; i < this.plugins.length; i++) { + let plugin = this.plugins[i] + let promise = this.runOnRoot(plugin) + if (isPromise(promise)) { + try { + await promise + } catch (error) { + throw this.handleError(error) + } + } + } + + this.prepareVisitors() + if (this.hasListener) { + let root = this.result.root + while (!root[isClean]) { + root[isClean] = true + let stack = [toStack(root)] + while (stack.length > 0) { + let promise = this.visitTick(stack) + if (isPromise(promise)) { + try { + await promise + } catch (e) { + let node = stack[stack.length - 1].node + throw this.handleError(e, node) + } + } + } + } + + if (this.listeners.OnceExit) { + for (let [plugin, visitor] of this.listeners.OnceExit) { + this.result.lastPlugin = plugin + try { + if (root.type === 'document') { + let roots = root.nodes.map(subRoot => + visitor(subRoot, this.helpers) + ) + + await Promise.all(roots) + } else { + await visitor(root, this.helpers) + } + } catch (e) { + throw this.handleError(e) + } + } + } + } + + this.processed = true + return this.stringify() + } + + runOnRoot(plugin) { + this.result.lastPlugin = plugin + try { + if (typeof plugin === 'object' && plugin.Once) { + if (this.result.root.type === 'document') { + let roots = this.result.root.nodes.map(root => + plugin.Once(root, this.helpers) + ) + + if (isPromise(roots[0])) { + return Promise.all(roots) + } + + return roots + } + + return plugin.Once(this.result.root, this.helpers) + } else if (typeof plugin === 'function') { + return plugin(this.result.root, this.result) + } + } catch (error) { + throw this.handleError(error) + } + } + + stringify() { + if (this.error) throw this.error + if (this.stringified) return this.result + this.stringified = true + + this.sync() + + let opts = this.result.opts + let str = stringify + if (opts.syntax) str = opts.syntax.stringify + if (opts.stringifier) str = opts.stringifier + if (str.stringify) str = str.stringify + + let map = new MapGenerator(str, this.result.root, this.result.opts) + let data = map.generate() + this.result.css = data[0] + this.result.map = data[1] + + return this.result + } + + sync() { + if (this.error) throw this.error + if (this.processed) return this.result + this.processed = true + + if (this.processing) { + throw this.getAsyncError() + } + + for (let plugin of this.plugins) { + let promise = this.runOnRoot(plugin) + if (isPromise(promise)) { + throw this.getAsyncError() + } + } + + this.prepareVisitors() + if (this.hasListener) { + let root = this.result.root + while (!root[isClean]) { + root[isClean] = true + this.walkSync(root) + } + if (this.listeners.OnceExit) { + if (root.type === 'document') { + for (let subRoot of root.nodes) { + this.visitSync(this.listeners.OnceExit, subRoot) + } + } else { + this.visitSync(this.listeners.OnceExit, root) + } + } + } + + return this.result + } + + then(onFulfilled, onRejected) { + if (process.env.NODE_ENV !== 'production') { + if (!('from' in this.opts)) { + warnOnce( + 'Without `from` option PostCSS could generate wrong source map ' + + 'and will not find Browserslist config. Set it to CSS file path ' + + 'or to `undefined` to prevent this warning.' + ) + } + } + return this.async().then(onFulfilled, onRejected) + } + + toString() { + return this.css + } + + visitSync(visitors, node) { + for (let [plugin, visitor] of visitors) { + this.result.lastPlugin = plugin + let promise + try { + promise = visitor(node, this.helpers) + } catch (e) { + throw this.handleError(e, node.proxyOf) + } + if (node.type !== 'root' && node.type !== 'document' && !node.parent) { + return true + } + if (isPromise(promise)) { + throw this.getAsyncError() + } + } + } + + visitTick(stack) { + let visit = stack[stack.length - 1] + let { node, visitors } = visit + + if (node.type !== 'root' && node.type !== 'document' && !node.parent) { + stack.pop() + return + } + + if (visitors.length > 0 && visit.visitorIndex < visitors.length) { + let [plugin, visitor] = visitors[visit.visitorIndex] + visit.visitorIndex += 1 + if (visit.visitorIndex === visitors.length) { + visit.visitors = [] + visit.visitorIndex = 0 + } + this.result.lastPlugin = plugin + try { + return visitor(node.toProxy(), this.helpers) + } catch (e) { + throw this.handleError(e, node) + } + } + + if (visit.iterator !== 0) { + let iterator = visit.iterator + let child + while ((child = node.nodes[node.indexes[iterator]])) { + node.indexes[iterator] += 1 + if (!child[isClean]) { + child[isClean] = true + stack.push(toStack(child)) + return + } + } + visit.iterator = 0 + delete node.indexes[iterator] + } + + let events = visit.events + while (visit.eventIndex < events.length) { + let event = events[visit.eventIndex] + visit.eventIndex += 1 + if (event === CHILDREN) { + if (node.nodes && node.nodes.length) { + node[isClean] = true + visit.iterator = node.getIterator() + } + return + } else if (this.listeners[event]) { + visit.visitors = this.listeners[event] + return + } + } + stack.pop() + } + + walkSync(node) { + node[isClean] = true + let events = getEvents(node) + for (let event of events) { + if (event === CHILDREN) { + if (node.nodes) { + node.each(child => { + if (!child[isClean]) this.walkSync(child) + }) + } + } else { + let visitors = this.listeners[event] + if (visitors) { + if (this.visitSync(visitors, node.toProxy())) return + } + } + } + } + + warnings() { + return this.sync().warnings() + } + + get content() { + return this.stringify().content + } + + get css() { + return this.stringify().css + } + + get map() { + return this.stringify().map + } + + get messages() { + return this.sync().messages + } + + get opts() { + return this.result.opts + } + + get processor() { + return this.result.processor + } + + get root() { + return this.sync().root + } + + get [Symbol.toStringTag]() { + return 'LazyResult' + } +} + +LazyResult.registerPostcss = dependant => { + postcss = dependant +} + +module.exports = LazyResult +LazyResult.default = LazyResult + +Root.registerLazyResult(LazyResult) +Document.registerLazyResult(LazyResult) diff --git a/node_modules/postcss/lib/list.d.ts b/node_modules/postcss/lib/list.d.ts new file mode 100644 index 0000000..e262ad3 --- /dev/null +++ b/node_modules/postcss/lib/list.d.ts @@ -0,0 +1,60 @@ +declare namespace list { + type List = { + /** + * Safely splits comma-separated values (such as those for `transition-*` + * and `background` properties). + * + * ```js + * Once (root, { list }) { + * list.comma('black, linear-gradient(white, black)') + * //=> ['black', 'linear-gradient(white, black)'] + * } + * ``` + * + * @param str Comma-separated values. + * @return Split values. + */ + comma(str: string): string[] + + default: List + + /** + * Safely splits space-separated values (such as those for `background`, + * `border-radius`, and other shorthand properties). + * + * ```js + * Once (root, { list }) { + * list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)'] + * } + * ``` + * + * @param str Space-separated values. + * @return Split values. + */ + space(str: string): string[] + + /** + * Safely splits values. + * + * ```js + * Once (root, { list }) { + * list.split('1px calc(10% + 1px)', [' ', '\n', '\t']) //=> ['1px', 'calc(10% + 1px)'] + * } + * ``` + * + * @param string separated values. + * @param separators array of separators. + * @param last boolean indicator. + * @return Split values. + */ + split( + string: string, + separators: readonly string[], + last: boolean + ): string[] + } +} + +declare const list: list.List + +export = list diff --git a/node_modules/postcss/lib/list.js b/node_modules/postcss/lib/list.js new file mode 100644 index 0000000..1b31f98 --- /dev/null +++ b/node_modules/postcss/lib/list.js @@ -0,0 +1,58 @@ +'use strict' + +let list = { + comma(string) { + return list.split(string, [','], true) + }, + + space(string) { + let spaces = [' ', '\n', '\t'] + return list.split(string, spaces) + }, + + split(string, separators, last) { + let array = [] + let current = '' + let split = false + + let func = 0 + let inQuote = false + let prevQuote = '' + let escape = false + + for (let letter of string) { + if (escape) { + escape = false + } else if (letter === '\\') { + escape = true + } else if (inQuote) { + if (letter === prevQuote) { + inQuote = false + } + } else if (letter === '"' || letter === "'") { + inQuote = true + prevQuote = letter + } else if (letter === '(') { + func += 1 + } else if (letter === ')') { + if (func > 0) func -= 1 + } else if (func === 0) { + if (separators.includes(letter)) split = true + } + + if (split) { + if (current !== '') array.push(current.trim()) + current = '' + split = false + } else { + current += letter + } + } + + if (last || current !== '') array.push(current.trim()) + return array + } +} + +module.exports = list +list.default = list diff --git a/node_modules/postcss/lib/map-generator.js b/node_modules/postcss/lib/map-generator.js new file mode 100644 index 0000000..89069d3 --- /dev/null +++ b/node_modules/postcss/lib/map-generator.js @@ -0,0 +1,368 @@ +'use strict' + +let { dirname, relative, resolve, sep } = require('path') +let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js') +let { pathToFileURL } = require('url') + +let Input = require('./input') + +let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator) +let pathAvailable = Boolean(dirname && resolve && relative && sep) + +class MapGenerator { + constructor(stringify, root, opts, cssString) { + this.stringify = stringify + this.mapOpts = opts.map || {} + this.root = root + this.opts = opts + this.css = cssString + this.originalCSS = cssString + this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute + + this.memoizedFileURLs = new Map() + this.memoizedPaths = new Map() + this.memoizedURLs = new Map() + } + + addAnnotation() { + let content + + if (this.isInline()) { + content = + 'data:application/json;base64,' + this.toBase64(this.map.toString()) + } else if (typeof this.mapOpts.annotation === 'string') { + content = this.mapOpts.annotation + } else if (typeof this.mapOpts.annotation === 'function') { + content = this.mapOpts.annotation(this.opts.to, this.root) + } else { + content = this.outputFile() + '.map' + } + let eol = '\n' + if (this.css.includes('\r\n')) eol = '\r\n' + + this.css += eol + '/*# sourceMappingURL=' + content + ' */' + } + + applyPrevMaps() { + for (let prev of this.previous()) { + let from = this.toUrl(this.path(prev.file)) + let root = prev.root || dirname(prev.file) + let map + + if (this.mapOpts.sourcesContent === false) { + map = new SourceMapConsumer(prev.text) + if (map.sourcesContent) { + map.sourcesContent = null + } + } else { + map = prev.consumer() + } + + this.map.applySourceMap(map, from, this.toUrl(this.path(root))) + } + } + + clearAnnotation() { + if (this.mapOpts.annotation === false) return + + if (this.root) { + let node + for (let i = this.root.nodes.length - 1; i >= 0; i--) { + node = this.root.nodes[i] + if (node.type !== 'comment') continue + if (node.text.startsWith('# sourceMappingURL=')) { + this.root.removeChild(i) + } + } + } else if (this.css) { + this.css = this.css.replace(/\n*\/\*#[\S\s]*?\*\/$/gm, '') + } + } + + generate() { + this.clearAnnotation() + if (pathAvailable && sourceMapAvailable && this.isMap()) { + return this.generateMap() + } else { + let result = '' + this.stringify(this.root, i => { + result += i + }) + return [result] + } + } + + generateMap() { + if (this.root) { + this.generateString() + } else if (this.previous().length === 1) { + let prev = this.previous()[0].consumer() + prev.file = this.outputFile() + this.map = SourceMapGenerator.fromSourceMap(prev, { + ignoreInvalidMapping: true + }) + } else { + this.map = new SourceMapGenerator({ + file: this.outputFile(), + ignoreInvalidMapping: true + }) + this.map.addMapping({ + generated: { column: 0, line: 1 }, + original: { column: 0, line: 1 }, + source: this.opts.from + ? this.toUrl(this.path(this.opts.from)) + : '' + }) + } + + if (this.isSourcesContent()) this.setSourcesContent() + if (this.root && this.previous().length > 0) this.applyPrevMaps() + if (this.isAnnotation()) this.addAnnotation() + + if (this.isInline()) { + return [this.css] + } else { + return [this.css, this.map] + } + } + + generateString() { + this.css = '' + this.map = new SourceMapGenerator({ + file: this.outputFile(), + ignoreInvalidMapping: true + }) + + let line = 1 + let column = 1 + + let noSource = '' + let mapping = { + generated: { column: 0, line: 0 }, + original: { column: 0, line: 0 }, + source: '' + } + + let last, lines + this.stringify(this.root, (str, node, type) => { + this.css += str + + if (node && type !== 'end') { + mapping.generated.line = line + mapping.generated.column = column - 1 + if (node.source && node.source.start) { + mapping.source = this.sourcePath(node) + mapping.original.line = node.source.start.line + mapping.original.column = node.source.start.column - 1 + this.map.addMapping(mapping) + } else { + mapping.source = noSource + mapping.original.line = 1 + mapping.original.column = 0 + this.map.addMapping(mapping) + } + } + + lines = str.match(/\n/g) + if (lines) { + line += lines.length + last = str.lastIndexOf('\n') + column = str.length - last + } else { + column += str.length + } + + if (node && type !== 'start') { + let p = node.parent || { raws: {} } + let childless = + node.type === 'decl' || (node.type === 'atrule' && !node.nodes) + if (!childless || node !== p.last || p.raws.semicolon) { + if (node.source && node.source.end) { + mapping.source = this.sourcePath(node) + mapping.original.line = node.source.end.line + mapping.original.column = node.source.end.column - 1 + mapping.generated.line = line + mapping.generated.column = column - 2 + this.map.addMapping(mapping) + } else { + mapping.source = noSource + mapping.original.line = 1 + mapping.original.column = 0 + mapping.generated.line = line + mapping.generated.column = column - 1 + this.map.addMapping(mapping) + } + } + } + }) + } + + isAnnotation() { + if (this.isInline()) { + return true + } + if (typeof this.mapOpts.annotation !== 'undefined') { + return this.mapOpts.annotation + } + if (this.previous().length) { + return this.previous().some(i => i.annotation) + } + return true + } + + isInline() { + if (typeof this.mapOpts.inline !== 'undefined') { + return this.mapOpts.inline + } + + let annotation = this.mapOpts.annotation + if (typeof annotation !== 'undefined' && annotation !== true) { + return false + } + + if (this.previous().length) { + return this.previous().some(i => i.inline) + } + return true + } + + isMap() { + if (typeof this.opts.map !== 'undefined') { + return !!this.opts.map + } + return this.previous().length > 0 + } + + isSourcesContent() { + if (typeof this.mapOpts.sourcesContent !== 'undefined') { + return this.mapOpts.sourcesContent + } + if (this.previous().length) { + return this.previous().some(i => i.withContent()) + } + return true + } + + outputFile() { + if (this.opts.to) { + return this.path(this.opts.to) + } else if (this.opts.from) { + return this.path(this.opts.from) + } else { + return 'to.css' + } + } + + path(file) { + if (this.mapOpts.absolute) return file + if (file.charCodeAt(0) === 60 /* `<` */) return file + if (/^\w+:\/\//.test(file)) return file + let cached = this.memoizedPaths.get(file) + if (cached) return cached + + let from = this.opts.to ? dirname(this.opts.to) : '.' + + if (typeof this.mapOpts.annotation === 'string') { + from = dirname(resolve(from, this.mapOpts.annotation)) + } + + let path = relative(from, file) + this.memoizedPaths.set(file, path) + + return path + } + + previous() { + if (!this.previousMaps) { + this.previousMaps = [] + if (this.root) { + this.root.walk(node => { + if (node.source && node.source.input.map) { + let map = node.source.input.map + if (!this.previousMaps.includes(map)) { + this.previousMaps.push(map) + } + } + }) + } else { + let input = new Input(this.originalCSS, this.opts) + if (input.map) this.previousMaps.push(input.map) + } + } + + return this.previousMaps + } + + setSourcesContent() { + let already = {} + if (this.root) { + this.root.walk(node => { + if (node.source) { + let from = node.source.input.from + if (from && !already[from]) { + already[from] = true + let fromUrl = this.usesFileUrls + ? this.toFileUrl(from) + : this.toUrl(this.path(from)) + this.map.setSourceContent(fromUrl, node.source.input.css) + } + } + }) + } else if (this.css) { + let from = this.opts.from + ? this.toUrl(this.path(this.opts.from)) + : '' + this.map.setSourceContent(from, this.css) + } + } + + sourcePath(node) { + if (this.mapOpts.from) { + return this.toUrl(this.mapOpts.from) + } else if (this.usesFileUrls) { + return this.toFileUrl(node.source.input.from) + } else { + return this.toUrl(this.path(node.source.input.from)) + } + } + + toBase64(str) { + if (Buffer) { + return Buffer.from(str).toString('base64') + } else { + return window.btoa(unescape(encodeURIComponent(str))) + } + } + + toFileUrl(path) { + let cached = this.memoizedFileURLs.get(path) + if (cached) return cached + + if (pathToFileURL) { + let fileURL = pathToFileURL(path).toString() + this.memoizedFileURLs.set(path, fileURL) + + return fileURL + } else { + throw new Error( + '`map.absolute` option is not available in this PostCSS build' + ) + } + } + + toUrl(path) { + let cached = this.memoizedURLs.get(path) + if (cached) return cached + + if (sep === '\\') { + path = path.replace(/\\/g, '/') + } + + let url = encodeURI(path).replace(/[#?]/g, encodeURIComponent) + this.memoizedURLs.set(path, url) + + return url + } +} + +module.exports = MapGenerator diff --git a/node_modules/postcss/lib/no-work-result.d.ts b/node_modules/postcss/lib/no-work-result.d.ts new file mode 100644 index 0000000..8039076 --- /dev/null +++ b/node_modules/postcss/lib/no-work-result.d.ts @@ -0,0 +1,46 @@ +import LazyResult from './lazy-result.js' +import { SourceMap } from './postcss.js' +import Processor from './processor.js' +import Result, { Message, ResultOptions } from './result.js' +import Root from './root.js' +import Warning from './warning.js' + +declare namespace NoWorkResult { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { NoWorkResult_ as default } +} + +/** + * A Promise proxy for the result of PostCSS transformations. + * This lazy result instance doesn't parse css unless `NoWorkResult#root` or `Result#root` + * are accessed. See the example below for details. + * A `NoWork` instance is returned by `Processor#process` ONLY when no plugins defined. + * + * ```js + * const noWorkResult = postcss().process(css) // No plugins are defined. + * // CSS is not parsed + * let root = noWorkResult.root // now css is parsed because we accessed the root + * ``` + */ +declare class NoWorkResult_ implements LazyResult { + catch: Promise>['catch'] + finally: Promise>['finally'] + then: Promise>['then'] + constructor(processor: Processor, css: string, opts: ResultOptions) + async(): Promise> + sync(): Result + toString(): string + warnings(): Warning[] + get content(): string + get css(): string + get map(): SourceMap + get messages(): Message[] + get opts(): ResultOptions + get processor(): Processor + get root(): Root + get [Symbol.toStringTag](): string +} + +declare class NoWorkResult extends NoWorkResult_ {} + +export = NoWorkResult diff --git a/node_modules/postcss/lib/no-work-result.js b/node_modules/postcss/lib/no-work-result.js new file mode 100644 index 0000000..a84d843 --- /dev/null +++ b/node_modules/postcss/lib/no-work-result.js @@ -0,0 +1,138 @@ +'use strict' + +let MapGenerator = require('./map-generator') +let parse = require('./parse') +const Result = require('./result') +let stringify = require('./stringify') +let warnOnce = require('./warn-once') + +class NoWorkResult { + constructor(processor, css, opts) { + css = css.toString() + this.stringified = false + + this._processor = processor + this._css = css + this._opts = opts + this._map = undefined + let root + + let str = stringify + this.result = new Result(this._processor, root, this._opts) + this.result.css = css + + let self = this + Object.defineProperty(this.result, 'root', { + get() { + return self.root + } + }) + + let map = new MapGenerator(str, root, this._opts, css) + if (map.isMap()) { + let [generatedCSS, generatedMap] = map.generate() + if (generatedCSS) { + this.result.css = generatedCSS + } + if (generatedMap) { + this.result.map = generatedMap + } + } else { + map.clearAnnotation() + this.result.css = map.css + } + } + + async() { + if (this.error) return Promise.reject(this.error) + return Promise.resolve(this.result) + } + + catch(onRejected) { + return this.async().catch(onRejected) + } + + finally(onFinally) { + return this.async().then(onFinally, onFinally) + } + + sync() { + if (this.error) throw this.error + return this.result + } + + then(onFulfilled, onRejected) { + if (process.env.NODE_ENV !== 'production') { + if (!('from' in this._opts)) { + warnOnce( + 'Without `from` option PostCSS could generate wrong source map ' + + 'and will not find Browserslist config. Set it to CSS file path ' + + 'or to `undefined` to prevent this warning.' + ) + } + } + + return this.async().then(onFulfilled, onRejected) + } + + toString() { + return this._css + } + + warnings() { + return [] + } + + get content() { + return this.result.css + } + + get css() { + return this.result.css + } + + get map() { + return this.result.map + } + + get messages() { + return [] + } + + get opts() { + return this.result.opts + } + + get processor() { + return this.result.processor + } + + get root() { + if (this._root) { + return this._root + } + + let root + let parser = parse + + try { + root = parser(this._css, this._opts) + } catch (error) { + this.error = error + } + + if (this.error) { + throw this.error + } else { + this._root = root + return root + } + } + + get [Symbol.toStringTag]() { + return 'NoWorkResult' + } +} + +module.exports = NoWorkResult +NoWorkResult.default = NoWorkResult diff --git a/node_modules/postcss/lib/node.d.ts b/node_modules/postcss/lib/node.d.ts new file mode 100644 index 0000000..3597670 --- /dev/null +++ b/node_modules/postcss/lib/node.d.ts @@ -0,0 +1,541 @@ +import AtRule = require('./at-rule.js') + +import { AtRuleProps } from './at-rule.js' +import Comment, { CommentProps } from './comment.js' +import Container, { NewChild } from './container.js' +import CssSyntaxError from './css-syntax-error.js' +import Declaration, { DeclarationProps } from './declaration.js' +import Document from './document.js' +import Input from './input.js' +import { Stringifier, Syntax } from './postcss.js' +import Result from './result.js' +import Root from './root.js' +import Rule, { RuleProps } from './rule.js' +import Warning, { WarningOptions } from './warning.js' + +declare namespace Node { + export type ChildNode = AtRule.default | Comment | Declaration | Rule + + export type AnyNode = + | AtRule.default + | Comment + | Declaration + | Document + | Root + | Rule + + export type ChildProps = + | AtRuleProps + | CommentProps + | DeclarationProps + | RuleProps + + export interface Position { + /** + * Source line in file. In contrast to `offset` it starts from 1. + */ + column: number + + /** + * Source column in file. + */ + line: number + + /** + * Source offset in file. It starts from 0. + */ + offset: number + } + + export interface Range { + /** + * End position, exclusive. + */ + end: Position + + /** + * Start position, inclusive. + */ + start: Position + } + + /** + * Source represents an interface for the {@link Node.source} property. + */ + export interface Source { + /** + * The inclusive ending position for the source + * code of a node. + */ + end?: Position + + /** + * The source file from where a node has originated. + */ + input: Input + + /** + * The inclusive starting position for the source + * code of a node. + */ + start?: Position + } + + /** + * Interface represents an interface for an object received + * as parameter by Node class constructor. + */ + export interface NodeProps { + source?: Source + } + + export interface NodeErrorOptions { + /** + * An ending index inside a node's string that should be highlighted as + * source of error. + */ + endIndex?: number + /** + * An index inside a node's string that should be highlighted as source + * of error. + */ + index?: number + /** + * Plugin name that created this error. PostCSS will set it automatically. + */ + plugin?: string + /** + * A word inside a node's string, that should be highlighted as source + * of error. + */ + word?: string + } + + // eslint-disable-next-line @typescript-eslint/no-shadow + class Node extends Node_ {} + export { Node as default } +} + +/** + * It represents an abstract class that handles common + * methods for other CSS abstract syntax tree nodes. + * + * Any node that represents CSS selector or value should + * not extend the `Node` class. + */ +declare abstract class Node_ { + /** + * It represents parent of the current node. + * + * ```js + * root.nodes[0].parent === root //=> true + * ``` + */ + parent: Container | Document | undefined + + /** + * It represents unnecessary whitespace and characters present + * in the css source code. + * + * Information to generate byte-to-byte equal node string as it was + * in the origin input. + * + * The properties of the raws object are decided by parser, + * the default parser uses the following properties: + * + * * `before`: the space symbols before the node. It also stores `*` + * and `_` symbols before the declaration (IE hack). + * * `after`: the space symbols after the last child of the node + * to the end of the node. + * * `between`: the symbols between the property and value + * for declarations, selector and `{` for rules, or last parameter + * and `{` for at-rules. + * * `semicolon`: contains true if the last child has + * an (optional) semicolon. + * * `afterName`: the space between the at-rule name and its parameters. + * * `left`: the space symbols between `/*` and the comment’s text. + * * `right`: the space symbols between the comment’s text + * and */. + * - `important`: the content of the important statement, + * if it is not just `!important`. + * + * PostCSS filters out the comments inside selectors, declaration values + * and at-rule parameters but it stores the origin content in raws. + * + * ```js + * const root = postcss.parse('a {\n color:black\n}') + * root.first.first.raws //=> { before: '\n ', between: ':' } + * ``` + */ + raws: any + + /** + * It represents information related to origin of a node and is required + * for generating source maps. + * + * The nodes that are created manually using the public APIs + * provided by PostCSS will have `source` undefined and + * will be absent in the source map. + * + * For this reason, the plugin developer should consider + * duplicating nodes as the duplicate node will have the + * same source as the original node by default or assign + * source to a node created manually. + * + * ```js + * decl.source.input.from //=> '/home/ai/source.css' + * decl.source.start //=> { line: 10, column: 2 } + * decl.source.end //=> { line: 10, column: 12 } + * ``` + * + * ```js + * // Incorrect method, source not specified! + * const prefixed = postcss.decl({ + * prop: '-moz-' + decl.prop, + * value: decl.value + * }) + * + * // Correct method, source is inherited when duplicating. + * const prefixed = decl.clone({ + * prop: '-moz-' + decl.prop + * }) + * ``` + * + * ```js + * if (atrule.name === 'add-link') { + * const rule = postcss.rule({ + * selector: 'a', + * source: atrule.source + * }) + * + * atrule.parent.insertBefore(atrule, rule) + * } + * ``` + */ + source?: Node.Source + + /** + * It represents type of a node in + * an abstract syntax tree. + * + * A type of node helps in identification of a node + * and perform operation based on it's type. + * + * ```js + * const declaration = new Declaration({ + * prop: 'color', + * value: 'black' + * }) + * + * declaration.type //=> 'decl' + * ``` + */ + type: string + + constructor(defaults?: object) + + /** + * If this node isn't already dirty, marks it and its ancestors as such. This + * indicates to the LazyResult processor that the {@link Root} has been + * modified by the current plugin and may need to be processed again by other + * plugins. + */ + protected markDirty(): void + + /** + * Insert new node after current node to current node’s parent. + * + * Just alias for `node.parent.insertAfter(node, add)`. + * + * ```js + * decl.after('color: black') + * ``` + * + * @param newNode New node. + * @return This node for methods chain. + */ + after( + newNode: Node | Node.ChildProps | readonly Node[] | string | undefined + ): this + + /** + * It assigns properties to an existing node instance. + * + * ```js + * decl.assign({ prop: 'word-wrap', value: 'break-word' }) + * ``` + * + * @param overrides New properties to override the node. + * + * @return `this` for method chaining. + */ + assign(overrides: object): this + + /** + * Insert new node before current node to current node’s parent. + * + * Just alias for `node.parent.insertBefore(node, add)`. + * + * ```js + * decl.before('content: ""') + * ``` + * + * @param newNode New node. + * @return This node for methods chain. + */ + before( + newNode: Node | Node.ChildProps | readonly Node[] | string | undefined + ): this + + /** + * Clear the code style properties for the node and its children. + * + * ```js + * node.raws.before //=> ' ' + * node.cleanRaws() + * node.raws.before //=> undefined + * ``` + * + * @param keepBetween Keep the `raws.between` symbols. + */ + cleanRaws(keepBetween?: boolean): void + + /** + * It creates clone of an existing node, which includes all the properties + * and their values, that includes `raws` but not `type`. + * + * ```js + * decl.raws.before //=> "\n " + * const cloned = decl.clone({ prop: '-moz-' + decl.prop }) + * cloned.raws.before //=> "\n " + * cloned.toString() //=> -moz-transform: scale(0) + * ``` + * + * @param overrides New properties to override in the clone. + * + * @return Duplicate of the node instance. + */ + clone(overrides?: object): this + + /** + * Shortcut to clone the node and insert the resulting cloned node + * after the current node. + * + * @param overrides New properties to override in the clone. + * @return New node. + */ + cloneAfter(overrides?: object): this + + /** + * Shortcut to clone the node and insert the resulting cloned node + * before the current node. + * + * ```js + * decl.cloneBefore({ prop: '-moz-' + decl.prop }) + * ``` + * + * @param overrides Mew properties to override in the clone. + * + * @return New node + */ + cloneBefore(overrides?: object): this + + /** + * It creates an instance of the class `CssSyntaxError` and parameters passed + * to this method are assigned to the error instance. + * + * The error instance will have description for the + * error, original position of the node in the + * source, showing line and column number. + * + * If any previous map is present, it would be used + * to get original position of the source. + * + * The Previous Map here is referred to the source map + * generated by previous compilation, example: Less, + * Stylus and Sass. + * + * This method returns the error instance instead of + * throwing it. + * + * ```js + * if (!variables[name]) { + * throw decl.error(`Unknown variable ${name}`, { word: name }) + * // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black + * // color: $black + * // a + * // ^ + * // background: white + * } + * ``` + * + * @param message Description for the error instance. + * @param options Options for the error instance. + * + * @return Error instance is returned. + */ + error(message: string, options?: Node.NodeErrorOptions): CssSyntaxError + + /** + * Returns the next child of the node’s parent. + * Returns `undefined` if the current node is the last child. + * + * ```js + * if (comment.text === 'delete next') { + * const next = comment.next() + * if (next) { + * next.remove() + * } + * } + * ``` + * + * @return Next node. + */ + next(): Node.ChildNode | undefined + + /** + * Get the position for a word or an index inside the node. + * + * @param opts Options. + * @return Position. + */ + positionBy(opts?: Pick): Node.Position + + /** + * Convert string index to line/column. + * + * @param index The symbol number in the node’s string. + * @return Symbol position in file. + */ + positionInside(index: number): Node.Position + + /** + * Returns the previous child of the node’s parent. + * Returns `undefined` if the current node is the first child. + * + * ```js + * const annotation = decl.prev() + * if (annotation.type === 'comment') { + * readAnnotation(annotation.text) + * } + * ``` + * + * @return Previous node. + */ + prev(): Node.ChildNode | undefined + + /** + * Get the range for a word or start and end index inside the node. + * The start index is inclusive; the end index is exclusive. + * + * @param opts Options. + * @return Range. + */ + rangeBy( + opts?: Pick + ): Node.Range + + /** + * Returns a `raws` value. If the node is missing + * the code style property (because the node was manually built or cloned), + * PostCSS will try to autodetect the code style property by looking + * at other nodes in the tree. + * + * ```js + * const root = postcss.parse('a { background: white }') + * root.nodes[0].append({ prop: 'color', value: 'black' }) + * root.nodes[0].nodes[1].raws.before //=> undefined + * root.nodes[0].nodes[1].raw('before') //=> ' ' + * ``` + * + * @param prop Name of code style property. + * @param defaultType Name of default value, it can be missed + * if the value is the same as prop. + * @return {string} Code style value. + */ + raw(prop: string, defaultType?: string): string + + /** + * It removes the node from its parent and deletes its parent property. + * + * ```js + * if (decl.prop.match(/^-webkit-/)) { + * decl.remove() + * } + * ``` + * + * @return `this` for method chaining. + */ + remove(): this + + /** + * Inserts node(s) before the current node and removes the current node. + * + * ```js + * AtRule: { + * mixin: atrule => { + * atrule.replaceWith(mixinRules[atrule.params]) + * } + * } + * ``` + * + * @param nodes Mode(s) to replace current one. + * @return Current node to methods chain. + */ + replaceWith(...nodes: NewChild[]): this + + /** + * Finds the Root instance of the node’s tree. + * + * ```js + * root.nodes[0].nodes[0].root() === root + * ``` + * + * @return Root parent. + */ + root(): Root + + /** + * Fix circular links on `JSON.stringify()`. + * + * @return Cleaned object. + */ + toJSON(): object + + /** + * It compiles the node to browser readable cascading style sheets string + * depending on it's type. + * + * ```js + * new Rule({ selector: 'a' }).toString() //=> "a {}" + * ``` + * + * @param stringifier A syntax to use in string generation. + * @return CSS string of this node. + */ + toString(stringifier?: Stringifier | Syntax): string + + /** + * It is a wrapper for {@link Result#warn}, providing convenient + * way of generating warnings. + * + * ```js + * Declaration: { + * bad: (decl, { result }) => { + * decl.warn(result, 'Deprecated property: bad') + * } + * } + * ``` + * + * @param result The `Result` instance that will receive the warning. + * @param message Description for the warning. + * @param options Options for the warning. + * + * @return `Warning` instance is returned + */ + warn(result: Result, message: string, options?: WarningOptions): Warning +} + +declare class Node extends Node_ {} + +export = Node diff --git a/node_modules/postcss/lib/node.js b/node_modules/postcss/lib/node.js new file mode 100644 index 0000000..88f382a --- /dev/null +++ b/node_modules/postcss/lib/node.js @@ -0,0 +1,389 @@ +'use strict' + +let CssSyntaxError = require('./css-syntax-error') +let Stringifier = require('./stringifier') +let stringify = require('./stringify') +let { isClean, my } = require('./symbols') + +function cloneNode(obj, parent) { + let cloned = new obj.constructor() + + for (let i in obj) { + if (!Object.prototype.hasOwnProperty.call(obj, i)) { + /* c8 ignore next 2 */ + continue + } + if (i === 'proxyCache') continue + let value = obj[i] + let type = typeof value + + if (i === 'parent' && type === 'object') { + if (parent) cloned[i] = parent + } else if (i === 'source') { + cloned[i] = value + } else if (Array.isArray(value)) { + cloned[i] = value.map(j => cloneNode(j, cloned)) + } else { + if (type === 'object' && value !== null) value = cloneNode(value) + cloned[i] = value + } + } + + return cloned +} + +class Node { + constructor(defaults = {}) { + this.raws = {} + this[isClean] = false + this[my] = true + + for (let name in defaults) { + if (name === 'nodes') { + this.nodes = [] + for (let node of defaults[name]) { + if (typeof node.clone === 'function') { + this.append(node.clone()) + } else { + this.append(node) + } + } + } else { + this[name] = defaults[name] + } + } + } + + addToError(error) { + error.postcssNode = this + if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) { + let s = this.source + error.stack = error.stack.replace( + /\n\s{4}at /, + `$&${s.input.from}:${s.start.line}:${s.start.column}$&` + ) + } + return error + } + + after(add) { + this.parent.insertAfter(this, add) + return this + } + + assign(overrides = {}) { + for (let name in overrides) { + this[name] = overrides[name] + } + return this + } + + before(add) { + this.parent.insertBefore(this, add) + return this + } + + cleanRaws(keepBetween) { + delete this.raws.before + delete this.raws.after + if (!keepBetween) delete this.raws.between + } + + clone(overrides = {}) { + let cloned = cloneNode(this) + for (let name in overrides) { + cloned[name] = overrides[name] + } + return cloned + } + + cloneAfter(overrides = {}) { + let cloned = this.clone(overrides) + this.parent.insertAfter(this, cloned) + return cloned + } + + cloneBefore(overrides = {}) { + let cloned = this.clone(overrides) + this.parent.insertBefore(this, cloned) + return cloned + } + + error(message, opts = {}) { + if (this.source) { + let { end, start } = this.rangeBy(opts) + return this.source.input.error( + message, + { column: start.column, line: start.line }, + { column: end.column, line: end.line }, + opts + ) + } + return new CssSyntaxError(message) + } + + getProxyProcessor() { + return { + get(node, prop) { + if (prop === 'proxyOf') { + return node + } else if (prop === 'root') { + return () => node.root().toProxy() + } else { + return node[prop] + } + }, + + set(node, prop, value) { + if (node[prop] === value) return true + node[prop] = value + if ( + prop === 'prop' || + prop === 'value' || + prop === 'name' || + prop === 'params' || + prop === 'important' || + /* c8 ignore next */ + prop === 'text' + ) { + node.markDirty() + } + return true + } + } + } + + /* c8 ignore next 3 */ + markClean() { + this[isClean] = true + } + + markDirty() { + if (this[isClean]) { + this[isClean] = false + let next = this + while ((next = next.parent)) { + next[isClean] = false + } + } + } + + next() { + if (!this.parent) return undefined + let index = this.parent.index(this) + return this.parent.nodes[index + 1] + } + + positionBy(opts, stringRepresentation) { + let pos = this.source.start + if (opts.index) { + pos = this.positionInside(opts.index, stringRepresentation) + } else if (opts.word) { + stringRepresentation = this.toString() + let index = stringRepresentation.indexOf(opts.word) + if (index !== -1) pos = this.positionInside(index, stringRepresentation) + } + return pos + } + + positionInside(index, stringRepresentation) { + let string = stringRepresentation || this.toString() + let column = this.source.start.column + let line = this.source.start.line + + for (let i = 0; i < index; i++) { + if (string[i] === '\n') { + column = 1 + line += 1 + } else { + column += 1 + } + } + + return { column, line } + } + + prev() { + if (!this.parent) return undefined + let index = this.parent.index(this) + return this.parent.nodes[index - 1] + } + + rangeBy(opts) { + let start = { + column: this.source.start.column, + line: this.source.start.line + } + let end = this.source.end + ? { + column: this.source.end.column + 1, + line: this.source.end.line + } + : { + column: start.column + 1, + line: start.line + } + + if (opts.word) { + let stringRepresentation = this.toString() + let index = stringRepresentation.indexOf(opts.word) + if (index !== -1) { + start = this.positionInside(index, stringRepresentation) + end = this.positionInside( + index + opts.word.length, + stringRepresentation + ) + } + } else { + if (opts.start) { + start = { + column: opts.start.column, + line: opts.start.line + } + } else if (opts.index) { + start = this.positionInside(opts.index) + } + + if (opts.end) { + end = { + column: opts.end.column, + line: opts.end.line + } + } else if (typeof opts.endIndex === 'number') { + end = this.positionInside(opts.endIndex) + } else if (opts.index) { + end = this.positionInside(opts.index + 1) + } + } + + if ( + end.line < start.line || + (end.line === start.line && end.column <= start.column) + ) { + end = { column: start.column + 1, line: start.line } + } + + return { end, start } + } + + raw(prop, defaultType) { + let str = new Stringifier() + return str.raw(this, prop, defaultType) + } + + remove() { + if (this.parent) { + this.parent.removeChild(this) + } + this.parent = undefined + return this + } + + replaceWith(...nodes) { + if (this.parent) { + let bookmark = this + let foundSelf = false + for (let node of nodes) { + if (node === this) { + foundSelf = true + } else if (foundSelf) { + this.parent.insertAfter(bookmark, node) + bookmark = node + } else { + this.parent.insertBefore(bookmark, node) + } + } + + if (!foundSelf) { + this.remove() + } + } + + return this + } + + root() { + let result = this + while (result.parent && result.parent.type !== 'document') { + result = result.parent + } + return result + } + + toJSON(_, inputs) { + let fixed = {} + let emitInputs = inputs == null + inputs = inputs || new Map() + let inputsNextIndex = 0 + + for (let name in this) { + if (!Object.prototype.hasOwnProperty.call(this, name)) { + /* c8 ignore next 2 */ + continue + } + if (name === 'parent' || name === 'proxyCache') continue + let value = this[name] + + if (Array.isArray(value)) { + fixed[name] = value.map(i => { + if (typeof i === 'object' && i.toJSON) { + return i.toJSON(null, inputs) + } else { + return i + } + }) + } else if (typeof value === 'object' && value.toJSON) { + fixed[name] = value.toJSON(null, inputs) + } else if (name === 'source') { + let inputId = inputs.get(value.input) + if (inputId == null) { + inputId = inputsNextIndex + inputs.set(value.input, inputsNextIndex) + inputsNextIndex++ + } + fixed[name] = { + end: value.end, + inputId, + start: value.start + } + } else { + fixed[name] = value + } + } + + if (emitInputs) { + fixed.inputs = [...inputs.keys()].map(input => input.toJSON()) + } + + return fixed + } + + toProxy() { + if (!this.proxyCache) { + this.proxyCache = new Proxy(this, this.getProxyProcessor()) + } + return this.proxyCache + } + + toString(stringifier = stringify) { + if (stringifier.stringify) stringifier = stringifier.stringify + let result = '' + stringifier(this, i => { + result += i + }) + return result + } + + warn(result, text, opts) { + let data = { node: this } + for (let i in opts) data[i] = opts[i] + return result.warn(text, data) + } + + get proxyOf() { + return this + } +} + +module.exports = Node +Node.default = Node diff --git a/node_modules/postcss/lib/parse.d.ts b/node_modules/postcss/lib/parse.d.ts new file mode 100644 index 0000000..4c943a4 --- /dev/null +++ b/node_modules/postcss/lib/parse.d.ts @@ -0,0 +1,9 @@ +import { Parser } from './postcss.js' + +interface Parse extends Parser { + default: Parse +} + +declare const parse: Parse + +export = parse diff --git a/node_modules/postcss/lib/parse.js b/node_modules/postcss/lib/parse.js new file mode 100644 index 0000000..00a1037 --- /dev/null +++ b/node_modules/postcss/lib/parse.js @@ -0,0 +1,42 @@ +'use strict' + +let Container = require('./container') +let Input = require('./input') +let Parser = require('./parser') + +function parse(css, opts) { + let input = new Input(css, opts) + let parser = new Parser(input) + try { + parser.parse() + } catch (e) { + if (process.env.NODE_ENV !== 'production') { + if (e.name === 'CssSyntaxError' && opts && opts.from) { + if (/\.scss$/i.test(opts.from)) { + e.message += + '\nYou tried to parse SCSS with ' + + 'the standard CSS parser; ' + + 'try again with the postcss-scss parser' + } else if (/\.sass/i.test(opts.from)) { + e.message += + '\nYou tried to parse Sass with ' + + 'the standard CSS parser; ' + + 'try again with the postcss-sass parser' + } else if (/\.less$/i.test(opts.from)) { + e.message += + '\nYou tried to parse Less with ' + + 'the standard CSS parser; ' + + 'try again with the postcss-less parser' + } + } + } + throw e + } + + return parser.root +} + +module.exports = parse +parse.default = parse + +Container.registerParse(parse) diff --git a/node_modules/postcss/lib/parser.js b/node_modules/postcss/lib/parser.js new file mode 100644 index 0000000..8a04411 --- /dev/null +++ b/node_modules/postcss/lib/parser.js @@ -0,0 +1,609 @@ +'use strict' + +let AtRule = require('./at-rule') +let Comment = require('./comment') +let Declaration = require('./declaration') +let Root = require('./root') +let Rule = require('./rule') +let tokenizer = require('./tokenize') + +const SAFE_COMMENT_NEIGHBOR = { + empty: true, + space: true +} + +function findLastWithPosition(tokens) { + for (let i = tokens.length - 1; i >= 0; i--) { + let token = tokens[i] + let pos = token[3] || token[2] + if (pos) return pos + } +} + +class Parser { + constructor(input) { + this.input = input + + this.root = new Root() + this.current = this.root + this.spaces = '' + this.semicolon = false + + this.createTokenizer() + this.root.source = { input, start: { column: 1, line: 1, offset: 0 } } + } + + atrule(token) { + let node = new AtRule() + node.name = token[1].slice(1) + if (node.name === '') { + this.unnamedAtrule(node, token) + } + this.init(node, token[2]) + + let type + let prev + let shift + let last = false + let open = false + let params = [] + let brackets = [] + + while (!this.tokenizer.endOfFile()) { + token = this.tokenizer.nextToken() + type = token[0] + + if (type === '(' || type === '[') { + brackets.push(type === '(' ? ')' : ']') + } else if (type === '{' && brackets.length > 0) { + brackets.push('}') + } else if (type === brackets[brackets.length - 1]) { + brackets.pop() + } + + if (brackets.length === 0) { + if (type === ';') { + node.source.end = this.getPosition(token[2]) + node.source.end.offset++ + this.semicolon = true + break + } else if (type === '{') { + open = true + break + } else if (type === '}') { + if (params.length > 0) { + shift = params.length - 1 + prev = params[shift] + while (prev && prev[0] === 'space') { + prev = params[--shift] + } + if (prev) { + node.source.end = this.getPosition(prev[3] || prev[2]) + node.source.end.offset++ + } + } + this.end(token) + break + } else { + params.push(token) + } + } else { + params.push(token) + } + + if (this.tokenizer.endOfFile()) { + last = true + break + } + } + + node.raws.between = this.spacesAndCommentsFromEnd(params) + if (params.length) { + node.raws.afterName = this.spacesAndCommentsFromStart(params) + this.raw(node, 'params', params) + if (last) { + token = params[params.length - 1] + node.source.end = this.getPosition(token[3] || token[2]) + node.source.end.offset++ + this.spaces = node.raws.between + node.raws.between = '' + } + } else { + node.raws.afterName = '' + node.params = '' + } + + if (open) { + node.nodes = [] + this.current = node + } + } + + checkMissedSemicolon(tokens) { + let colon = this.colon(tokens) + if (colon === false) return + + let founded = 0 + let token + for (let j = colon - 1; j >= 0; j--) { + token = tokens[j] + if (token[0] !== 'space') { + founded += 1 + if (founded === 2) break + } + } + // If the token is a word, e.g. `!important`, `red` or any other valid property's value. + // Then we need to return the colon after that word token. [3] is the "end" colon of that word. + // And because we need it after that one we do +1 to get the next one. + throw this.input.error( + 'Missed semicolon', + token[0] === 'word' ? token[3] + 1 : token[2] + ) + } + + colon(tokens) { + let brackets = 0 + let prev, token, type + for (let [i, element] of tokens.entries()) { + token = element + type = token[0] + + if (type === '(') { + brackets += 1 + } + if (type === ')') { + brackets -= 1 + } + if (brackets === 0 && type === ':') { + if (!prev) { + this.doubleColon(token) + } else if (prev[0] === 'word' && prev[1] === 'progid') { + continue + } else { + return i + } + } + + prev = token + } + return false + } + + comment(token) { + let node = new Comment() + this.init(node, token[2]) + node.source.end = this.getPosition(token[3] || token[2]) + node.source.end.offset++ + + let text = token[1].slice(2, -2) + if (/^\s*$/.test(text)) { + node.text = '' + node.raws.left = text + node.raws.right = '' + } else { + let match = text.match(/^(\s*)([^]*\S)(\s*)$/) + node.text = match[2] + node.raws.left = match[1] + node.raws.right = match[3] + } + } + + createTokenizer() { + this.tokenizer = tokenizer(this.input) + } + + decl(tokens, customProperty) { + let node = new Declaration() + this.init(node, tokens[0][2]) + + let last = tokens[tokens.length - 1] + if (last[0] === ';') { + this.semicolon = true + tokens.pop() + } + + node.source.end = this.getPosition( + last[3] || last[2] || findLastWithPosition(tokens) + ) + node.source.end.offset++ + + while (tokens[0][0] !== 'word') { + if (tokens.length === 1) this.unknownWord(tokens) + node.raws.before += tokens.shift()[1] + } + node.source.start = this.getPosition(tokens[0][2]) + + node.prop = '' + while (tokens.length) { + let type = tokens[0][0] + if (type === ':' || type === 'space' || type === 'comment') { + break + } + node.prop += tokens.shift()[1] + } + + node.raws.between = '' + + let token + while (tokens.length) { + token = tokens.shift() + + if (token[0] === ':') { + node.raws.between += token[1] + break + } else { + if (token[0] === 'word' && /\w/.test(token[1])) { + this.unknownWord([token]) + } + node.raws.between += token[1] + } + } + + if (node.prop[0] === '_' || node.prop[0] === '*') { + node.raws.before += node.prop[0] + node.prop = node.prop.slice(1) + } + + let firstSpaces = [] + let next + while (tokens.length) { + next = tokens[0][0] + if (next !== 'space' && next !== 'comment') break + firstSpaces.push(tokens.shift()) + } + + this.precheckMissedSemicolon(tokens) + + for (let i = tokens.length - 1; i >= 0; i--) { + token = tokens[i] + if (token[1].toLowerCase() === '!important') { + node.important = true + let string = this.stringFrom(tokens, i) + string = this.spacesFromEnd(tokens) + string + if (string !== ' !important') node.raws.important = string + break + } else if (token[1].toLowerCase() === 'important') { + let cache = tokens.slice(0) + let str = '' + for (let j = i; j > 0; j--) { + let type = cache[j][0] + if (str.trim().startsWith('!') && type !== 'space') { + break + } + str = cache.pop()[1] + str + } + if (str.trim().startsWith('!')) { + node.important = true + node.raws.important = str + tokens = cache + } + } + + if (token[0] !== 'space' && token[0] !== 'comment') { + break + } + } + + let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment') + + if (hasWord) { + node.raws.between += firstSpaces.map(i => i[1]).join('') + firstSpaces = [] + } + this.raw(node, 'value', firstSpaces.concat(tokens), customProperty) + + if (node.value.includes(':') && !customProperty) { + this.checkMissedSemicolon(tokens) + } + } + + doubleColon(token) { + throw this.input.error( + 'Double colon', + { offset: token[2] }, + { offset: token[2] + token[1].length } + ) + } + + emptyRule(token) { + let node = new Rule() + this.init(node, token[2]) + node.selector = '' + node.raws.between = '' + this.current = node + } + + end(token) { + if (this.current.nodes && this.current.nodes.length) { + this.current.raws.semicolon = this.semicolon + } + this.semicolon = false + + this.current.raws.after = (this.current.raws.after || '') + this.spaces + this.spaces = '' + + if (this.current.parent) { + this.current.source.end = this.getPosition(token[2]) + this.current.source.end.offset++ + this.current = this.current.parent + } else { + this.unexpectedClose(token) + } + } + + endFile() { + if (this.current.parent) this.unclosedBlock() + if (this.current.nodes && this.current.nodes.length) { + this.current.raws.semicolon = this.semicolon + } + this.current.raws.after = (this.current.raws.after || '') + this.spaces + this.root.source.end = this.getPosition(this.tokenizer.position()) + } + + freeSemicolon(token) { + this.spaces += token[1] + if (this.current.nodes) { + let prev = this.current.nodes[this.current.nodes.length - 1] + if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) { + prev.raws.ownSemicolon = this.spaces + this.spaces = '' + } + } + } + + // Helpers + + getPosition(offset) { + let pos = this.input.fromOffset(offset) + return { + column: pos.col, + line: pos.line, + offset + } + } + + init(node, offset) { + this.current.push(node) + node.source = { + input: this.input, + start: this.getPosition(offset) + } + node.raws.before = this.spaces + this.spaces = '' + if (node.type !== 'comment') this.semicolon = false + } + + other(start) { + let end = false + let type = null + let colon = false + let bracket = null + let brackets = [] + let customProperty = start[1].startsWith('--') + + let tokens = [] + let token = start + while (token) { + type = token[0] + tokens.push(token) + + if (type === '(' || type === '[') { + if (!bracket) bracket = token + brackets.push(type === '(' ? ')' : ']') + } else if (customProperty && colon && type === '{') { + if (!bracket) bracket = token + brackets.push('}') + } else if (brackets.length === 0) { + if (type === ';') { + if (colon) { + this.decl(tokens, customProperty) + return + } else { + break + } + } else if (type === '{') { + this.rule(tokens) + return + } else if (type === '}') { + this.tokenizer.back(tokens.pop()) + end = true + break + } else if (type === ':') { + colon = true + } + } else if (type === brackets[brackets.length - 1]) { + brackets.pop() + if (brackets.length === 0) bracket = null + } + + token = this.tokenizer.nextToken() + } + + if (this.tokenizer.endOfFile()) end = true + if (brackets.length > 0) this.unclosedBracket(bracket) + + if (end && colon) { + if (!customProperty) { + while (tokens.length) { + token = tokens[tokens.length - 1][0] + if (token !== 'space' && token !== 'comment') break + this.tokenizer.back(tokens.pop()) + } + } + this.decl(tokens, customProperty) + } else { + this.unknownWord(tokens) + } + } + + parse() { + let token + while (!this.tokenizer.endOfFile()) { + token = this.tokenizer.nextToken() + + switch (token[0]) { + case 'space': + this.spaces += token[1] + break + + case ';': + this.freeSemicolon(token) + break + + case '}': + this.end(token) + break + + case 'comment': + this.comment(token) + break + + case 'at-word': + this.atrule(token) + break + + case '{': + this.emptyRule(token) + break + + default: + this.other(token) + break + } + } + this.endFile() + } + + precheckMissedSemicolon(/* tokens */) { + // Hook for Safe Parser + } + + raw(node, prop, tokens, customProperty) { + let token, type + let length = tokens.length + let value = '' + let clean = true + let next, prev + + for (let i = 0; i < length; i += 1) { + token = tokens[i] + type = token[0] + if (type === 'space' && i === length - 1 && !customProperty) { + clean = false + } else if (type === 'comment') { + prev = tokens[i - 1] ? tokens[i - 1][0] : 'empty' + next = tokens[i + 1] ? tokens[i + 1][0] : 'empty' + if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) { + if (value.slice(-1) === ',') { + clean = false + } else { + value += token[1] + } + } else { + clean = false + } + } else { + value += token[1] + } + } + if (!clean) { + let raw = tokens.reduce((all, i) => all + i[1], '') + node.raws[prop] = { raw, value } + } + node[prop] = value + } + + rule(tokens) { + tokens.pop() + + let node = new Rule() + this.init(node, tokens[0][2]) + + node.raws.between = this.spacesAndCommentsFromEnd(tokens) + this.raw(node, 'selector', tokens) + this.current = node + } + + spacesAndCommentsFromEnd(tokens) { + let lastTokenType + let spaces = '' + while (tokens.length) { + lastTokenType = tokens[tokens.length - 1][0] + if (lastTokenType !== 'space' && lastTokenType !== 'comment') break + spaces = tokens.pop()[1] + spaces + } + return spaces + } + + // Errors + + spacesAndCommentsFromStart(tokens) { + let next + let spaces = '' + while (tokens.length) { + next = tokens[0][0] + if (next !== 'space' && next !== 'comment') break + spaces += tokens.shift()[1] + } + return spaces + } + + spacesFromEnd(tokens) { + let lastTokenType + let spaces = '' + while (tokens.length) { + lastTokenType = tokens[tokens.length - 1][0] + if (lastTokenType !== 'space') break + spaces = tokens.pop()[1] + spaces + } + return spaces + } + + stringFrom(tokens, from) { + let result = '' + for (let i = from; i < tokens.length; i++) { + result += tokens[i][1] + } + tokens.splice(from, tokens.length - from) + return result + } + + unclosedBlock() { + let pos = this.current.source.start + throw this.input.error('Unclosed block', pos.line, pos.column) + } + + unclosedBracket(bracket) { + throw this.input.error( + 'Unclosed bracket', + { offset: bracket[2] }, + { offset: bracket[2] + 1 } + ) + } + + unexpectedClose(token) { + throw this.input.error( + 'Unexpected }', + { offset: token[2] }, + { offset: token[2] + 1 } + ) + } + + unknownWord(tokens) { + throw this.input.error( + 'Unknown word', + { offset: tokens[0][2] }, + { offset: tokens[0][2] + tokens[0][1].length } + ) + } + + unnamedAtrule(node, token) { + throw this.input.error( + 'At-rule without name', + { offset: token[2] }, + { offset: token[2] + token[1].length } + ) + } +} + +module.exports = Parser diff --git a/node_modules/postcss/lib/postcss.d.mts b/node_modules/postcss/lib/postcss.d.mts new file mode 100644 index 0000000..4cf5b49 --- /dev/null +++ b/node_modules/postcss/lib/postcss.d.mts @@ -0,0 +1,69 @@ +export { + // postcss function / namespace + default, + + // Value exports from postcss.mjs + stringify, + fromJSON, + // @ts-expect-error This value exists, but it’s untyped. + plugin, + parse, + list, + document, + comment, + atRule, + rule, + decl, + root, + CssSyntaxError, + Declaration, + Container, + Processor, + Document, + Comment, + Warning, + AtRule, + Result, + Input, + Rule, + Root, + Node, + + // Type-only exports + AcceptedPlugin, + AnyNode, + AtRuleProps, + Builder, + ChildNode, + ChildProps, + CommentProps, + ContainerProps, + DeclarationProps, + DocumentProps, + FilePosition, + Helpers, + JSONHydrator, + Message, + NodeErrorOptions, + NodeProps, + OldPlugin, + Parser, + Plugin, + PluginCreator, + Position, + Postcss, + ProcessOptions, + RootProps, + RuleProps, + Source, + SourceMap, + SourceMapOptions, + Stringifier, + Syntax, + TransformCallback, + Transformer, + WarningOptions, + + // This is a class, but it’s not re-exported. That’s why it’s exported as type-only here. + type LazyResult +} from './postcss.js' diff --git a/node_modules/postcss/lib/postcss.d.ts b/node_modules/postcss/lib/postcss.d.ts new file mode 100644 index 0000000..d0b8b53 --- /dev/null +++ b/node_modules/postcss/lib/postcss.d.ts @@ -0,0 +1,453 @@ +import { RawSourceMap, SourceMapGenerator } from 'source-map-js' + +import AtRule, { AtRuleProps } from './at-rule.js' +import Comment, { CommentProps } from './comment.js' +import Container, { ContainerProps, NewChild } from './container.js' +import CssSyntaxError from './css-syntax-error.js' +import Declaration, { DeclarationProps } from './declaration.js' +import Document, { DocumentProps } from './document.js' +import Input, { FilePosition } from './input.js' +import LazyResult from './lazy-result.js' +import list from './list.js' +import Node, { + AnyNode, + ChildNode, + ChildProps, + NodeErrorOptions, + NodeProps, + Position, + Source +} from './node.js' +import Processor from './processor.js' +import Result, { Message } from './result.js' +import Root, { RootProps } from './root.js' +import Rule, { RuleProps } from './rule.js' +import Warning, { WarningOptions } from './warning.js' + +type DocumentProcessor = ( + document: Document, + helper: postcss.Helpers +) => Promise | void +type RootProcessor = ( + root: Root, + helper: postcss.Helpers +) => Promise | void +type DeclarationProcessor = ( + decl: Declaration, + helper: postcss.Helpers +) => Promise | void +type RuleProcessor = ( + rule: Rule, + helper: postcss.Helpers +) => Promise | void +type AtRuleProcessor = ( + atRule: AtRule, + helper: postcss.Helpers +) => Promise | void +type CommentProcessor = ( + comment: Comment, + helper: postcss.Helpers +) => Promise | void + +interface Processors { + /** + * Will be called on all`AtRule` nodes. + * + * Will be called again on node or children changes. + */ + AtRule?: { [name: string]: AtRuleProcessor } | AtRuleProcessor + + /** + * Will be called on all `AtRule` nodes, when all children will be processed. + * + * Will be called again on node or children changes. + */ + AtRuleExit?: { [name: string]: AtRuleProcessor } | AtRuleProcessor + + /** + * Will be called on all `Comment` nodes. + * + * Will be called again on node or children changes. + */ + Comment?: CommentProcessor + + /** + * Will be called on all `Comment` nodes after listeners + * for `Comment` event. + * + * Will be called again on node or children changes. + */ + CommentExit?: CommentProcessor + + /** + * Will be called on all `Declaration` nodes after listeners + * for `Declaration` event. + * + * Will be called again on node or children changes. + */ + Declaration?: { [prop: string]: DeclarationProcessor } | DeclarationProcessor + + /** + * Will be called on all `Declaration` nodes. + * + * Will be called again on node or children changes. + */ + DeclarationExit?: + | { [prop: string]: DeclarationProcessor } + | DeclarationProcessor + + /** + * Will be called on `Document` node. + * + * Will be called again on children changes. + */ + Document?: DocumentProcessor + + /** + * Will be called on `Document` node, when all children will be processed. + * + * Will be called again on children changes. + */ + DocumentExit?: DocumentProcessor + + /** + * Will be called on `Root` node once. + */ + Once?: RootProcessor + + /** + * Will be called on `Root` node once, when all children will be processed. + */ + OnceExit?: RootProcessor + + /** + * Will be called on `Root` node. + * + * Will be called again on children changes. + */ + Root?: RootProcessor + + /** + * Will be called on `Root` node, when all children will be processed. + * + * Will be called again on children changes. + */ + RootExit?: RootProcessor + + /** + * Will be called on all `Rule` nodes. + * + * Will be called again on node or children changes. + */ + Rule?: RuleProcessor + + /** + * Will be called on all `Rule` nodes, when all children will be processed. + * + * Will be called again on node or children changes. + */ + RuleExit?: RuleProcessor +} + +declare namespace postcss { + export { + AnyNode, + AtRule, + AtRuleProps, + ChildNode, + ChildProps, + Comment, + CommentProps, + Container, + ContainerProps, + CssSyntaxError, + Declaration, + DeclarationProps, + Document, + DocumentProps, + FilePosition, + Input, + LazyResult, + list, + Message, + NewChild, + Node, + NodeErrorOptions, + NodeProps, + Position, + Processor, + Result, + Root, + RootProps, + Rule, + RuleProps, + Source, + Warning, + WarningOptions + } + + export type SourceMap = { + toJSON(): RawSourceMap + } & SourceMapGenerator + + export type Helpers = { postcss: Postcss; result: Result } & Postcss + + export interface Plugin extends Processors { + postcssPlugin: string + prepare?: (result: Result) => Processors + } + + export interface PluginCreator { + (opts?: PluginOptions): Plugin | Processor + postcss: true + } + + export interface Transformer extends TransformCallback { + postcssPlugin: string + postcssVersion: string + } + + export interface TransformCallback { + (root: Root, result: Result): Promise | void + } + + export interface OldPlugin extends Transformer { + (opts?: T): Transformer + postcss: Transformer + } + + export type AcceptedPlugin = + | { + postcss: Processor | TransformCallback + } + | OldPlugin + | Plugin + | PluginCreator + | Processor + | TransformCallback + + export interface Parser { + ( + css: { toString(): string } | string, + opts?: Pick + ): RootNode + } + + export interface Builder { + (part: string, node?: AnyNode, type?: 'end' | 'start'): void + } + + export interface Stringifier { + (node: AnyNode, builder: Builder): void + } + + export interface JSONHydrator { + (data: object): Node + (data: object[]): Node[] + } + + export interface Syntax { + /** + * Function to generate AST by string. + */ + parse?: Parser + + /** + * Class to generate string by AST. + */ + stringify?: Stringifier + } + + export interface SourceMapOptions { + /** + * Use absolute path in generated source map. + */ + absolute?: boolean + + /** + * Indicates that PostCSS should add annotation comments to the CSS. + * By default, PostCSS will always add a comment with a path + * to the source map. PostCSS will not add annotations to CSS files + * that do not contain any comments. + * + * By default, PostCSS presumes that you want to save the source map as + * `opts.to + '.map'` and will use this path in the annotation comment. + * A different path can be set by providing a string value for annotation. + * + * If you have set `inline: true`, annotation cannot be disabled. + */ + annotation?: ((file: string, root: Root) => string) | boolean | string + + /** + * Override `from` in map’s sources. + */ + from?: string + + /** + * Indicates that the source map should be embedded in the output CSS + * as a Base64-encoded comment. By default, it is `true`. + * But if all previous maps are external, not inline, PostCSS will not embed + * the map even if you do not set this option. + * + * If you have an inline source map, the result.map property will be empty, + * as the source map will be contained within the text of `result.css`. + */ + inline?: boolean + + /** + * Source map content from a previous processing step (e.g., Sass). + * + * PostCSS will try to read the previous source map + * automatically (based on comments within the source CSS), but you can use + * this option to identify it manually. + * + * If desired, you can omit the previous map with prev: `false`. + */ + prev?: ((file: string) => string) | boolean | object | string + + /** + * Indicates that PostCSS should set the origin content (e.g., Sass source) + * of the source map. By default, it is true. But if all previous maps do not + * contain sources content, PostCSS will also leave it out even if you + * do not set this option. + */ + sourcesContent?: boolean + } + + export interface ProcessOptions { + /** + * The path of the CSS source file. You should always set `from`, + * because it is used in source map generation and syntax error messages. + */ + from?: string | undefined + + /** + * Source map options + */ + map?: boolean | SourceMapOptions + + /** + * Function to generate AST by string. + */ + parser?: Parser | Syntax + + /** + * Class to generate string by AST. + */ + stringifier?: Stringifier | Syntax + + /** + * Object with parse and stringify. + */ + syntax?: Syntax + + /** + * The path where you'll put the output CSS file. You should always set `to` + * to generate correct source maps. + */ + to?: string + } + + export type Postcss = typeof postcss + + /** + * Default function to convert a node tree into a CSS string. + */ + export let stringify: Stringifier + + /** + * Parses source css and returns a new `Root` or `Document` node, + * which contains the source CSS nodes. + * + * ```js + * // Simple CSS concatenation with source map support + * const root1 = postcss.parse(css1, { from: file1 }) + * const root2 = postcss.parse(css2, { from: file2 }) + * root1.append(root2).toResult().css + * ``` + */ + export let parse: Parser + + /** + * Rehydrate a JSON AST (from `Node#toJSON`) back into the AST classes. + * + * ```js + * const json = root.toJSON() + * // save to file, send by network, etc + * const root2 = postcss.fromJSON(json) + * ``` + */ + export let fromJSON: JSONHydrator + + /** + * Creates a new `Comment` node. + * + * @param defaults Properties for the new node. + * @return New comment node + */ + export function comment(defaults?: CommentProps): Comment + + /** + * Creates a new `AtRule` node. + * + * @param defaults Properties for the new node. + * @return New at-rule node. + */ + export function atRule(defaults?: AtRuleProps): AtRule + + /** + * Creates a new `Declaration` node. + * + * @param defaults Properties for the new node. + * @return New declaration node. + */ + export function decl(defaults?: DeclarationProps): Declaration + + /** + * Creates a new `Rule` node. + * + * @param default Properties for the new node. + * @return New rule node. + */ + export function rule(defaults?: RuleProps): Rule + + /** + * Creates a new `Root` node. + * + * @param defaults Properties for the new node. + * @return New root node. + */ + export function root(defaults?: RootProps): Root + + /** + * Creates a new `Document` node. + * + * @param defaults Properties for the new node. + * @return New document node. + */ + export function document(defaults?: DocumentProps): Document + + export { postcss as default } +} + +/** + * Create a new `Processor` instance that will apply `plugins` + * as CSS processors. + * + * ```js + * let postcss = require('postcss') + * + * postcss(plugins).process(css, { from, to }).then(result => { + * console.log(result.css) + * }) + * ``` + * + * @param plugins PostCSS plugins. + * @return Processor to process multiple CSS. + */ +declare function postcss( + plugins?: readonly postcss.AcceptedPlugin[] +): Processor +declare function postcss(...plugins: postcss.AcceptedPlugin[]): Processor + +export = postcss diff --git a/node_modules/postcss/lib/postcss.js b/node_modules/postcss/lib/postcss.js new file mode 100644 index 0000000..8f0773b --- /dev/null +++ b/node_modules/postcss/lib/postcss.js @@ -0,0 +1,101 @@ +'use strict' + +let AtRule = require('./at-rule') +let Comment = require('./comment') +let Container = require('./container') +let CssSyntaxError = require('./css-syntax-error') +let Declaration = require('./declaration') +let Document = require('./document') +let fromJSON = require('./fromJSON') +let Input = require('./input') +let LazyResult = require('./lazy-result') +let list = require('./list') +let Node = require('./node') +let parse = require('./parse') +let Processor = require('./processor') +let Result = require('./result.js') +let Root = require('./root') +let Rule = require('./rule') +let stringify = require('./stringify') +let Warning = require('./warning') + +function postcss(...plugins) { + if (plugins.length === 1 && Array.isArray(plugins[0])) { + plugins = plugins[0] + } + return new Processor(plugins) +} + +postcss.plugin = function plugin(name, initializer) { + let warningPrinted = false + function creator(...args) { + // eslint-disable-next-line no-console + if (console && console.warn && !warningPrinted) { + warningPrinted = true + // eslint-disable-next-line no-console + console.warn( + name + + ': postcss.plugin was deprecated. Migration guide:\n' + + 'https://evilmartians.com/chronicles/postcss-8-plugin-migration' + ) + if (process.env.LANG && process.env.LANG.startsWith('cn')) { + /* c8 ignore next 7 */ + // eslint-disable-next-line no-console + console.warn( + name + + ': 里面 postcss.plugin 被弃用. 迁移指南:\n' + + 'https://www.w3ctech.com/topic/2226' + ) + } + } + let transformer = initializer(...args) + transformer.postcssPlugin = name + transformer.postcssVersion = new Processor().version + return transformer + } + + let cache + Object.defineProperty(creator, 'postcss', { + get() { + if (!cache) cache = creator() + return cache + } + }) + + creator.process = function (css, processOpts, pluginOpts) { + return postcss([creator(pluginOpts)]).process(css, processOpts) + } + + return creator +} + +postcss.stringify = stringify +postcss.parse = parse +postcss.fromJSON = fromJSON +postcss.list = list + +postcss.comment = defaults => new Comment(defaults) +postcss.atRule = defaults => new AtRule(defaults) +postcss.decl = defaults => new Declaration(defaults) +postcss.rule = defaults => new Rule(defaults) +postcss.root = defaults => new Root(defaults) +postcss.document = defaults => new Document(defaults) + +postcss.CssSyntaxError = CssSyntaxError +postcss.Declaration = Declaration +postcss.Container = Container +postcss.Processor = Processor +postcss.Document = Document +postcss.Comment = Comment +postcss.Warning = Warning +postcss.AtRule = AtRule +postcss.Result = Result +postcss.Input = Input +postcss.Rule = Rule +postcss.Root = Root +postcss.Node = Node + +LazyResult.registerPostcss(postcss) + +module.exports = postcss +postcss.default = postcss diff --git a/node_modules/postcss/lib/postcss.mjs b/node_modules/postcss/lib/postcss.mjs new file mode 100644 index 0000000..3507598 --- /dev/null +++ b/node_modules/postcss/lib/postcss.mjs @@ -0,0 +1,30 @@ +import postcss from './postcss.js' + +export default postcss + +export const stringify = postcss.stringify +export const fromJSON = postcss.fromJSON +export const plugin = postcss.plugin +export const parse = postcss.parse +export const list = postcss.list + +export const document = postcss.document +export const comment = postcss.comment +export const atRule = postcss.atRule +export const rule = postcss.rule +export const decl = postcss.decl +export const root = postcss.root + +export const CssSyntaxError = postcss.CssSyntaxError +export const Declaration = postcss.Declaration +export const Container = postcss.Container +export const Processor = postcss.Processor +export const Document = postcss.Document +export const Comment = postcss.Comment +export const Warning = postcss.Warning +export const AtRule = postcss.AtRule +export const Result = postcss.Result +export const Input = postcss.Input +export const Rule = postcss.Rule +export const Root = postcss.Root +export const Node = postcss.Node diff --git a/node_modules/postcss/lib/previous-map.d.ts b/node_modules/postcss/lib/previous-map.d.ts new file mode 100644 index 0000000..23edeb5 --- /dev/null +++ b/node_modules/postcss/lib/previous-map.d.ts @@ -0,0 +1,81 @@ +import { SourceMapConsumer } from 'source-map-js' + +import { ProcessOptions } from './postcss.js' + +declare namespace PreviousMap { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { PreviousMap_ as default } +} + +/** + * Source map information from input CSS. + * For example, source map after Sass compiler. + * + * This class will automatically find source map in input CSS or in file system + * near input file (according `from` option). + * + * ```js + * const root = parse(css, { from: 'a.sass.css' }) + * root.input.map //=> PreviousMap + * ``` + */ +declare class PreviousMap_ { + /** + * `sourceMappingURL` content. + */ + annotation?: string + + /** + * The CSS source identifier. Contains `Input#file` if the user + * set the `from` option, or `Input#id` if they did not. + */ + file?: string + + /** + * Was source map inlined by data-uri to input CSS. + */ + inline: boolean + + /** + * Path to source map file. + */ + mapFile?: string + + /** + * The directory with source map file, if source map is in separated file. + */ + root?: string + + /** + * Source map file content. + */ + text?: string + + /** + * @param css Input CSS source. + * @param opts Process options. + */ + constructor(css: string, opts?: ProcessOptions) + + /** + * Create a instance of `SourceMapGenerator` class + * from the `source-map` library to work with source map information. + * + * It is lazy method, so it will create object only on first call + * and then it will use cache. + * + * @return Object with source map information. + */ + consumer(): SourceMapConsumer + + /** + * Does source map contains `sourcesContent` with input source text. + * + * @return Is `sourcesContent` present. + */ + withContent(): boolean +} + +declare class PreviousMap extends PreviousMap_ {} + +export = PreviousMap diff --git a/node_modules/postcss/lib/previous-map.js b/node_modules/postcss/lib/previous-map.js new file mode 100644 index 0000000..b123dcd --- /dev/null +++ b/node_modules/postcss/lib/previous-map.js @@ -0,0 +1,144 @@ +'use strict' + +let { existsSync, readFileSync } = require('fs') +let { dirname, join } = require('path') +let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js') + +function fromBase64(str) { + if (Buffer) { + return Buffer.from(str, 'base64').toString() + } else { + /* c8 ignore next 2 */ + return window.atob(str) + } +} + +class PreviousMap { + constructor(css, opts) { + if (opts.map === false) return + this.loadAnnotation(css) + this.inline = this.startWith(this.annotation, 'data:') + + let prev = opts.map ? opts.map.prev : undefined + let text = this.loadMap(opts.from, prev) + if (!this.mapFile && opts.from) { + this.mapFile = opts.from + } + if (this.mapFile) this.root = dirname(this.mapFile) + if (text) this.text = text + } + + consumer() { + if (!this.consumerCache) { + this.consumerCache = new SourceMapConsumer(this.text) + } + return this.consumerCache + } + + decodeInline(text) { + let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/ + let baseUri = /^data:application\/json;base64,/ + let charsetUri = /^data:application\/json;charset=utf-?8,/ + let uri = /^data:application\/json,/ + + let uriMatch = text.match(charsetUri) || text.match(uri) + if (uriMatch) { + return decodeURIComponent(text.substr(uriMatch[0].length)) + } + + let baseUriMatch = text.match(baseCharsetUri) || text.match(baseUri) + if (baseUriMatch) { + return fromBase64(text.substr(baseUriMatch[0].length)) + } + + let encoding = text.match(/data:application\/json;([^,]+),/)[1] + throw new Error('Unsupported source map encoding ' + encoding) + } + + getAnnotationURL(sourceMapString) { + return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, '').trim() + } + + isMap(map) { + if (typeof map !== 'object') return false + return ( + typeof map.mappings === 'string' || + typeof map._mappings === 'string' || + Array.isArray(map.sections) + ) + } + + loadAnnotation(css) { + let comments = css.match(/\/\*\s*# sourceMappingURL=/g) + if (!comments) return + + // sourceMappingURLs from comments, strings, etc. + let start = css.lastIndexOf(comments.pop()) + let end = css.indexOf('*/', start) + + if (start > -1 && end > -1) { + // Locate the last sourceMappingURL to avoid pickin + this.annotation = this.getAnnotationURL(css.substring(start, end)) + } + } + + loadFile(path) { + this.root = dirname(path) + if (existsSync(path)) { + this.mapFile = path + return readFileSync(path, 'utf-8').toString().trim() + } + } + + loadMap(file, prev) { + if (prev === false) return false + + if (prev) { + if (typeof prev === 'string') { + return prev + } else if (typeof prev === 'function') { + let prevPath = prev(file) + if (prevPath) { + let map = this.loadFile(prevPath) + if (!map) { + throw new Error( + 'Unable to load previous source map: ' + prevPath.toString() + ) + } + return map + } + } else if (prev instanceof SourceMapConsumer) { + return SourceMapGenerator.fromSourceMap(prev).toString() + } else if (prev instanceof SourceMapGenerator) { + return prev.toString() + } else if (this.isMap(prev)) { + return JSON.stringify(prev) + } else { + throw new Error( + 'Unsupported previous source map format: ' + prev.toString() + ) + } + } else if (this.inline) { + return this.decodeInline(this.annotation) + } else if (this.annotation) { + let map = this.annotation + if (file) map = join(dirname(file), map) + return this.loadFile(map) + } + } + + startWith(string, start) { + if (!string) return false + return string.substr(0, start.length) === start + } + + withContent() { + return !!( + this.consumer().sourcesContent && + this.consumer().sourcesContent.length > 0 + ) + } +} + +module.exports = PreviousMap +PreviousMap.default = PreviousMap diff --git a/node_modules/postcss/lib/processor.d.ts b/node_modules/postcss/lib/processor.d.ts new file mode 100644 index 0000000..aa2942c --- /dev/null +++ b/node_modules/postcss/lib/processor.d.ts @@ -0,0 +1,115 @@ +import Document from './document.js' +import LazyResult from './lazy-result.js' +import NoWorkResult from './no-work-result.js' +import { + AcceptedPlugin, + Plugin, + ProcessOptions, + TransformCallback, + Transformer +} from './postcss.js' +import Result from './result.js' +import Root from './root.js' + +declare namespace Processor { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { Processor_ as default } +} + +/** + * Contains plugins to process CSS. Create one `Processor` instance, + * initialize its plugins, and then use that instance on numerous CSS files. + * + * ```js + * const processor = postcss([autoprefixer, postcssNested]) + * processor.process(css1).then(result => console.log(result.css)) + * processor.process(css2).then(result => console.log(result.css)) + * ``` + */ +declare class Processor_ { + /** + * Plugins added to this processor. + * + * ```js + * const processor = postcss([autoprefixer, postcssNested]) + * processor.plugins.length //=> 2 + * ``` + */ + plugins: (Plugin | TransformCallback | Transformer)[] + + /** + * Current PostCSS version. + * + * ```js + * if (result.processor.version.split('.')[0] !== '6') { + * throw new Error('This plugin works only with PostCSS 6') + * } + * ``` + */ + version: string + + /** + * @param plugins PostCSS plugins + */ + constructor(plugins?: readonly AcceptedPlugin[]) + + /** + * Parses source CSS and returns a `LazyResult` Promise proxy. + * Because some plugins can be asynchronous it doesn’t make + * any transformations. Transformations will be applied + * in the `LazyResult` methods. + * + * ```js + * processor.process(css, { from: 'a.css', to: 'a.out.css' }) + * .then(result => { + * console.log(result.css) + * }) + * ``` + * + * @param css String with input CSS or any object with a `toString()` method, + * like a Buffer. Optionally, send a `Result` instance + * and the processor will take the `Root` from it. + * @param opts Options. + * @return Promise proxy. + */ + process( + css: { toString(): string } | LazyResult | Result | Root | string + ): LazyResult | NoWorkResult + process( + css: { toString(): string } | LazyResult | Result | Root | string, + options: ProcessOptions + ): LazyResult + + /** + * Adds a plugin to be used as a CSS processor. + * + * PostCSS plugin can be in 4 formats: + * * A plugin in `Plugin` format. + * * A plugin creator function with `pluginCreator.postcss = true`. + * PostCSS will call this function without argument to get plugin. + * * A function. PostCSS will pass the function a {@link Root} + * as the first argument and current `Result` instance + * as the second. + * * Another `Processor` instance. PostCSS will copy plugins + * from that instance into this one. + * + * Plugins can also be added by passing them as arguments when creating + * a `postcss` instance (see [`postcss(plugins)`]). + * + * Asynchronous plugins should return a `Promise` instance. + * + * ```js + * const processor = postcss() + * .use(autoprefixer) + * .use(postcssNested) + * ``` + * + * @param plugin PostCSS plugin or `Processor` with plugins. + * @return Current processor to make methods chain. + */ + use(plugin: AcceptedPlugin): this +} + +declare class Processor extends Processor_ {} + +export = Processor diff --git a/node_modules/postcss/lib/processor.js b/node_modules/postcss/lib/processor.js new file mode 100644 index 0000000..729f725 --- /dev/null +++ b/node_modules/postcss/lib/processor.js @@ -0,0 +1,67 @@ +'use strict' + +let Document = require('./document') +let LazyResult = require('./lazy-result') +let NoWorkResult = require('./no-work-result') +let Root = require('./root') + +class Processor { + constructor(plugins = []) { + this.version = '8.4.47' + this.plugins = this.normalize(plugins) + } + + normalize(plugins) { + let normalized = [] + for (let i of plugins) { + if (i.postcss === true) { + i = i() + } else if (i.postcss) { + i = i.postcss + } + + if (typeof i === 'object' && Array.isArray(i.plugins)) { + normalized = normalized.concat(i.plugins) + } else if (typeof i === 'object' && i.postcssPlugin) { + normalized.push(i) + } else if (typeof i === 'function') { + normalized.push(i) + } else if (typeof i === 'object' && (i.parse || i.stringify)) { + if (process.env.NODE_ENV !== 'production') { + throw new Error( + 'PostCSS syntaxes cannot be used as plugins. Instead, please use ' + + 'one of the syntax/parser/stringifier options as outlined ' + + 'in your PostCSS runner documentation.' + ) + } + } else { + throw new Error(i + ' is not a PostCSS plugin') + } + } + return normalized + } + + process(css, opts = {}) { + if ( + !this.plugins.length && + !opts.parser && + !opts.stringifier && + !opts.syntax + ) { + return new NoWorkResult(this, css, opts) + } else { + return new LazyResult(this, css, opts) + } + } + + use(plugin) { + this.plugins = this.plugins.concat(this.normalize([plugin])) + return this + } +} + +module.exports = Processor +Processor.default = Processor + +Root.registerProcessor(Processor) +Document.registerProcessor(Processor) diff --git a/node_modules/postcss/lib/result.d.ts b/node_modules/postcss/lib/result.d.ts new file mode 100644 index 0000000..40e086f --- /dev/null +++ b/node_modules/postcss/lib/result.d.ts @@ -0,0 +1,205 @@ +import { + Document, + Node, + Plugin, + ProcessOptions, + Root, + SourceMap, + TransformCallback, + Warning, + WarningOptions +} from './postcss.js' +import Processor from './processor.js' + +declare namespace Result { + export interface Message { + [others: string]: any + + /** + * Source PostCSS plugin name. + */ + plugin?: string + + /** + * Message type. + */ + type: string + } + + export interface ResultOptions extends ProcessOptions { + /** + * The CSS node that was the source of the warning. + */ + node?: Node + + /** + * Name of plugin that created this warning. `Result#warn` will fill it + * automatically with `Plugin#postcssPlugin` value. + */ + plugin?: string + } + + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { Result_ as default } +} + +/** + * Provides the result of the PostCSS transformations. + * + * A Result instance is returned by `LazyResult#then` + * or `Root#toResult` methods. + * + * ```js + * postcss([autoprefixer]).process(css).then(result => { + * console.log(result.css) + * }) + * ``` + * + * ```js + * const result2 = postcss.parse(css).toResult() + * ``` + */ +declare class Result_ { + /** + * A CSS string representing of `Result#root`. + * + * ```js + * postcss.parse('a{}').toResult().css //=> "a{}" + * ``` + */ + css: string + + /** + * Last runned PostCSS plugin. + */ + lastPlugin: Plugin | TransformCallback + + /** + * An instance of `SourceMapGenerator` class from the `source-map` library, + * representing changes to the `Result#root` instance. + * + * ```js + * result.map.toJSON() //=> { version: 3, file: 'a.css', … } + * ``` + * + * ```js + * if (result.map) { + * fs.writeFileSync(result.opts.to + '.map', result.map.toString()) + * } + * ``` + */ + map: SourceMap + + /** + * Contains messages from plugins (e.g., warnings or custom messages). + * Each message should have type and plugin properties. + * + * ```js + * AtRule: { + * import: (atRule, { result }) { + * const importedFile = parseImport(atRule) + * result.messages.push({ + * type: 'dependency', + * plugin: 'postcss-import', + * file: importedFile, + * parent: result.opts.from + * }) + * } + * } + * ``` + */ + messages: Result.Message[] + + /** + * Options from the `Processor#process` or `Root#toResult` call + * that produced this Result instance.] + * + * ```js + * root.toResult(opts).opts === opts + * ``` + */ + opts: Result.ResultOptions + + /** + * The Processor instance used for this transformation. + * + * ```js + * for (const plugin of result.processor.plugins) { + * if (plugin.postcssPlugin === 'postcss-bad') { + * throw 'postcss-good is incompatible with postcss-bad' + * } + * }) + * ``` + */ + processor: Processor + + /** + * Root node after all transformations. + * + * ```js + * root.toResult().root === root + * ``` + */ + root: RootNode + + /** + * @param processor Processor used for this transformation. + * @param root Root node after all transformations. + * @param opts Options from the `Processor#process` or `Root#toResult`. + */ + constructor(processor: Processor, root: RootNode, opts: Result.ResultOptions) + + /** + * Returns for `Result#css` content. + * + * ```js + * result + '' === result.css + * ``` + * + * @return String representing of `Result#root`. + */ + toString(): string + + /** + * Creates an instance of `Warning` and adds it to `Result#messages`. + * + * ```js + * if (decl.important) { + * result.warn('Avoid !important', { node: decl, word: '!important' }) + * } + * ``` + * + * @param text Warning message. + * @param opts Warning options. + * @return Created warning. + */ + warn(message: string, options?: WarningOptions): Warning + + /** + * Returns warnings from plugins. Filters `Warning` instances + * from `Result#messages`. + * + * ```js + * result.warnings().forEach(warn => { + * console.warn(warn.toString()) + * }) + * ``` + * + * @return Warnings from plugins. + */ + warnings(): Warning[] + + /** + * An alias for the `Result#css` property. + * Use it with syntaxes that generate non-CSS output. + * + * ```js + * result.css === result.content + * ``` + */ + get content(): string +} + +declare class Result extends Result_ {} + +export = Result diff --git a/node_modules/postcss/lib/result.js b/node_modules/postcss/lib/result.js new file mode 100644 index 0000000..a39751d --- /dev/null +++ b/node_modules/postcss/lib/result.js @@ -0,0 +1,42 @@ +'use strict' + +let Warning = require('./warning') + +class Result { + constructor(processor, root, opts) { + this.processor = processor + this.messages = [] + this.root = root + this.opts = opts + this.css = undefined + this.map = undefined + } + + toString() { + return this.css + } + + warn(text, opts = {}) { + if (!opts.plugin) { + if (this.lastPlugin && this.lastPlugin.postcssPlugin) { + opts.plugin = this.lastPlugin.postcssPlugin + } + } + + let warning = new Warning(text, opts) + this.messages.push(warning) + + return warning + } + + warnings() { + return this.messages.filter(i => i.type === 'warning') + } + + get content() { + return this.css + } +} + +module.exports = Result +Result.default = Result diff --git a/node_modules/postcss/lib/root.d.ts b/node_modules/postcss/lib/root.d.ts new file mode 100644 index 0000000..5c91139 --- /dev/null +++ b/node_modules/postcss/lib/root.d.ts @@ -0,0 +1,87 @@ +import Container, { ContainerProps } from './container.js' +import Document from './document.js' +import { ProcessOptions } from './postcss.js' +import Result from './result.js' + +declare namespace Root { + export interface RootRaws extends Record { + /** + * The space symbols after the last child to the end of file. + */ + after?: string + + /** + * Non-CSS code after `Root`, when `Root` is inside `Document`. + * + * **Experimental:** some aspects of this node could change within minor + * or patch version releases. + */ + codeAfter?: string + + /** + * Non-CSS code before `Root`, when `Root` is inside `Document`. + * + * **Experimental:** some aspects of this node could change within minor + * or patch version releases. + */ + codeBefore?: string + + /** + * Is the last child has an (optional) semicolon. + */ + semicolon?: boolean + } + + export interface RootProps extends ContainerProps { + /** + * Information used to generate byte-to-byte equal node string + * as it was in the origin input. + * */ + raws?: RootRaws + } + + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { Root_ as default } +} + +/** + * Represents a CSS file and contains all its parsed nodes. + * + * ```js + * const root = postcss.parse('a{color:black} b{z-index:2}') + * root.type //=> 'root' + * root.nodes.length //=> 2 + * ``` + */ +declare class Root_ extends Container { + nodes: NonNullable + parent: Document | undefined + raws: Root.RootRaws + type: 'root' + + constructor(defaults?: Root.RootProps) + + assign(overrides: object | Root.RootProps): this + clone(overrides?: Partial): this + cloneAfter(overrides?: Partial): this + cloneBefore(overrides?: Partial): this + + /** + * Returns a `Result` instance representing the root’s CSS. + * + * ```js + * const root1 = postcss.parse(css1, { from: 'a.css' }) + * const root2 = postcss.parse(css2, { from: 'b.css' }) + * root1.append(root2) + * const result = root1.toResult({ to: 'all.css', map: true }) + * ``` + * + * @param options Options. + * @return Result with current root’s CSS. + */ + toResult(options?: ProcessOptions): Result +} + +declare class Root extends Root_ {} + +export = Root diff --git a/node_modules/postcss/lib/root.js b/node_modules/postcss/lib/root.js new file mode 100644 index 0000000..ea574ed --- /dev/null +++ b/node_modules/postcss/lib/root.js @@ -0,0 +1,61 @@ +'use strict' + +let Container = require('./container') + +let LazyResult, Processor + +class Root extends Container { + constructor(defaults) { + super(defaults) + this.type = 'root' + if (!this.nodes) this.nodes = [] + } + + normalize(child, sample, type) { + let nodes = super.normalize(child) + + if (sample) { + if (type === 'prepend') { + if (this.nodes.length > 1) { + sample.raws.before = this.nodes[1].raws.before + } else { + delete sample.raws.before + } + } else if (this.first !== sample) { + for (let node of nodes) { + node.raws.before = sample.raws.before + } + } + } + + return nodes + } + + removeChild(child, ignore) { + let index = this.index(child) + + if (!ignore && index === 0 && this.nodes.length > 1) { + this.nodes[1].raws.before = this.nodes[index].raws.before + } + + return super.removeChild(child) + } + + toResult(opts = {}) { + let lazy = new LazyResult(new Processor(), this, opts) + return lazy.stringify() + } +} + +Root.registerLazyResult = dependant => { + LazyResult = dependant +} + +Root.registerProcessor = dependant => { + Processor = dependant +} + +module.exports = Root +Root.default = Root + +Container.registerRoot(Root) diff --git a/node_modules/postcss/lib/rule.d.ts b/node_modules/postcss/lib/rule.d.ts new file mode 100644 index 0000000..da8aae7 --- /dev/null +++ b/node_modules/postcss/lib/rule.d.ts @@ -0,0 +1,126 @@ +import Container, { + ContainerProps, + ContainerWithChildren +} from './container.js' + +declare namespace Rule { + export interface RuleRaws extends Record { + /** + * The space symbols after the last child of the node to the end of the node. + */ + after?: string + + /** + * The space symbols before the node. It also stores `*` + * and `_` symbols before the declaration (IE hack). + */ + before?: string + + /** + * The symbols between the selector and `{` for rules. + */ + between?: string + + /** + * Contains `true` if there is semicolon after rule. + */ + ownSemicolon?: string + + /** + * The rule’s selector with comments. + */ + selector?: { + raw: string + value: string + } + + /** + * Contains `true` if the last child has an (optional) semicolon. + */ + semicolon?: boolean + } + + export type RuleProps = { + /** Information used to generate byte-to-byte equal node string as it was in the origin input. */ + raws?: RuleRaws + } & ( + | { + /** Selector or selectors of the rule. */ + selector: string + selectors?: never + } + | { + selector?: never + /** Selectors of the rule represented as an array of strings. */ + selectors: readonly string[] + } + ) & ContainerProps + + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { Rule_ as default } +} + +/** + * Represents a CSS rule: a selector followed by a declaration block. + * + * ```js + * Once (root, { Rule }) { + * let a = new Rule({ selector: 'a' }) + * a.append(…) + * root.append(a) + * } + * ``` + * + * ```js + * const root = postcss.parse('a{}') + * const rule = root.first + * rule.type //=> 'rule' + * rule.toString() //=> 'a{}' + * ``` + */ +declare class Rule_ extends Container { + nodes: NonNullable + parent: ContainerWithChildren | undefined + raws: Rule.RuleRaws + type: 'rule' + constructor(defaults?: Rule.RuleProps) + + assign(overrides: object | Rule.RuleProps): this + clone(overrides?: Partial): this + + cloneAfter(overrides?: Partial): this + + cloneBefore(overrides?: Partial): this + /** + * The rule’s full selector represented as a string. + * + * ```js + * const root = postcss.parse('a, b { }') + * const rule = root.first + * rule.selector //=> 'a, b' + * ``` + */ + get selector(): string + set selector(value: string) + /** + * An array containing the rule’s individual selectors. + * Groups of selectors are split at commas. + * + * ```js + * const root = postcss.parse('a, b { }') + * const rule = root.first + * + * rule.selector //=> 'a, b' + * rule.selectors //=> ['a', 'b'] + * + * rule.selectors = ['a', 'strong'] + * rule.selector //=> 'a, strong' + * ``` + */ + get selectors(): string[] + set selectors(values: string[]) +} + +declare class Rule extends Rule_ {} + +export = Rule diff --git a/node_modules/postcss/lib/rule.js b/node_modules/postcss/lib/rule.js new file mode 100644 index 0000000..a93ab25 --- /dev/null +++ b/node_modules/postcss/lib/rule.js @@ -0,0 +1,27 @@ +'use strict' + +let Container = require('./container') +let list = require('./list') + +class Rule extends Container { + constructor(defaults) { + super(defaults) + this.type = 'rule' + if (!this.nodes) this.nodes = [] + } + + get selectors() { + return list.comma(this.selector) + } + + set selectors(values) { + let match = this.selector ? this.selector.match(/,\s*/) : null + let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen') + this.selector = values.join(sep) + } +} + +module.exports = Rule +Rule.default = Rule + +Container.registerRule(Rule) diff --git a/node_modules/postcss/lib/stringifier.d.ts b/node_modules/postcss/lib/stringifier.d.ts new file mode 100644 index 0000000..f707a6a --- /dev/null +++ b/node_modules/postcss/lib/stringifier.d.ts @@ -0,0 +1,46 @@ +import { + AnyNode, + AtRule, + Builder, + Comment, + Container, + Declaration, + Document, + Root, + Rule +} from './postcss.js' + +declare namespace Stringifier { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { Stringifier_ as default } +} + +declare class Stringifier_ { + builder: Builder + constructor(builder: Builder) + atrule(node: AtRule, semicolon?: boolean): void + beforeAfter(node: AnyNode, detect: 'after' | 'before'): string + block(node: AnyNode, start: string): void + body(node: Container): void + comment(node: Comment): void + decl(node: Declaration, semicolon?: boolean): void + document(node: Document): void + raw(node: AnyNode, own: null | string, detect?: string): string + rawBeforeClose(root: Root): string | undefined + rawBeforeComment(root: Root, node: Comment): string | undefined + rawBeforeDecl(root: Root, node: Declaration): string | undefined + rawBeforeOpen(root: Root): string | undefined + rawBeforeRule(root: Root): string | undefined + rawColon(root: Root): string | undefined + rawEmptyBody(root: Root): string | undefined + rawIndent(root: Root): string | undefined + rawSemicolon(root: Root): boolean | undefined + rawValue(node: AnyNode, prop: string): string + root(node: Root): void + rule(node: Rule): void + stringify(node: AnyNode, semicolon?: boolean): void +} + +declare class Stringifier extends Stringifier_ {} + +export = Stringifier diff --git a/node_modules/postcss/lib/stringifier.js b/node_modules/postcss/lib/stringifier.js new file mode 100644 index 0000000..e07ad12 --- /dev/null +++ b/node_modules/postcss/lib/stringifier.js @@ -0,0 +1,353 @@ +'use strict' + +const DEFAULT_RAW = { + after: '\n', + beforeClose: '\n', + beforeComment: '\n', + beforeDecl: '\n', + beforeOpen: ' ', + beforeRule: '\n', + colon: ': ', + commentLeft: ' ', + commentRight: ' ', + emptyBody: '', + indent: ' ', + semicolon: false +} + +function capitalize(str) { + return str[0].toUpperCase() + str.slice(1) +} + +class Stringifier { + constructor(builder) { + this.builder = builder + } + + atrule(node, semicolon) { + let name = '@' + node.name + let params = node.params ? this.rawValue(node, 'params') : '' + + if (typeof node.raws.afterName !== 'undefined') { + name += node.raws.afterName + } else if (params) { + name += ' ' + } + + if (node.nodes) { + this.block(node, name + params) + } else { + let end = (node.raws.between || '') + (semicolon ? ';' : '') + this.builder(name + params + end, node) + } + } + + beforeAfter(node, detect) { + let value + if (node.type === 'decl') { + value = this.raw(node, null, 'beforeDecl') + } else if (node.type === 'comment') { + value = this.raw(node, null, 'beforeComment') + } else if (detect === 'before') { + value = this.raw(node, null, 'beforeRule') + } else { + value = this.raw(node, null, 'beforeClose') + } + + let buf = node.parent + let depth = 0 + while (buf && buf.type !== 'root') { + depth += 1 + buf = buf.parent + } + + if (value.includes('\n')) { + let indent = this.raw(node, null, 'indent') + if (indent.length) { + for (let step = 0; step < depth; step++) value += indent + } + } + + return value + } + + block(node, start) { + let between = this.raw(node, 'between', 'beforeOpen') + this.builder(start + between + '{', node, 'start') + + let after + if (node.nodes && node.nodes.length) { + this.body(node) + after = this.raw(node, 'after') + } else { + after = this.raw(node, 'after', 'emptyBody') + } + + if (after) this.builder(after) + this.builder('}', node, 'end') + } + + body(node) { + let last = node.nodes.length - 1 + while (last > 0) { + if (node.nodes[last].type !== 'comment') break + last -= 1 + } + + let semicolon = this.raw(node, 'semicolon') + for (let i = 0; i < node.nodes.length; i++) { + let child = node.nodes[i] + let before = this.raw(child, 'before') + if (before) this.builder(before) + this.stringify(child, last !== i || semicolon) + } + } + + comment(node) { + let left = this.raw(node, 'left', 'commentLeft') + let right = this.raw(node, 'right', 'commentRight') + this.builder('/*' + left + node.text + right + '*/', node) + } + + decl(node, semicolon) { + let between = this.raw(node, 'between', 'colon') + let string = node.prop + between + this.rawValue(node, 'value') + + if (node.important) { + string += node.raws.important || ' !important' + } + + if (semicolon) string += ';' + this.builder(string, node) + } + + document(node) { + this.body(node) + } + + raw(node, own, detect) { + let value + if (!detect) detect = own + + // Already had + if (own) { + value = node.raws[own] + if (typeof value !== 'undefined') return value + } + + let parent = node.parent + + if (detect === 'before') { + // Hack for first rule in CSS + if (!parent || (parent.type === 'root' && parent.first === node)) { + return '' + } + + // `root` nodes in `document` should use only their own raws + if (parent && parent.type === 'document') { + return '' + } + } + + // Floating child without parent + if (!parent) return DEFAULT_RAW[detect] + + // Detect style by other nodes + let root = node.root() + if (!root.rawCache) root.rawCache = {} + if (typeof root.rawCache[detect] !== 'undefined') { + return root.rawCache[detect] + } + + if (detect === 'before' || detect === 'after') { + return this.beforeAfter(node, detect) + } else { + let method = 'raw' + capitalize(detect) + if (this[method]) { + value = this[method](root, node) + } else { + root.walk(i => { + value = i.raws[own] + if (typeof value !== 'undefined') return false + }) + } + } + + if (typeof value === 'undefined') value = DEFAULT_RAW[detect] + + root.rawCache[detect] = value + return value + } + + rawBeforeClose(root) { + let value + root.walk(i => { + if (i.nodes && i.nodes.length > 0) { + if (typeof i.raws.after !== 'undefined') { + value = i.raws.after + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, '') + } + return false + } + } + }) + if (value) value = value.replace(/\S/g, '') + return value + } + + rawBeforeComment(root, node) { + let value + root.walkComments(i => { + if (typeof i.raws.before !== 'undefined') { + value = i.raws.before + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, '') + } + return false + } + }) + if (typeof value === 'undefined') { + value = this.raw(node, null, 'beforeDecl') + } else if (value) { + value = value.replace(/\S/g, '') + } + return value + } + + rawBeforeDecl(root, node) { + let value + root.walkDecls(i => { + if (typeof i.raws.before !== 'undefined') { + value = i.raws.before + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, '') + } + return false + } + }) + if (typeof value === 'undefined') { + value = this.raw(node, null, 'beforeRule') + } else if (value) { + value = value.replace(/\S/g, '') + } + return value + } + + rawBeforeOpen(root) { + let value + root.walk(i => { + if (i.type !== 'decl') { + value = i.raws.between + if (typeof value !== 'undefined') return false + } + }) + return value + } + + rawBeforeRule(root) { + let value + root.walk(i => { + if (i.nodes && (i.parent !== root || root.first !== i)) { + if (typeof i.raws.before !== 'undefined') { + value = i.raws.before + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, '') + } + return false + } + } + }) + if (value) value = value.replace(/\S/g, '') + return value + } + + rawColon(root) { + let value + root.walkDecls(i => { + if (typeof i.raws.between !== 'undefined') { + value = i.raws.between.replace(/[^\s:]/g, '') + return false + } + }) + return value + } + + rawEmptyBody(root) { + let value + root.walk(i => { + if (i.nodes && i.nodes.length === 0) { + value = i.raws.after + if (typeof value !== 'undefined') return false + } + }) + return value + } + + rawIndent(root) { + if (root.raws.indent) return root.raws.indent + let value + root.walk(i => { + let p = i.parent + if (p && p !== root && p.parent && p.parent === root) { + if (typeof i.raws.before !== 'undefined') { + let parts = i.raws.before.split('\n') + value = parts[parts.length - 1] + value = value.replace(/\S/g, '') + return false + } + } + }) + return value + } + + rawSemicolon(root) { + let value + root.walk(i => { + if (i.nodes && i.nodes.length && i.last.type === 'decl') { + value = i.raws.semicolon + if (typeof value !== 'undefined') return false + } + }) + return value + } + + rawValue(node, prop) { + let value = node[prop] + let raw = node.raws[prop] + if (raw && raw.value === value) { + return raw.raw + } + + return value + } + + root(node) { + this.body(node) + if (node.raws.after) this.builder(node.raws.after) + } + + rule(node) { + this.block(node, this.rawValue(node, 'selector')) + if (node.raws.ownSemicolon) { + this.builder(node.raws.ownSemicolon, node, 'end') + } + } + + stringify(node, semicolon) { + /* c8 ignore start */ + if (!this[node.type]) { + throw new Error( + 'Unknown AST node type ' + + node.type + + '. ' + + 'Maybe you need to change PostCSS stringifier.' + ) + } + /* c8 ignore stop */ + this[node.type](node, semicolon) + } +} + +module.exports = Stringifier +Stringifier.default = Stringifier diff --git a/node_modules/postcss/lib/stringify.d.ts b/node_modules/postcss/lib/stringify.d.ts new file mode 100644 index 0000000..06ad0b4 --- /dev/null +++ b/node_modules/postcss/lib/stringify.d.ts @@ -0,0 +1,9 @@ +import { Stringifier } from './postcss.js' + +interface Stringify extends Stringifier { + default: Stringify +} + +declare const stringify: Stringify + +export = stringify diff --git a/node_modules/postcss/lib/stringify.js b/node_modules/postcss/lib/stringify.js new file mode 100644 index 0000000..77bd017 --- /dev/null +++ b/node_modules/postcss/lib/stringify.js @@ -0,0 +1,11 @@ +'use strict' + +let Stringifier = require('./stringifier') + +function stringify(node, builder) { + let str = new Stringifier(builder) + str.stringify(node) +} + +module.exports = stringify +stringify.default = stringify diff --git a/node_modules/postcss/lib/symbols.js b/node_modules/postcss/lib/symbols.js new file mode 100644 index 0000000..a142c26 --- /dev/null +++ b/node_modules/postcss/lib/symbols.js @@ -0,0 +1,5 @@ +'use strict' + +module.exports.isClean = Symbol('isClean') + +module.exports.my = Symbol('my') diff --git a/node_modules/postcss/lib/terminal-highlight.js b/node_modules/postcss/lib/terminal-highlight.js new file mode 100644 index 0000000..6196c9d --- /dev/null +++ b/node_modules/postcss/lib/terminal-highlight.js @@ -0,0 +1,70 @@ +'use strict' + +let pico = require('picocolors') + +let tokenizer = require('./tokenize') + +let Input + +function registerInput(dependant) { + Input = dependant +} + +const HIGHLIGHT_THEME = { + ';': pico.yellow, + ':': pico.yellow, + '(': pico.cyan, + ')': pico.cyan, + '[': pico.yellow, + ']': pico.yellow, + '{': pico.yellow, + '}': pico.yellow, + 'at-word': pico.cyan, + 'brackets': pico.cyan, + 'call': pico.cyan, + 'class': pico.yellow, + 'comment': pico.gray, + 'hash': pico.magenta, + 'string': pico.green +} + +function getTokenType([type, value], processor) { + if (type === 'word') { + if (value[0] === '.') { + return 'class' + } + if (value[0] === '#') { + return 'hash' + } + } + + if (!processor.endOfFile()) { + let next = processor.nextToken() + processor.back(next) + if (next[0] === 'brackets' || next[0] === '(') return 'call' + } + + return type +} + +function terminalHighlight(css) { + let processor = tokenizer(new Input(css), { ignoreErrors: true }) + let result = '' + while (!processor.endOfFile()) { + let token = processor.nextToken() + let color = HIGHLIGHT_THEME[getTokenType(token, processor)] + if (color) { + result += token[1] + .split(/\r?\n/) + .map(i => color(i)) + .join('\n') + } else { + result += token[1] + } + } + return result +} + +terminalHighlight.registerInput = registerInput + +module.exports = terminalHighlight diff --git a/node_modules/postcss/lib/tokenize.js b/node_modules/postcss/lib/tokenize.js new file mode 100644 index 0000000..1d41284 --- /dev/null +++ b/node_modules/postcss/lib/tokenize.js @@ -0,0 +1,266 @@ +'use strict' + +const SINGLE_QUOTE = "'".charCodeAt(0) +const DOUBLE_QUOTE = '"'.charCodeAt(0) +const BACKSLASH = '\\'.charCodeAt(0) +const SLASH = '/'.charCodeAt(0) +const NEWLINE = '\n'.charCodeAt(0) +const SPACE = ' '.charCodeAt(0) +const FEED = '\f'.charCodeAt(0) +const TAB = '\t'.charCodeAt(0) +const CR = '\r'.charCodeAt(0) +const OPEN_SQUARE = '['.charCodeAt(0) +const CLOSE_SQUARE = ']'.charCodeAt(0) +const OPEN_PARENTHESES = '('.charCodeAt(0) +const CLOSE_PARENTHESES = ')'.charCodeAt(0) +const OPEN_CURLY = '{'.charCodeAt(0) +const CLOSE_CURLY = '}'.charCodeAt(0) +const SEMICOLON = ';'.charCodeAt(0) +const ASTERISK = '*'.charCodeAt(0) +const COLON = ':'.charCodeAt(0) +const AT = '@'.charCodeAt(0) + +const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g +const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g +const RE_BAD_BRACKET = /.[\r\n"'(/\\]/ +const RE_HEX_ESCAPE = /[\da-f]/i + +module.exports = function tokenizer(input, options = {}) { + let css = input.css.valueOf() + let ignore = options.ignoreErrors + + let code, content, escape, next, quote + let currentToken, escaped, escapePos, n, prev + + let length = css.length + let pos = 0 + let buffer = [] + let returned = [] + + function position() { + return pos + } + + function unclosed(what) { + throw input.error('Unclosed ' + what, pos) + } + + function endOfFile() { + return returned.length === 0 && pos >= length + } + + function nextToken(opts) { + if (returned.length) return returned.pop() + if (pos >= length) return + + let ignoreUnclosed = opts ? opts.ignoreUnclosed : false + + code = css.charCodeAt(pos) + + switch (code) { + case NEWLINE: + case SPACE: + case TAB: + case CR: + case FEED: { + next = pos + do { + next += 1 + code = css.charCodeAt(next) + } while ( + code === SPACE || + code === NEWLINE || + code === TAB || + code === CR || + code === FEED + ) + + currentToken = ['space', css.slice(pos, next)] + pos = next - 1 + break + } + + case OPEN_SQUARE: + case CLOSE_SQUARE: + case OPEN_CURLY: + case CLOSE_CURLY: + case COLON: + case SEMICOLON: + case CLOSE_PARENTHESES: { + let controlChar = String.fromCharCode(code) + currentToken = [controlChar, controlChar, pos] + break + } + + case OPEN_PARENTHESES: { + prev = buffer.length ? buffer.pop()[1] : '' + n = css.charCodeAt(pos + 1) + if ( + prev === 'url' && + n !== SINGLE_QUOTE && + n !== DOUBLE_QUOTE && + n !== SPACE && + n !== NEWLINE && + n !== TAB && + n !== FEED && + n !== CR + ) { + next = pos + do { + escaped = false + next = css.indexOf(')', next + 1) + if (next === -1) { + if (ignore || ignoreUnclosed) { + next = pos + break + } else { + unclosed('bracket') + } + } + escapePos = next + while (css.charCodeAt(escapePos - 1) === BACKSLASH) { + escapePos -= 1 + escaped = !escaped + } + } while (escaped) + + currentToken = ['brackets', css.slice(pos, next + 1), pos, next] + + pos = next + } else { + next = css.indexOf(')', pos + 1) + content = css.slice(pos, next + 1) + + if (next === -1 || RE_BAD_BRACKET.test(content)) { + currentToken = ['(', '(', pos] + } else { + currentToken = ['brackets', content, pos, next] + pos = next + } + } + + break + } + + case SINGLE_QUOTE: + case DOUBLE_QUOTE: { + quote = code === SINGLE_QUOTE ? "'" : '"' + next = pos + do { + escaped = false + next = css.indexOf(quote, next + 1) + if (next === -1) { + if (ignore || ignoreUnclosed) { + next = pos + 1 + break + } else { + unclosed('string') + } + } + escapePos = next + while (css.charCodeAt(escapePos - 1) === BACKSLASH) { + escapePos -= 1 + escaped = !escaped + } + } while (escaped) + + currentToken = ['string', css.slice(pos, next + 1), pos, next] + pos = next + break + } + + case AT: { + RE_AT_END.lastIndex = pos + 1 + RE_AT_END.test(css) + if (RE_AT_END.lastIndex === 0) { + next = css.length - 1 + } else { + next = RE_AT_END.lastIndex - 2 + } + + currentToken = ['at-word', css.slice(pos, next + 1), pos, next] + + pos = next + break + } + + case BACKSLASH: { + next = pos + escape = true + while (css.charCodeAt(next + 1) === BACKSLASH) { + next += 1 + escape = !escape + } + code = css.charCodeAt(next + 1) + if ( + escape && + code !== SLASH && + code !== SPACE && + code !== NEWLINE && + code !== TAB && + code !== CR && + code !== FEED + ) { + next += 1 + if (RE_HEX_ESCAPE.test(css.charAt(next))) { + while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) { + next += 1 + } + if (css.charCodeAt(next + 1) === SPACE) { + next += 1 + } + } + } + + currentToken = ['word', css.slice(pos, next + 1), pos, next] + + pos = next + break + } + + default: { + if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) { + next = css.indexOf('*/', pos + 2) + 1 + if (next === 0) { + if (ignore || ignoreUnclosed) { + next = css.length + } else { + unclosed('comment') + } + } + + currentToken = ['comment', css.slice(pos, next + 1), pos, next] + pos = next + } else { + RE_WORD_END.lastIndex = pos + 1 + RE_WORD_END.test(css) + if (RE_WORD_END.lastIndex === 0) { + next = css.length - 1 + } else { + next = RE_WORD_END.lastIndex - 2 + } + + currentToken = ['word', css.slice(pos, next + 1), pos, next] + buffer.push(currentToken) + pos = next + } + + break + } + } + + pos++ + return currentToken + } + + function back(token) { + returned.push(token) + } + + return { + back, + endOfFile, + nextToken, + position + } +} diff --git a/node_modules/postcss/lib/warn-once.js b/node_modules/postcss/lib/warn-once.js new file mode 100644 index 0000000..316e1cf --- /dev/null +++ b/node_modules/postcss/lib/warn-once.js @@ -0,0 +1,13 @@ +/* eslint-disable no-console */ +'use strict' + +let printed = {} + +module.exports = function warnOnce(message) { + if (printed[message]) return + printed[message] = true + + if (typeof console !== 'undefined' && console.warn) { + console.warn(message) + } +} diff --git a/node_modules/postcss/lib/warning.d.ts b/node_modules/postcss/lib/warning.d.ts new file mode 100644 index 0000000..b25bba8 --- /dev/null +++ b/node_modules/postcss/lib/warning.d.ts @@ -0,0 +1,147 @@ +import { RangePosition } from './css-syntax-error.js' +import Node from './node.js' + +declare namespace Warning { + export interface WarningOptions { + /** + * End position, exclusive, in CSS node string that caused the warning. + */ + end?: RangePosition + + /** + * End index, exclusive, in CSS node string that caused the warning. + */ + endIndex?: number + + /** + * Start index, inclusive, in CSS node string that caused the warning. + */ + index?: number + + /** + * CSS node that caused the warning. + */ + node?: Node + + /** + * Name of the plugin that created this warning. `Result#warn` fills + * this property automatically. + */ + plugin?: string + + /** + * Start position, inclusive, in CSS node string that caused the warning. + */ + start?: RangePosition + + /** + * Word in CSS source that caused the warning. + */ + word?: string + } + + // eslint-disable-next-line @typescript-eslint/no-use-before-define + export { Warning_ as default } +} + +/** + * Represents a plugin’s warning. It can be created using `Node#warn`. + * + * ```js + * if (decl.important) { + * decl.warn(result, 'Avoid !important', { word: '!important' }) + * } + * ``` + */ +declare class Warning_ { + /** + * Column for inclusive start position in the input file with this warning’s source. + * + * ```js + * warning.column //=> 6 + * ``` + */ + column: number + + /** + * Column for exclusive end position in the input file with this warning’s source. + * + * ```js + * warning.endColumn //=> 4 + * ``` + */ + endColumn?: number + + /** + * Line for exclusive end position in the input file with this warning’s source. + * + * ```js + * warning.endLine //=> 6 + * ``` + */ + endLine?: number + + /** + * Line for inclusive start position in the input file with this warning’s source. + * + * ```js + * warning.line //=> 5 + * ``` + */ + line: number + + /** + * Contains the CSS node that caused the warning. + * + * ```js + * warning.node.toString() //=> 'color: white !important' + * ``` + */ + node: Node + + /** + * The name of the plugin that created this warning. + * When you call `Node#warn` it will fill this property automatically. + * + * ```js + * warning.plugin //=> 'postcss-important' + * ``` + */ + plugin: string + + /** + * The warning message. + * + * ```js + * warning.text //=> 'Try to avoid !important' + * ``` + */ + text: string + + /** + * Type to filter warnings from `Result#messages`. + * Always equal to `"warning"`. + */ + type: 'warning' + + /** + * @param text Warning message. + * @param opts Warning options. + */ + constructor(text: string, opts?: Warning.WarningOptions) + + /** + * Returns a warning position and message. + * + * ```js + * warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important' + * ``` + * + * @return Warning position and message. + */ + toString(): string +} + +declare class Warning extends Warning_ {} + +export = Warning diff --git a/node_modules/postcss/lib/warning.js b/node_modules/postcss/lib/warning.js new file mode 100644 index 0000000..3a3d79c --- /dev/null +++ b/node_modules/postcss/lib/warning.js @@ -0,0 +1,37 @@ +'use strict' + +class Warning { + constructor(text, opts = {}) { + this.type = 'warning' + this.text = text + + if (opts.node && opts.node.source) { + let range = opts.node.rangeBy(opts) + this.line = range.start.line + this.column = range.start.column + this.endLine = range.end.line + this.endColumn = range.end.column + } + + for (let opt in opts) this[opt] = opts[opt] + } + + toString() { + if (this.node) { + return this.node.error(this.text, { + index: this.index, + plugin: this.plugin, + word: this.word + }).message + } + + if (this.plugin) { + return this.plugin + ': ' + this.text + } + + return this.text + } +} + +module.exports = Warning +Warning.default = Warning diff --git a/node_modules/postcss/package.json b/node_modules/postcss/package.json new file mode 100755 index 0000000..bd8992a --- /dev/null +++ b/node_modules/postcss/package.json @@ -0,0 +1,88 @@ +{ + "name": "postcss", + "version": "8.4.47", + "description": "Tool for transforming styles with JS plugins", + "engines": { + "node": "^10 || ^12 || >=14" + }, + "exports": { + ".": { + "require": "./lib/postcss.js", + "import": "./lib/postcss.mjs" + }, + "./lib/at-rule": "./lib/at-rule.js", + "./lib/comment": "./lib/comment.js", + "./lib/container": "./lib/container.js", + "./lib/css-syntax-error": "./lib/css-syntax-error.js", + "./lib/declaration": "./lib/declaration.js", + "./lib/fromJSON": "./lib/fromJSON.js", + "./lib/input": "./lib/input.js", + "./lib/lazy-result": "./lib/lazy-result.js", + "./lib/no-work-result": "./lib/no-work-result.js", + "./lib/list": "./lib/list.js", + "./lib/map-generator": "./lib/map-generator.js", + "./lib/node": "./lib/node.js", + "./lib/parse": "./lib/parse.js", + "./lib/parser": "./lib/parser.js", + "./lib/postcss": "./lib/postcss.js", + "./lib/previous-map": "./lib/previous-map.js", + "./lib/processor": "./lib/processor.js", + "./lib/result": "./lib/result.js", + "./lib/root": "./lib/root.js", + "./lib/rule": "./lib/rule.js", + "./lib/stringifier": "./lib/stringifier.js", + "./lib/stringify": "./lib/stringify.js", + "./lib/symbols": "./lib/symbols.js", + "./lib/terminal-highlight": "./lib/terminal-highlight.js", + "./lib/tokenize": "./lib/tokenize.js", + "./lib/warn-once": "./lib/warn-once.js", + "./lib/warning": "./lib/warning.js", + "./package.json": "./package.json" + }, + "main": "./lib/postcss.js", + "types": "./lib/postcss.d.ts", + "keywords": [ + "css", + "postcss", + "rework", + "preprocessor", + "parser", + "source map", + "transform", + "manipulation", + "transpiler" + ], + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "author": "Andrey Sitnik ", + "license": "MIT", + "homepage": "https://postcss.org/", + "repository": "postcss/postcss", + "bugs": { + "url": "https://github.com/postcss/postcss/issues" + }, + "dependencies": { + "nanoid": "^3.3.7", + "picocolors": "^1.1.0", + "source-map-js": "^1.2.1" + }, + "browser": { + "./lib/terminal-highlight": false, + "source-map-js": false, + "path": false, + "url": false, + "fs": false + } +} diff --git a/node_modules/posthtml-match-helper/LICENSE b/node_modules/posthtml-match-helper/LICENSE new file mode 100644 index 0000000..c2cf232 --- /dev/null +++ b/node_modules/posthtml-match-helper/LICENSE @@ -0,0 +1,21 @@ +MIT License (MIT) + +Copyright (c) Rasmus Fløe + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/posthtml-match-helper/README.md b/node_modules/posthtml-match-helper/README.md new file mode 100644 index 0000000..73463dd --- /dev/null +++ b/node_modules/posthtml-match-helper/README.md @@ -0,0 +1,84 @@ +
+ +

posthtml-match-helper

+ + Expand CSS selectors into PostHTML matcher objects + + [![Version][npm-version-shield]][npm] + [![Build][github-ci-shield]][github-ci] + [![License][license-shield]][license] + [![Downloads][npm-stats-shield]][npm-stats] +
+ +## Introduction + +This PostHTML plugin can turn simple CSS selectors into [matcher objects](https://github.com/posthtml/posthtml/blob/master/README.md#match). + +Supported features: + +* Tags: `"div"` returns `{tag: "div"}`. +* Ids: `"#bar"` returns `{attrs: {id: "bar"}}`. +* Classes: `.foo` returns `{attrs: { class: /(?:^|\s)foo(?:\\s|$)/ }}`. Any number of classnames supported. +* Attribute selectors: any number of standard [attribute selectors](https://developer.mozilla.org/en/docs/Web/CSS/Attribute_selectors) can be used1 including the following non-standard: + * `[attr!=value]`: matches attributes with values that do not contain `value`. +* Multiple node selectors: `"div, span"` returns `[{tag: "div"}, {tag: "span"}]`. + +**1** Multiple attribute selectors for the same attribute are not supported (this includes mixing classnames and attribute selectors matching `class`). + +The basic template for selectors (and order of features) looks like this: + +```js +"tag#id.class.name[attr*=value][otherattr^='start']" +``` + +## Basic usage + +```js +import matchHelper from "posthtml-match-helper"; + +tree.match(matchHelper("div.class"), function (node) { + // do stuff with matched node... +}); +``` + +## Advanced usage + +```js +import matchHelper from "posthtml-match-helper"; + +tree.match(matchHelper("input.my-control[type!='radio'][checked], input[value^='foo'][checked]"), function (node) { + // do stuff with node that matched either of the selectors... +}); +``` + +## Classnames with escaped characters + +If you need to match nodes with classnames that use escaped characters, like those in Tailwind CSS utilities with arbitrary values, use the following syntax: + +```js +import matchHelper from "posthtml-match-helper"; + +tree.match(matchHelper("input.\\[display:none\\]"), function (node) { + // do stuff with node that matched either of the selectors... +}); +``` + + +## The helper function + +#### Arguments + +* `matcher` (string) - A CSS selector that describes the node you want to match in PostHTML. + +#### Returns + +A matcher object or an array of matcher objects. + +[npm]: https://www.npmjs.com/package/posthtml-match-helper +[npm-version-shield]: https://img.shields.io/npm/v/posthtml-match-helper.svg +[npm-stats]: http://npm-stat.com/charts.html?package=posthtml-match-helper +[npm-stats-shield]: https://img.shields.io/npm/dt/posthtml-match-helper.svg +[github-ci]: https://github.com/posthtml/posthtml-match-helper/actions/workflows/nodejs.yml +[github-ci-shield]: https://github.com/posthtml/posthtml-match-helper/actions/workflows/nodejs.yml/badge.svg +[license]: ./LICENSE +[license-shield]: https://img.shields.io/npm/l/posthtml-match-helper.svg diff --git a/node_modules/posthtml-match-helper/lib/index.d.ts b/node_modules/posthtml-match-helper/lib/index.d.ts new file mode 100644 index 0000000..9e9ef25 --- /dev/null +++ b/node_modules/posthtml-match-helper/lib/index.d.ts @@ -0,0 +1,10 @@ +import type { AttrMatcher, StringMatcher } from "posthtml"; + +interface Matcher { + tag?: StringMatcher; + attrs: AttrMatcher; +} + +declare function createMatcher(matcher: string | string[]): Matcher | Matcher[]; + +export default createMatcher; diff --git a/node_modules/posthtml-match-helper/lib/index.js b/node_modules/posthtml-match-helper/lib/index.js new file mode 100644 index 0000000..6e7ca64 --- /dev/null +++ b/node_modules/posthtml-match-helper/lib/index.js @@ -0,0 +1,149 @@ +const selectorReg = /^([^#\.\[]+)?(?:#([^\.\[]+))?(?:\.((?:[^\[\]\\]|\\.)+))?((?:\[[^\]]*\])+)?$/; // eslint-disable-line +const attributeReg = /^([a-zA-Z0-9_-]*[^~|^$*!=])(?:([~|^$*!]?)=['"]?([^'"]*)['"]?)?$/; +const splitReg = /\s*,\s*/; + +function expandMatcher(matcher) { + if (typeof matcher === "string") { + const match = matcher.match(selectorReg); + + if (match) { + matcher = {}; + const tag = match[1]; + const id = match[2]; + const className = match[3]; + const attrs = match[4]; + let attributes; + + if (tag) { + matcher.tag = tag; + } + + if (attrs) { + attributes = expandAttributes(attrs); + } else if (id || className) { + attributes = {}; + } + + if (id) { + attributes.id = id; + } + + if (className) { + attributes.class = new RegExp(getCombinations(className.split(".")).map((order) => { + return "(?:^|\\s)" + order.join("\\s(?:.*?\\s)?") + "(?:\\s|$)"; + }).join("|")); + } + + if (attributes) { + matcher.attrs = attributes; + } + } else { + matcher = {tag: matcher}; + } + } + + return matcher; +} + +function cssAttrToRegExp(value, operator) { + let reg; + + switch (operator) { + case "~": + reg = "(?:^|\\s)" + value + "(?:\\s|$)"; + break; + + case "|": + reg = "^" + value + "(?:-|$)"; + break; + + case "^": + reg = "^" + value; + break; + + case "$": + reg = value + "$"; + break; + + case "*": + reg = value; + break; + + case "!": + reg = "^((?!" + value + ")[\\s\\S])*$"; + break; + + default: + reg = "^" + value + "$"; + break; + } + + return new RegExp(reg); +} + +function expandAttributes(attrs) { + attrs = attrs.slice(1, -1); + + if (attrs.length > 0) { + attrs = attrs.split("]["); + const attrObject = {}; + let l = attrs.length; + let attrMatch; + let name; + let operator; + let value; + + while (l--) { + attrMatch = attrs[l].match(attributeReg); + + if (attrMatch) { + name = attrMatch[1]; + operator = attrMatch[2]; + value = attrMatch[3]; + + if (!value) { + value = true; + } + + attrObject[name] = (operator) ? cssAttrToRegExp(value, operator) : value; + } + } + + return attrObject; + } +} + +function getCombinations(values, subresult) { + subresult = subresult || []; + let result = []; + + for (const value of values) { + if (subresult.indexOf(value) < 0) { + const _subresult = subresult.concat([value]); + + if (_subresult.length < values.length) { + result = result.concat(getCombinations(values, _subresult)); + } else { + result.push(_subresult); + } + } + } + + return result; +} + +export default function (matcher) { + if (typeof matcher === "string") { + if (matcher.match(splitReg)) { + matcher = matcher.split(splitReg); + } else { + return expandMatcher(matcher); + } + } + + if (Array.isArray(matcher)) { + return matcher.map(expandMatcher); + } + + return matcher; +} diff --git a/node_modules/posthtml-match-helper/package.json b/node_modules/posthtml-match-helper/package.json new file mode 100644 index 0000000..f92f8cf --- /dev/null +++ b/node_modules/posthtml-match-helper/package.json @@ -0,0 +1,41 @@ +{ + "name": "posthtml-match-helper", + "description": "A helper to expand CSS selectors into PostHTML matcher objects", + "version": "2.0.2", + "license": "MIT", + "author": "Rasmus Fløe (https://github.com/phloe)", + "repository": { + "type": "git", + "url": "https://github.com/posthtml/posthtml-match-helper.git" + }, + "bugs": "https://github.com/posthtml/posthtml-match-helper/issues", + "type": "module", + "exports": "./lib/index.js", + "types": "./lib/index.d.ts", + "engines": { + "node": ">=18" + }, + "scripts": { + "dev": "vitest", + "test": "vitest run --coverage", + "lint": "biome lint ./lib", + "pretest": "npm run lint", + "release": "npx np" + }, + "files": [ + "lib" + ], + "keywords": [ + "posthtml", + "posthtml-helper", + "posthtml-matcher" + ], + "peerDependencies": { + "posthtml": "^0.16.6" + }, + "devDependencies": { + "@biomejs/biome": "1.8.3", + "@vitest/coverage-v8": "^1.3.1", + "vitest": "^1.3.1" + } +} diff --git a/node_modules/posthtml-parser/dist/chunk.2UQLUWPH.js b/node_modules/posthtml-parser/dist/chunk.2UQLUWPH.js new file mode 100644 index 0000000..e3e2f6d --- /dev/null +++ b/node_modules/posthtml-parser/dist/chunk.2UQLUWPH.js @@ -0,0 +1 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true});var i=class{constructor(t){this.source=t,this.lastPosition={line:1,column:1},this.lastIndex=0}getPosition(t){if(t; +declare type Content = NodeText | Array; +declare type NodeText = string | number; +declare type NodeTag = { + tag?: Tag; + attrs?: Attributes; + content?: Content; + location?: SourceLocation; +}; +declare type Node = NodeText | NodeTag; +declare const parser: (html: string, options?: Options) => Node[]; + +export { Attributes, Content, Directive, Node, NodeTag, NodeText, Options, Tag, parser }; diff --git a/node_modules/posthtml-parser/dist/index.js b/node_modules/posthtml-parser/dist/index.js new file mode 100644 index 0000000..0111a8b --- /dev/null +++ b/node_modules/posthtml-parser/dist/index.js @@ -0,0 +1 @@ +"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk2UQLUWPHjs = require('./chunk.2UQLUWPH.js');var _htmlparser2 = require('htmlparser2');var I={lowerCaseTags:!1,lowerCaseAttributeNames:!1,decodeEntities:!1},P=[{name:"!doctype",start:"<",end:">"}],w= exports.parser =(g,c={})=>{let a=new (0, _chunk2UQLUWPHjs.a)(g),i=[],s=[],p=0,f={};function u(){return i[i.length-1]}function y(n,t){return n.name instanceof RegExp?new RegExp(n.name.source,"i").test(t):t===n.name}function x(n){let t={};return Object.keys(n).forEach(e=>{let o={};o[e]=String(n[e]).replace(/"/g,'"'),c.recognizeNoValueAttribute&&f[e]&&(o[e]=!0),Object.assign(t,o)}),t}function A(n,t){var l;let e=P.concat((l=c.directives)!=null?l:[]),o=u();for(let d of e){let b=d.start+t+d.end;if(y(d,n.toLowerCase())){if(o===void 0){s.push(b);return}typeof o=="object"&&(o.content===void 0&&(o.content=[]),Array.isArray(o.content)&&o.content.push(b))}}}function N(n){let t=u(),e=``;if(t===void 0){s.push(e);return}typeof t=="object"&&(t.content===void 0&&(t.content=[]),Array.isArray(t.content)&&t.content.push(e))}function m(n,t,e){e===void 0&&(f[n]=!0)}function h(n,t){let e={tag:n};c.sourceLocations&&(e.location={start:a.getPosition(r.startIndex),end:a.getPosition(r.endIndex)},p=r.endIndex),Object.keys(t).length>0&&(e.attrs=x(t)),f={},i.push(e)}function T(n,t){let e=i.pop();if(e&&typeof e=="object"&&e.location&&r.endIndex!==null&&(t?p0){let e=t.content[t.content.length-1];if(typeof e=="string"&&!e.startsWith(" + +```js +var parseRange = require('range-parser') +``` + +### parseRange(size, header, options) + +Parse the given `header` string where `size` is the maximum size of the resource. +An array of ranges will be returned or negative numbers indicating an error parsing. + + * `-2` signals a malformed header string + * `-1` signals an unsatisfiable range + + + +```js +// parse header from request +var range = parseRange(size, req.headers.range) + +// the type of the range +if (range.type === 'bytes') { + // the ranges + range.forEach(function (r) { + // do something with r.start and r.end + }) +} +``` + +#### Options + +These properties are accepted in the options object. + +##### combine + +Specifies if overlapping & adjacent ranges should be combined, defaults to `false`. +When `true`, ranges will be combined and returned as if they were specified that +way in the header. + + + +```js +parseRange(100, 'bytes=50-55,0-10,5-10,56-60', { combine: true }) +// => [ +// { start: 0, end: 10 }, +// { start: 50, end: 60 } +// ] +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/range-parser/master +[coveralls-url]: https://coveralls.io/r/jshttp/range-parser?branch=master +[node-image]: https://badgen.net/npm/node/range-parser +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/range-parser +[npm-url]: https://npmjs.org/package/range-parser +[npm-version-image]: https://badgen.net/npm/v/range-parser +[travis-image]: https://badgen.net/travis/jshttp/range-parser/master +[travis-url]: https://travis-ci.org/jshttp/range-parser diff --git a/node_modules/range-parser/index.js b/node_modules/range-parser/index.js new file mode 100644 index 0000000..b7dc5c0 --- /dev/null +++ b/node_modules/range-parser/index.js @@ -0,0 +1,162 @@ +/*! + * range-parser + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = rangeParser + +/** + * Parse "Range" header `str` relative to the given file `size`. + * + * @param {Number} size + * @param {String} str + * @param {Object} [options] + * @return {Array} + * @public + */ + +function rangeParser (size, str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string') + } + + var index = str.indexOf('=') + + if (index === -1) { + return -2 + } + + // split the range string + var arr = str.slice(index + 1).split(',') + var ranges = [] + + // add ranges type + ranges.type = str.slice(0, index) + + // parse all ranges + for (var i = 0; i < arr.length; i++) { + var range = arr[i].split('-') + var start = parseInt(range[0], 10) + var end = parseInt(range[1], 10) + + // -nnn + if (isNaN(start)) { + start = size - end + end = size - 1 + // nnn- + } else if (isNaN(end)) { + end = size - 1 + } + + // limit last-byte-pos to current length + if (end > size - 1) { + end = size - 1 + } + + // invalid or unsatisifiable + if (isNaN(start) || isNaN(end) || start > end || start < 0) { + continue + } + + // add range + ranges.push({ + start: start, + end: end + }) + } + + if (ranges.length < 1) { + // unsatisifiable + return -1 + } + + return options && options.combine + ? combineRanges(ranges) + : ranges +} + +/** + * Combine overlapping & adjacent ranges. + * @private + */ + +function combineRanges (ranges) { + var ordered = ranges.map(mapWithIndex).sort(sortByRangeStart) + + for (var j = 0, i = 1; i < ordered.length; i++) { + var range = ordered[i] + var current = ordered[j] + + if (range.start > current.end + 1) { + // next range + ordered[++j] = range + } else if (range.end > current.end) { + // extend range + current.end = range.end + current.index = Math.min(current.index, range.index) + } + } + + // trim ordered array + ordered.length = j + 1 + + // generate combined range + var combined = ordered.sort(sortByRangeIndex).map(mapWithoutIndex) + + // copy ranges type + combined.type = ranges.type + + return combined +} + +/** + * Map function to add index value to ranges. + * @private + */ + +function mapWithIndex (range, index) { + return { + start: range.start, + end: range.end, + index: index + } +} + +/** + * Map function to remove index value from ranges. + * @private + */ + +function mapWithoutIndex (range) { + return { + start: range.start, + end: range.end + } +} + +/** + * Sort function to sort ranges by index. + * @private + */ + +function sortByRangeIndex (a, b) { + return a.index - b.index +} + +/** + * Sort function to sort ranges by start position. + * @private + */ + +function sortByRangeStart (a, b) { + return a.start - b.start +} diff --git a/node_modules/range-parser/package.json b/node_modules/range-parser/package.json new file mode 100644 index 0000000..abea6d8 --- /dev/null +++ b/node_modules/range-parser/package.json @@ -0,0 +1,44 @@ +{ + "name": "range-parser", + "author": "TJ Holowaychuk (http://tjholowaychuk.com)", + "description": "Range header field string parser", + "version": "1.2.1", + "contributors": [ + "Douglas Christopher Wilson ", + "James Wyatt Cready ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "range", + "parser", + "http" + ], + "repository": "jshttp/range-parser", + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-markdown": "1.0.0", + "eslint-plugin-import": "2.17.2", + "eslint-plugin-node": "8.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "mocha": "6.1.4", + "nyc": "14.1.1" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "test-travis": "nyc --reporter=text npm test" + } +} diff --git a/node_modules/read-cache/LICENSE b/node_modules/read-cache/LICENSE new file mode 100644 index 0000000..4b98a41 --- /dev/null +++ b/node_modules/read-cache/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright 2016 Bogdan Chadkin + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/read-cache/README.md b/node_modules/read-cache/README.md new file mode 100644 index 0000000..16a5c36 --- /dev/null +++ b/node_modules/read-cache/README.md @@ -0,0 +1,46 @@ +# read-cache [![Build Status](https://travis-ci.org/TrySound/read-cache.svg?branch=master)](https://travis-ci.org/TrySound/read-cache) + +Reads and caches the entire contents of a file until it is modified. + + +## Install + +``` +$ npm i read-cache +``` + + +## Usage + +```js +// foo.js +var readCache = require('read-cache'); + +readCache('foo.js').then(function (contents) { + console.log(contents); +}); +``` + + +## API + +### readCache(path[, encoding]) + +Returns a promise that resolves with the file's contents. + +### readCache.sync(path[, encoding]) + +Returns the content of the file. + +### readCache.get(path[, encoding]) + +Returns the content of cached file or null. + +### readCache.clear() + +Clears the contents of the cache. + + +## License + +MIT © [Bogdan Chadkin](mailto:trysound@yandex.ru) diff --git a/node_modules/read-cache/index.js b/node_modules/read-cache/index.js new file mode 100644 index 0000000..b5263e6 --- /dev/null +++ b/node_modules/read-cache/index.js @@ -0,0 +1,78 @@ +var fs = require('fs'); +var path = require('path'); +var pify = require('pify'); + +var stat = pify(fs.stat); +var readFile = pify(fs.readFile); +var resolve = path.resolve; + +var cache = Object.create(null); + +function convert(content, encoding) { + if (Buffer.isEncoding(encoding)) { + return content.toString(encoding); + } + return content; +} + +module.exports = function (path, encoding) { + path = resolve(path); + + return stat(path).then(function (stats) { + var item = cache[path]; + + if (item && item.mtime.getTime() === stats.mtime.getTime()) { + return convert(item.content, encoding); + } + + return readFile(path).then(function (data) { + cache[path] = { + mtime: stats.mtime, + content: data + }; + + return convert(data, encoding); + }); + }).catch(function (err) { + cache[path] = null; + return Promise.reject(err); + }); +}; + +module.exports.sync = function (path, encoding) { + path = resolve(path); + + try { + var stats = fs.statSync(path); + var item = cache[path]; + + if (item && item.mtime.getTime() === stats.mtime.getTime()) { + return convert(item.content, encoding); + } + + var data = fs.readFileSync(path); + + cache[path] = { + mtime: stats.mtime, + content: data + }; + + return convert(data, encoding); + } catch (err) { + cache[path] = null; + throw err; + } + +}; + +module.exports.get = function (path, encoding) { + path = resolve(path); + if (cache[path]) { + return convert(cache[path].content, encoding); + } + return null; +}; + +module.exports.clear = function () { + cache = Object.create(null); +}; diff --git a/node_modules/read-cache/package.json b/node_modules/read-cache/package.json new file mode 100644 index 0000000..87199b0 --- /dev/null +++ b/node_modules/read-cache/package.json @@ -0,0 +1,34 @@ +{ + "name": "read-cache", + "version": "1.0.0", + "description": "Reads and caches the entire contents of a file until it is modified", + "files": [ + "index.js" + ], + "main": "index.js", + "scripts": { + "test": "ava" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/TrySound/read-cache.git" + }, + "keywords": [ + "fs", + "read", + "cache" + ], + "author": "Bogdan Chadkin ", + "license": "MIT", + "bugs": { + "url": "https://github.com/TrySound/read-cache/issues" + }, + "homepage": "https://github.com/TrySound/read-cache#readme", + "devDependencies": { + "ava": "^0.9.1", + "del": "^2.2.0" + }, + "dependencies": { + "pify": "^2.3.0" + } +} diff --git a/node_modules/read-pkg/index.js b/node_modules/read-pkg/index.js new file mode 100644 index 0000000..dff948b --- /dev/null +++ b/node_modules/read-pkg/index.js @@ -0,0 +1,47 @@ +'use strict'; +const path = require('path'); +const loadJsonFile = require('load-json-file'); +const pathType = require('path-type'); + +module.exports = (fp, opts) => { + if (typeof fp !== 'string') { + opts = fp; + fp = '.'; + } + + opts = opts || {}; + + return pathType.dir(fp) + .then(isDir => { + if (isDir) { + fp = path.join(fp, 'package.json'); + } + + return loadJsonFile(fp); + }) + .then(x => { + if (opts.normalize !== false) { + require('normalize-package-data')(x); + } + + return x; + }); +}; + +module.exports.sync = (fp, opts) => { + if (typeof fp !== 'string') { + opts = fp; + fp = '.'; + } + + opts = opts || {}; + fp = pathType.dirSync(fp) ? path.join(fp, 'package.json') : fp; + + const x = loadJsonFile.sync(fp); + + if (opts.normalize !== false) { + require('normalize-package-data')(x); + } + + return x; +}; diff --git a/node_modules/read-pkg/license b/node_modules/read-pkg/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/read-pkg/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/read-pkg/package.json b/node_modules/read-pkg/package.json new file mode 100644 index 0000000..1a40fe0 --- /dev/null +++ b/node_modules/read-pkg/package.json @@ -0,0 +1,42 @@ +{ + "name": "read-pkg", + "version": "3.0.0", + "description": "Read a package.json file", + "license": "MIT", + "repository": "sindresorhus/read-pkg", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=4" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "json", + "read", + "parse", + "file", + "fs", + "graceful", + "load", + "pkg", + "package", + "normalize" + ], + "dependencies": { + "load-json-file": "^4.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^3.0.0" + }, + "devDependencies": { + "ava": "*", + "xo": "*" + } +} diff --git a/node_modules/read-pkg/readme.md b/node_modules/read-pkg/readme.md new file mode 100644 index 0000000..6875067 --- /dev/null +++ b/node_modules/read-pkg/readme.md @@ -0,0 +1,79 @@ +# read-pkg [![Build Status](https://travis-ci.org/sindresorhus/read-pkg.svg?branch=master)](https://travis-ci.org/sindresorhus/read-pkg) + +> Read a package.json file + + +## Why + +- [Gracefully handles filesystem issues](https://github.com/isaacs/node-graceful-fs) +- [Strips UTF-8 BOM](https://github.com/sindresorhus/strip-bom) +- [Throws more helpful JSON errors](https://github.com/sindresorhus/parse-json) +- [Normalizes the data](https://github.com/npm/normalize-package-data#what-normalization-currently-entails) + + +## Install + +``` +$ npm install read-pkg +``` + + +## Usage + +```js +const readPkg = require('read-pkg'); + +readPkg().then(pkg => { + console.log(pkg); + //=> {name: 'read-pkg', ...} +}); + +readPkg(__dirname).then(pkg => { + console.log(pkg); + //=> {name: 'read-pkg', ...} +}); + +readPkg(path.join('unicorn', 'package.json')).then(pkg => { + console.log(pkg); + //=> {name: 'read-pkg', ...} +}); +``` + + +## API + +### readPkg([path], [options]) + +Returns a `Promise` for the parsed JSON. + +### readPkg.sync([path], [options]) + +Returns the parsed JSON. + +#### path + +Type: `string`
+Default: `process.cwd()` + +Path to a `package.json` file or its directory. + +#### options + +##### normalize + +Type: `boolean`
+Default: `true` + +[Normalize](https://github.com/npm/normalize-package-data#what-normalization-currently-entails) the package data. + + +## Related + +- [read-pkg-up](https://github.com/sindresorhus/read-pkg-up) - Read the closest package.json file +- [write-pkg](https://github.com/sindresorhus/write-pkg) - Write a `package.json` file +- [load-json-file](https://github.com/sindresorhus/load-json-file) - Read and parse a JSON file + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/readdirp/LICENSE b/node_modules/readdirp/LICENSE new file mode 100644 index 0000000..037cbb4 --- /dev/null +++ b/node_modules/readdirp/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/readdirp/README.md b/node_modules/readdirp/README.md new file mode 100644 index 0000000..465593c --- /dev/null +++ b/node_modules/readdirp/README.md @@ -0,0 +1,122 @@ +# readdirp [![Weekly downloads](https://img.shields.io/npm/dw/readdirp.svg)](https://github.com/paulmillr/readdirp) + +Recursive version of [fs.readdir](https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback). Exposes a **stream API** and a **promise API**. + + +```sh +npm install readdirp +``` + +```javascript +const readdirp = require('readdirp'); + +// Use streams to achieve small RAM & CPU footprint. +// 1) Streams example with for-await. +for await (const entry of readdirp('.')) { + const {path} = entry; + console.log(`${JSON.stringify({path})}`); +} + +// 2) Streams example, non for-await. +// Print out all JS files along with their size within the current folder & subfolders. +readdirp('.', {fileFilter: '*.js', alwaysStat: true}) + .on('data', (entry) => { + const {path, stats: {size}} = entry; + console.log(`${JSON.stringify({path, size})}`); + }) + // Optionally call stream.destroy() in `warn()` in order to abort and cause 'close' to be emitted + .on('warn', error => console.error('non-fatal error', error)) + .on('error', error => console.error('fatal error', error)) + .on('end', () => console.log('done')); + +// 3) Promise example. More RAM and CPU than streams / for-await. +const files = await readdirp.promise('.'); +console.log(files.map(file => file.path)); + +// Other options. +readdirp('test', { + fileFilter: '*.js', + directoryFilter: ['!.git', '!*modules'] + // directoryFilter: (di) => di.basename.length === 9 + type: 'files_directories', + depth: 1 +}); +``` + +For more examples, check out `examples` directory. + +## API + +`const stream = readdirp(root[, options])` — **Stream API** + +- Reads given root recursively and returns a `stream` of [entry infos](#entryinfo) +- Optionally can be used like `for await (const entry of stream)` with node.js 10+ (`asyncIterator`). +- `on('data', (entry) => {})` [entry info](#entryinfo) for every file / dir. +- `on('warn', (error) => {})` non-fatal `Error` that prevents a file / dir from being processed. Example: inaccessible to the user. +- `on('error', (error) => {})` fatal `Error` which also ends the stream. Example: illegal options where passed. +- `on('end')` — we are done. Called when all entries were found and no more will be emitted. +- `on('close')` — stream is destroyed via `stream.destroy()`. + Could be useful if you want to manually abort even on a non fatal error. + At that point the stream is no longer `readable` and no more entries, warning or errors are emitted +- To learn more about streams, consult the very detailed [nodejs streams documentation](https://nodejs.org/api/stream.html) + or the [stream-handbook](https://github.com/substack/stream-handbook) + +`const entries = await readdirp.promise(root[, options])` — **Promise API**. Returns a list of [entry infos](#entryinfo). + +First argument is awalys `root`, path in which to start reading and recursing into subdirectories. + +### options + +- `fileFilter: ["*.js"]`: filter to include or exclude files. A `Function`, Glob string or Array of glob strings. + - **Function**: a function that takes an entry info as a parameter and returns true to include or false to exclude the entry + - **Glob string**: a string (e.g., `*.js`) which is matched using [picomatch](https://github.com/micromatch/picomatch), so go there for more + information. Globstars (`**`) are not supported since specifying a recursive pattern for an already recursive function doesn't make sense. Negated globs (as explained in the minimatch documentation) are allowed, e.g., `!*.txt` matches everything but text files. + - **Array of glob strings**: either need to be all inclusive or all exclusive (negated) patterns otherwise an error is thrown. + `['*.json', '*.js']` includes all JavaScript and Json files. + `['!.git', '!node_modules']` includes all directories except the '.git' and 'node_modules'. + - Directories that do not pass a filter will not be recursed into. +- `directoryFilter: ['!.git']`: filter to include/exclude directories found and to recurse into. Directories that do not pass a filter will not be recursed into. +- `depth: 5`: depth at which to stop recursing even if more subdirectories are found +- `type: 'files'`: determines if data events on the stream should be emitted for `'files'` (default), `'directories'`, `'files_directories'`, or `'all'`. Setting to `'all'` will also include entries for other types of file descriptors like character devices, unix sockets and named pipes. +- `alwaysStat: false`: always return `stats` property for every file. Default is `false`, readdirp will return `Dirent` entries. Setting it to `true` can double readdir execution time - use it only when you need file `size`, `mtime` etc. Cannot be enabled on node <10.10.0. +- `lstat: false`: include symlink entries in the stream along with files. When `true`, `fs.lstat` would be used instead of `fs.stat` + +### `EntryInfo` + +Has the following properties: + +- `path: 'assets/javascripts/react.js'`: path to the file/directory (relative to given root) +- `fullPath: '/Users/dev/projects/app/assets/javascripts/react.js'`: full path to the file/directory found +- `basename: 'react.js'`: name of the file/directory +- `dirent: fs.Dirent`: built-in [dir entry object](https://nodejs.org/api/fs.html#fs_class_fs_dirent) - only with `alwaysStat: false` +- `stats: fs.Stats`: built in [stat object](https://nodejs.org/api/fs.html#fs_class_fs_stats) - only with `alwaysStat: true` + +## Changelog + +- 3.5 (Oct 13, 2020) disallows recursive directory-based symlinks. + Before, it could have entered infinite loop. +- 3.4 (Mar 19, 2020) adds support for directory-based symlinks. +- 3.3 (Dec 6, 2019) stabilizes RAM consumption and enables perf management with `highWaterMark` option. Fixes race conditions related to `for-await` looping. +- 3.2 (Oct 14, 2019) improves performance by 250% and makes streams implementation more idiomatic. +- 3.1 (Jul 7, 2019) brings `bigint` support to `stat` output on Windows. This is backwards-incompatible for some cases. Be careful. It you use it incorrectly, you'll see "TypeError: Cannot mix BigInt and other types, use explicit conversions". +- 3.0 brings huge performance improvements and stream backpressure support. +- Upgrading 2.x to 3.x: + - Signature changed from `readdirp(options)` to `readdirp(root, options)` + - Replaced callback API with promise API. + - Renamed `entryType` option to `type` + - Renamed `entryType: 'both'` to `'files_directories'` + - `EntryInfo` + - Renamed `stat` to `stats` + - Emitted only when `alwaysStat: true` + - `dirent` is emitted instead of `stats` by default with `alwaysStat: false` + - Renamed `name` to `basename` + - Removed `parentDir` and `fullParentDir` properties +- Supported node.js versions: + - 3.x: node 8+ + - 2.x: node 0.6+ + +## License + +Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller () + +MIT License, see [LICENSE](LICENSE) file. diff --git a/node_modules/readdirp/index.d.ts b/node_modules/readdirp/index.d.ts new file mode 100644 index 0000000..cbbd76c --- /dev/null +++ b/node_modules/readdirp/index.d.ts @@ -0,0 +1,43 @@ +// TypeScript Version: 3.2 + +/// + +import * as fs from 'fs'; +import { Readable } from 'stream'; + +declare namespace readdir { + interface EntryInfo { + path: string; + fullPath: string; + basename: string; + stats?: fs.Stats; + dirent?: fs.Dirent; + } + + interface ReaddirpOptions { + root?: string; + fileFilter?: string | string[] | ((entry: EntryInfo) => boolean); + directoryFilter?: string | string[] | ((entry: EntryInfo) => boolean); + type?: 'files' | 'directories' | 'files_directories' | 'all'; + lstat?: boolean; + depth?: number; + alwaysStat?: boolean; + } + + interface ReaddirpStream extends Readable, AsyncIterable { + read(): EntryInfo; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + function promise( + root: string, + options?: ReaddirpOptions + ): Promise; +} + +declare function readdir( + root: string, + options?: readdir.ReaddirpOptions +): readdir.ReaddirpStream; + +export = readdir; diff --git a/node_modules/readdirp/index.js b/node_modules/readdirp/index.js new file mode 100644 index 0000000..cf739b2 --- /dev/null +++ b/node_modules/readdirp/index.js @@ -0,0 +1,287 @@ +'use strict'; + +const fs = require('fs'); +const { Readable } = require('stream'); +const sysPath = require('path'); +const { promisify } = require('util'); +const picomatch = require('picomatch'); + +const readdir = promisify(fs.readdir); +const stat = promisify(fs.stat); +const lstat = promisify(fs.lstat); +const realpath = promisify(fs.realpath); + +/** + * @typedef {Object} EntryInfo + * @property {String} path + * @property {String} fullPath + * @property {fs.Stats=} stats + * @property {fs.Dirent=} dirent + * @property {String} basename + */ + +const BANG = '!'; +const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR'; +const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]); +const FILE_TYPE = 'files'; +const DIR_TYPE = 'directories'; +const FILE_DIR_TYPE = 'files_directories'; +const EVERYTHING_TYPE = 'all'; +const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE]; + +const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code); +const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10)); +const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5)); + +const normalizeFilter = filter => { + if (filter === undefined) return; + if (typeof filter === 'function') return filter; + + if (typeof filter === 'string') { + const glob = picomatch(filter.trim()); + return entry => glob(entry.basename); + } + + if (Array.isArray(filter)) { + const positive = []; + const negative = []; + for (const item of filter) { + const trimmed = item.trim(); + if (trimmed.charAt(0) === BANG) { + negative.push(picomatch(trimmed.slice(1))); + } else { + positive.push(picomatch(trimmed)); + } + } + + if (negative.length > 0) { + if (positive.length > 0) { + return entry => + positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename)); + } + return entry => !negative.some(f => f(entry.basename)); + } + return entry => positive.some(f => f(entry.basename)); + } +}; + +class ReaddirpStream extends Readable { + static get defaultOptions() { + return { + root: '.', + /* eslint-disable no-unused-vars */ + fileFilter: (path) => true, + directoryFilter: (path) => true, + /* eslint-enable no-unused-vars */ + type: FILE_TYPE, + lstat: false, + depth: 2147483648, + alwaysStat: false + }; + } + + constructor(options = {}) { + super({ + objectMode: true, + autoDestroy: true, + highWaterMark: options.highWaterMark || 4096 + }); + const opts = { ...ReaddirpStream.defaultOptions, ...options }; + const { root, type } = opts; + + this._fileFilter = normalizeFilter(opts.fileFilter); + this._directoryFilter = normalizeFilter(opts.directoryFilter); + + const statMethod = opts.lstat ? lstat : stat; + // Use bigint stats if it's windows and stat() supports options (node 10+). + if (wantBigintFsStats) { + this._stat = path => statMethod(path, { bigint: true }); + } else { + this._stat = statMethod; + } + + this._maxDepth = opts.depth; + this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type); + this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type); + this._wantsEverything = type === EVERYTHING_TYPE; + this._root = sysPath.resolve(root); + this._isDirent = ('Dirent' in fs) && !opts.alwaysStat; + this._statsProp = this._isDirent ? 'dirent' : 'stats'; + this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent }; + + // Launch stream with one parent, the root dir. + this.parents = [this._exploreDir(root, 1)]; + this.reading = false; + this.parent = undefined; + } + + async _read(batch) { + if (this.reading) return; + this.reading = true; + + try { + while (!this.destroyed && batch > 0) { + const { path, depth, files = [] } = this.parent || {}; + + if (files.length > 0) { + const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path)); + for (const entry of await Promise.all(slice)) { + if (this.destroyed) return; + + const entryType = await this._getEntryType(entry); + if (entryType === 'directory' && this._directoryFilter(entry)) { + if (depth <= this._maxDepth) { + this.parents.push(this._exploreDir(entry.fullPath, depth + 1)); + } + + if (this._wantsDir) { + this.push(entry); + batch--; + } + } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) { + if (this._wantsFile) { + this.push(entry); + batch--; + } + } + } + } else { + const parent = this.parents.pop(); + if (!parent) { + this.push(null); + break; + } + this.parent = await parent; + if (this.destroyed) return; + } + } + } catch (error) { + this.destroy(error); + } finally { + this.reading = false; + } + } + + async _exploreDir(path, depth) { + let files; + try { + files = await readdir(path, this._rdOptions); + } catch (error) { + this._onError(error); + } + return { files, depth, path }; + } + + async _formatEntry(dirent, path) { + let entry; + try { + const basename = this._isDirent ? dirent.name : dirent; + const fullPath = sysPath.resolve(sysPath.join(path, basename)); + entry = { path: sysPath.relative(this._root, fullPath), fullPath, basename }; + entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath); + } catch (err) { + this._onError(err); + } + return entry; + } + + _onError(err) { + if (isNormalFlowError(err) && !this.destroyed) { + this.emit('warn', err); + } else { + this.destroy(err); + } + } + + async _getEntryType(entry) { + // entry may be undefined, because a warning or an error were emitted + // and the statsProp is undefined + const stats = entry && entry[this._statsProp]; + if (!stats) { + return; + } + if (stats.isFile()) { + return 'file'; + } + if (stats.isDirectory()) { + return 'directory'; + } + if (stats && stats.isSymbolicLink()) { + const full = entry.fullPath; + try { + const entryRealPath = await realpath(full); + const entryRealPathStats = await lstat(entryRealPath); + if (entryRealPathStats.isFile()) { + return 'file'; + } + if (entryRealPathStats.isDirectory()) { + const len = entryRealPath.length; + if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath.sep) { + const recursiveError = new Error( + `Circular symlink detected: "${full}" points to "${entryRealPath}"` + ); + recursiveError.code = RECURSIVE_ERROR_CODE; + return this._onError(recursiveError); + } + return 'directory'; + } + } catch (error) { + this._onError(error); + } + } + } + + _includeAsFile(entry) { + const stats = entry && entry[this._statsProp]; + + return stats && this._wantsEverything && !stats.isDirectory(); + } +} + +/** + * @typedef {Object} ReaddirpArguments + * @property {Function=} fileFilter + * @property {Function=} directoryFilter + * @property {String=} type + * @property {Number=} depth + * @property {String=} root + * @property {Boolean=} lstat + * @property {Boolean=} bigint + */ + +/** + * Main function which ends up calling readdirRec and reads all files and directories in given root recursively. + * @param {String} root Root directory + * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth + */ +const readdirp = (root, options = {}) => { + let type = options.entryType || options.type; + if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility + if (type) options.type = type; + if (!root) { + throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)'); + } else if (typeof root !== 'string') { + throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)'); + } else if (type && !ALL_TYPES.includes(type)) { + throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`); + } + + options.root = root; + return new ReaddirpStream(options); +}; + +const readdirpPromise = (root, options = {}) => { + return new Promise((resolve, reject) => { + const files = []; + readdirp(root, options) + .on('data', entry => files.push(entry)) + .on('end', () => resolve(files)) + .on('error', error => reject(error)); + }); +}; + +readdirp.promise = readdirpPromise; +readdirp.ReaddirpStream = ReaddirpStream; +readdirp.default = readdirp; + +module.exports = readdirp; diff --git a/node_modules/readdirp/package.json b/node_modules/readdirp/package.json new file mode 100644 index 0000000..dba5388 --- /dev/null +++ b/node_modules/readdirp/package.json @@ -0,0 +1,122 @@ +{ + "name": "readdirp", + "description": "Recursive version of fs.readdir with streaming API.", + "version": "3.6.0", + "homepage": "https://github.com/paulmillr/readdirp", + "repository": { + "type": "git", + "url": "git://github.com/paulmillr/readdirp.git" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/paulmillr/readdirp/issues" + }, + "author": "Thorsten Lorenz (thlorenz.com)", + "contributors": [ + "Thorsten Lorenz (thlorenz.com)", + "Paul Miller (https://paulmillr.com)" + ], + "main": "index.js", + "engines": { + "node": ">=8.10.0" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "recursive", + "fs", + "stream", + "streams", + "readdir", + "filesystem", + "find", + "filter" + ], + "scripts": { + "dtslint": "dtslint", + "nyc": "nyc", + "mocha": "mocha --exit", + "lint": "eslint --report-unused-disable-directives --ignore-path .gitignore .", + "test": "npm run lint && nyc npm run mocha" + }, + "dependencies": { + "picomatch": "^2.2.1" + }, + "devDependencies": { + "@types/node": "^14", + "chai": "^4.2", + "chai-subset": "^1.6", + "dtslint": "^3.3.0", + "eslint": "^7.0.0", + "mocha": "^7.1.1", + "nyc": "^15.0.0", + "rimraf": "^3.0.0", + "typescript": "^4.0.3" + }, + "nyc": { + "reporter": [ + "html", + "text" + ] + }, + "eslintConfig": { + "root": true, + "extends": "eslint:recommended", + "parserOptions": { + "ecmaVersion": 9, + "sourceType": "script" + }, + "env": { + "node": true, + "es6": true + }, + "rules": { + "array-callback-return": "error", + "no-empty": [ + "error", + { + "allowEmptyCatch": true + } + ], + "no-else-return": [ + "error", + { + "allowElseIf": false + } + ], + "no-lonely-if": "error", + "no-var": "error", + "object-shorthand": "error", + "prefer-arrow-callback": [ + "error", + { + "allowNamedFunctions": true + } + ], + "prefer-const": [ + "error", + { + "ignoreReadBeforeAssign": true + } + ], + "prefer-destructuring": [ + "error", + { + "object": true, + "array": false + } + ], + "prefer-spread": "error", + "prefer-template": "error", + "radix": "error", + "semi": "error", + "strict": "error", + "quotes": [ + "error", + "single" + ] + } + } +} diff --git a/node_modules/regexp.prototype.flags/.editorconfig b/node_modules/regexp.prototype.flags/.editorconfig new file mode 100644 index 0000000..eaa2141 --- /dev/null +++ b/node_modules/regexp.prototype.flags/.editorconfig @@ -0,0 +1,13 @@ +root = true + +[*] +indent_style = tab; +insert_final_newline = true; +quote_type = auto; +space_after_anonymous_functions = true; +space_after_control_statements = true; +spaces_around_operators = true; +trim_trailing_whitespace = true; +spaces_in_brackets = false; +end_of_line = lf; + diff --git a/node_modules/regexp.prototype.flags/.eslintrc b/node_modules/regexp.prototype.flags/.eslintrc new file mode 100644 index 0000000..fb009ab --- /dev/null +++ b/node_modules/regexp.prototype.flags/.eslintrc @@ -0,0 +1,20 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "eqeqeq": [2, "allow-null"], + "id-length": 0, + "no-invalid-this": "off", + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "max-lines-per-function": 0, + }, + }, + ], +} diff --git a/node_modules/regexp.prototype.flags/.nycrc b/node_modules/regexp.prototype.flags/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/node_modules/regexp.prototype.flags/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/regexp.prototype.flags/CHANGELOG.md b/node_modules/regexp.prototype.flags/CHANGELOG.md new file mode 100644 index 0000000..aa90d5c --- /dev/null +++ b/node_modules/regexp.prototype.flags/CHANGELOG.md @@ -0,0 +1,241 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.5.3](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.5.2...v1.5.3) - 2024-10-03 + +### Fixed + +- [Fix] avoid unnecessary polyfill [`#31`](https://github.com/es-shims/RegExp.prototype.flags/issues/31) + +### Commits + +- [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` [`9e8bc20`](https://github.com/es-shims/RegExp.prototype.flags/commit/9e8bc20868a6366c08cfa9f37648573b8bcab449) +- [Dev Deps] update `@es-shims/api`, `auto-changelog`, `es-value-fixtures`, `tape` [`c32be8e`](https://github.com/es-shims/RegExp.prototype.flags/commit/c32be8e8bb8b6726376ba82d27a31087b4847444) +- [readme] fix typos [`195c32e`](https://github.com/es-shims/RegExp.prototype.flags/commit/195c32e7f48d09b12428442aaaa5a28a72d56287) +- [Deps] update `call-bind`, `set-function-name` [`207517f`](https://github.com/es-shims/RegExp.prototype.flags/commit/207517f62aa8f6a9c721c6d484c2c7f5a386864a) +- [Dev Deps] update `available-regexp-flags`, `tape` [`b3854f7`](https://github.com/es-shims/RegExp.prototype.flags/commit/b3854f70afa7a5da8c0f4cac40bb8ad8df71d297) +- [Tests] replace `aud` with `npm audit` [`d3ee951`](https://github.com/es-shims/RegExp.prototype.flags/commit/d3ee951c0760b3f9f01e5a953dfef92c8d6fcfb4) +- [Dev Deps] update `hasown` [`9e407c4`](https://github.com/es-shims/RegExp.prototype.flags/commit/9e407c41cd8db52b1fd602ae3117b3cd3e1beecc) +- [Dev Deps] add missing peer dep [`0199bfd`](https://github.com/es-shims/RegExp.prototype.flags/commit/0199bfd69dd140bdee743d6a874d758349aaaaaa) + +## [v1.5.2](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.5.1...v1.5.2) - 2024-02-11 + +### Commits + +- [Tests] increase coverage [`c692c88`](https://github.com/es-shims/RegExp.prototype.flags/commit/c692c88e073f6d17fc5b6b1c740ef1ecb433eb4b) +- [Dev Deps] use `hasown` instead of `has` [`fb5b350`](https://github.com/es-shims/RegExp.prototype.flags/commit/fb5b350122507e4bec68fb417a46f07d062caf77) +- [Dev Deps] update `aud`, `hasown`, `npmignore`, `tape` [`fd0ddd9`](https://github.com/es-shims/RegExp.prototype.flags/commit/fd0ddd9c837c0a8066de37a41eb4f83310f15a57) +- [Deps] update `call-bind`, `define-properties`, `set-function-name` [`ca53f66`](https://github.com/es-shims/RegExp.prototype.flags/commit/ca53f662549b2fbff61323a6d2aa9af15a6c836b) +- [Dev Deps] update `object-inspect`, `tape` [`4491680`](https://github.com/es-shims/RegExp.prototype.flags/commit/449168010d4d63a2cd854dcec9f37efacda19082) +- [Refactor] use `es-errors` [`1d03d22`](https://github.com/es-shims/RegExp.prototype.flags/commit/1d03d225327008aeb6b4b501a4720318d717621e) +- [Fix] properly check for a non-object receiver [`024d442`](https://github.com/es-shims/RegExp.prototype.flags/commit/024d4421edd8922f9acbac35afcfe69a8a3db6a9) +- [Deps] update `call-bind` [`f222ce0`](https://github.com/es-shims/RegExp.prototype.flags/commit/f222ce0925a7431d1d3dd113d803746f07e1175d) + +## [v1.5.1](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.5.0...v1.5.1) - 2023-09-12 + +### Commits + +- [Refactor] use `set-function-name` [`1384147`](https://github.com/es-shims/RegExp.prototype.flags/commit/13841474baf5700de8e3f65fae3670ad1b233483) +- [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `aud`, `available-regexp-flags`, `tape` [`07bf9a2`](https://github.com/es-shims/RegExp.prototype.flags/commit/07bf9a2c354cc41379b01fe5c383233adaaccf0e) +- [Dev Deps] add missing `npmignore` dep [`8ca9dfe`](https://github.com/es-shims/RegExp.prototype.flags/commit/8ca9dfe4da31ef74ee48a4dcf62692eebb8f8fdd) + +## [v1.5.0](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.4.3...v1.5.0) - 2023-04-18 + +### Commits + +- [meta] use `npmignore` to autogenerate an npmignore file [`f7438ad`](https://github.com/es-shims/RegExp.prototype.flags/commit/f7438ad3728128b99daaeb1d3133a40d906d3621) +- [New] add `unicodeSets`/`v` flag [`f922170`](https://github.com/es-shims/RegExp.prototype.flags/commit/f92217039c9c86a61421ce69594e93a546721397) +- [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `aud`, `available-regexp-flags`, `object-inspect`, `tape` [`1203078`](https://github.com/es-shims/RegExp.prototype.flags/commit/12030785e6beb1f06c406a4731714012d93867e2) +- [actions] update rebase action to use reusable workflow [`c562ea2`](https://github.com/es-shims/RegExp.prototype.flags/commit/c562ea20c27442ff30ce65091a313b5e49ae8515) +- [Dev Deps] update `aud`, `object-inspect`, `tape` [`f3ae811`](https://github.com/es-shims/RegExp.prototype.flags/commit/f3ae81109dd08b200dce8bd52c183bc44662c3b4) +- [Deps] update `define-properties`, `functions-have-names` [`2d0476e`](https://github.com/es-shims/RegExp.prototype.flags/commit/2d0476e5eba1e4a9b786f169f3be96c2f5a192b2) +- [Tests] use `for-each` instead of `foreach` [`d9f30da`](https://github.com/es-shims/RegExp.prototype.flags/commit/d9f30dab65ff0185a8688c6e62dc1fe650879cc0) +- [Deps] update `define-properties` [`81c1c20`](https://github.com/es-shims/RegExp.prototype.flags/commit/81c1c2012070c1f4480a9ab55bc0cff206152603) + +## [v1.4.3](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.4.2...v1.4.3) - 2022-04-14 + +### Commits + +- [Fix] when shimmed, name must be `get flags` [`fcefd00`](https://github.com/es-shims/RegExp.prototype.flags/commit/fcefd0039177e9cbcb2ed842d353131ace7a3377) + +## [v1.4.2](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.4.1...v1.4.2) - 2022-04-12 + +### Commits + +- [Fix] ensure `hasIndices` is patched properly, and getter order is correct [`a1af45a`](https://github.com/es-shims/RegExp.prototype.flags/commit/a1af45a8a6f7305b097b83f96ee9fc45abb3e733) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `auto-changelog`, `tape` [`24f5a0c`](https://github.com/es-shims/RegExp.prototype.flags/commit/24f5a0c84f2e7d263ae0e2008def870afd6d5a4f) + +## [v1.4.1](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.4.0...v1.4.1) - 2022-01-13 + +### Commits + +- [Fix] `polyfill`: do not throw in a descriptorless environment [`e2d24e7`](https://github.com/es-shims/RegExp.prototype.flags/commit/e2d24e707a44d958a0b6d3a114effb2f2b475337) + +## [v1.4.0](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.3.2...v1.4.0) - 2022-01-13 + +### Commits + +- [Tests] use `available-regexp-flags` [`95af246`](https://github.com/es-shims/RegExp.prototype.flags/commit/95af2463f1373282087528f8566e20ffae26c3db) +- [New] add `hasIndices`/`d` flag [`89959ca`](https://github.com/es-shims/RegExp.prototype.flags/commit/89959ca1128ea48dcd0ec1416355264425fa3bc5) + +## [v1.3.2](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.3.1...v1.3.2) - 2022-01-13 + +### Commits + +- [actions] reuse common workflows [`6665b5d`](https://github.com/es-shims/RegExp.prototype.flags/commit/6665b5db7c45ce6b987d08ebaf6d2767eec95b94) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`babce94`](https://github.com/es-shims/RegExp.prototype.flags/commit/babce94b5ca96e93e74e384c0a01295943677a3f) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `object-inspect`, `safe-publish-latest`, `tape` [`52132d9`](https://github.com/es-shims/RegExp.prototype.flags/commit/52132d9f3df904864d4cf3fd44892ee563aee524) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `aud`, `auto-changelog`, `object-inspect`, `tape` [`c16687c`](https://github.com/es-shims/RegExp.prototype.flags/commit/c16687c118d374d8997a8d885467507bf943b4bc) +- [actions] update codecov uploader [`0a3c904`](https://github.com/es-shims/RegExp.prototype.flags/commit/0a3c904a9fd1247b3b8e0fb6b451b3fbe97735bd) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` [`3fce7f2`](https://github.com/es-shims/RegExp.prototype.flags/commit/3fce7f27c753440003675d03ae9a7ecfa6a74d30) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`75ca498`](https://github.com/es-shims/RegExp.prototype.flags/commit/75ca49889349fc42e51ea79b2ec7a1996fb3eb18) +- [actions] update workflows [`300f321`](https://github.com/es-shims/RegExp.prototype.flags/commit/300f321984526066656bec791f0bb3861b33cfbc) +- [meta] better `eccheck` command [`5f735ab`](https://github.com/es-shims/RegExp.prototype.flags/commit/5f735ab1b1c87dbd05c0096249160587f166cd51) +- [Dev Deps] update `eslint`, `tape` [`3059637`](https://github.com/es-shims/RegExp.prototype.flags/commit/3059637210eb5c9fa97160ec2f0aea1d1d724eb7) +- [actions] update workflows` [`dbd8ab4`](https://github.com/es-shims/RegExp.prototype.flags/commit/dbd8ab49fa2196dd74791107825c43e4481cdfd2) +- [meta] use `prepublishOnly` script for npm 7+ [`5cc8652`](https://github.com/es-shims/RegExp.prototype.flags/commit/5cc86524a41bf358b6701bcf46e480f0e3e470b4) +- [Fix] use polyfill, not implementation, in main export [`15ab4b8`](https://github.com/es-shims/RegExp.prototype.flags/commit/15ab4b85f3904e48664e26394dc12765ed666da4) +- [meta] remove `audit-level` config, which breaks npm 7 installs [`1cb98ae`](https://github.com/es-shims/RegExp.prototype.flags/commit/1cb98aed731e73d11df5ed3b853b371d35a69f5a) + +## [v1.3.1](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.3.0...v1.3.1) - 2021-01-15 + +### Commits + +- [Tests] run `nyc` on all tests; use `tape` runner; add full es-shims test suite [`047a1e8`](https://github.com/es-shims/RegExp.prototype.flags/commit/047a1e8ff250220254b0e9598d962a56c8ec3ffc) +- [Tests] migrate tests to Github Actions [`e4e391f`](https://github.com/es-shims/RegExp.prototype.flags/commit/e4e391fd3e6f057172994ad0c33ca128568c0b06) +- [meta] use `auto-changelog` for changelog [`afbcd06`](https://github.com/es-shims/RegExp.prototype.flags/commit/afbcd06402e97e975af797e2c1375e35e22e90f2) +- [actions] add Require Allow Edits workflow [`0db5d50`](https://github.com/es-shims/RegExp.prototype.flags/commit/0db5d50cdf59e3e5529024af4f8ce05829edc06d) +- [meta] do not publish github action workflow files [`53f2902`](https://github.com/es-shims/RegExp.prototype.flags/commit/53f29020e5a1f517e91b8cf226ed6bc97eadc090) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`; add `aud` [`05f2a85`](https://github.com/es-shims/RegExp.prototype.flags/commit/05f2a851869069c7911176809028be8491465f86) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`2a197b8`](https://github.com/es-shims/RegExp.prototype.flags/commit/2a197b84916f094946c5cad56ef8e7bb7e8f12ac) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`; add `safe-publish-latest` [`e40bd37`](https://github.com/es-shims/RegExp.prototype.flags/commit/e40bd37de9bb756672832a6c994652965d09b9ae) +- [Refactor] use `call-bind` instead of `es-abstract` [`e6eac90`](https://github.com/es-shims/RegExp.prototype.flags/commit/e6eac9052ebdb4bc28cb83b5d3017a4ed74fe3f1) +- [Deps] update `es-abstract` [`f198075`](https://github.com/es-shims/RegExp.prototype.flags/commit/f198075d6fc075e0d98967af98a512742e6e7e4f) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`2d21727`](https://github.com/es-shims/RegExp.prototype.flags/commit/2d217275d78214b82c7f5cacca85ca2308df83f1) +- [Deps] update `es-abstract` [`7e7ddc6`](https://github.com/es-shims/RegExp.prototype.flags/commit/7e7ddc66174256f6688a857b09c9a02bafcf4866) + +## [v1.3.0](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.2.0...v1.3.0) - 2019-12-14 + +### Commits + +- [Tests] remove `jscs` [`4a09ab4`](https://github.com/es-shims/RegExp.prototype.flags/commit/4a09ab467f62065a1718b0dcc50f7818b5400ab6) +- [Tests] use shared travis-ci configs [`8afa6a9`](https://github.com/es-shims/RegExp.prototype.flags/commit/8afa6a99fd35c19fb49ba630fd17159a5da2a34e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `has`, `tape` [`13a9fc9`](https://github.com/es-shims/RegExp.prototype.flags/commit/13a9fc9d6bc2600681eb3f638668beccf80b843c) +- [Refactor] use `callBind` helper from `es-abstract` [`c3a3727`](https://github.com/es-shims/RegExp.prototype.flags/commit/c3a37276764d99c1e4f7e9467ad636fce8c92c58) +- [actions] add automatic rebasing / merge commit blocking [`51e3f93`](https://github.com/es-shims/RegExp.prototype.flags/commit/51e3f9366d15a07edaf532884948ce74b6827125) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`7e1ee50`](https://github.com/es-shims/RegExp.prototype.flags/commit/7e1ee505df374867c2c04d500aa1c36265161b6f) +- [meta] add `funding` field [`c99cbec`](https://github.com/es-shims/RegExp.prototype.flags/commit/c99cbec1af9b0e0be42e82f164adacf2e1bdee16) +- [New] add `auto` entry point [`1e53e85`](https://github.com/es-shims/RegExp.prototype.flags/commit/1e53e854f663472e74dd0350e0c095df9c2b9c7b) +- [Tests] use `eclint` instead of `editorconfig-tools` [`8600bfe`](https://github.com/es-shims/RegExp.prototype.flags/commit/8600bfed42ab8d294463df482874c344fc079f82) +- [Deps] update `define-properties` [`ad221fa`](https://github.com/es-shims/RegExp.prototype.flags/commit/ad221fa2a26a9c2bc8d274b689cf7a626b58f4e9) + +## [v1.2.0](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.1.1...v1.2.0) - 2017-10-24 + +### Commits + +- [Tests] up to `node` `v8.8`, `v7.10`, `v6.11`, `v4.8`; improve matrix; use `nvm install-latest-npm` so new npm doesn’t break old node [`5a9653d`](https://github.com/es-shims/RegExp.prototype.flags/commit/5a9653d1904eb8ad8baffe43cd065b6f36013e5a) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`; add `has` [`556de86`](https://github.com/es-shims/RegExp.prototype.flags/commit/556de8632bbe7a23279717f7d0b6ee841514fbe1) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` [`726772c`](https://github.com/es-shims/RegExp.prototype.flags/commit/726772c054a499ab7680823c4bd8fa9b048d9420) +- [New] add support for `dotAll` regex flag. [`fcbd64f`](https://github.com/es-shims/RegExp.prototype.flags/commit/fcbd64f84fd974d98384bdb093bf25656eb72e8f) +- [Dev Deps] update `eslint`, `jscs`, `nsp`, `tape`, `@ljharb/eslint-config`, `@es-shims/api` [`0272934`](https://github.com/es-shims/RegExp.prototype.flags/commit/02729344addadc105b9c5e12d90cca85a75d16d6) +- [Dev Deps] update `jscs`, `nsp`, `eslint` [`e4cd264`](https://github.com/es-shims/RegExp.prototype.flags/commit/e4cd264f4afa33ff865325b04791de95696e3ae4) +- [Dev Deps] update `jscs`, `nsp`, `eslint`, `@es-shims/api` [`baf5169`](https://github.com/es-shims/RegExp.prototype.flags/commit/baf51698ac00b31b6a4a6d5646a183a409ad1118) +- [Dev Deps] update `tape`, `nsp`, `eslint`, `@ljharb/eslint-config` [`97cea15`](https://github.com/es-shims/RegExp.prototype.flags/commit/97cea152c20bb0e63e9c5111780f7b4af5d1a0e8) +- [Dev Deps] update `tape`, `discs`, `eslint`, `@ljharb/eslint-config` [`b6872f4`](https://github.com/es-shims/RegExp.prototype.flags/commit/b6872f44c833f6f7faf63881657208b6cd43ef49) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` [`14702cc`](https://github.com/es-shims/RegExp.prototype.flags/commit/14702ccd050029d4e6ea2e59d0912e6bfc16ffc0) +- [Dev Deps] update `jscs`, `@es-shims/api` [`cd060a6`](https://github.com/es-shims/RegExp.prototype.flags/commit/cd060a650db019be5244e1c1b77a29f6d79c89db) +- [Tests] up to `node` `v6.2`, `v5.11` [`14638bd`](https://github.com/es-shims/RegExp.prototype.flags/commit/14638bdbd62d6b6a7c89efb8ec57a7815032b4bb) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`b0a5ffb`](https://github.com/es-shims/RegExp.prototype.flags/commit/b0a5ffb25a76783053652e0d7f835e354f9b29b6) +- [Tests] npm run silently [`35804d4`](https://github.com/es-shims/RegExp.prototype.flags/commit/35804d45dd7f57faab923aaab914e6390813e700) +- [Tests] up to `node` `v5.9`, `v4.4` [`e0fe80d`](https://github.com/es-shims/RegExp.prototype.flags/commit/e0fe80d96783820444d6dea1e6b5739032a50c1b) +- [Tests] up to `node` `v5.7`, `v4.3` [`9739c42`](https://github.com/es-shims/RegExp.prototype.flags/commit/9739c422523571cc439d73a9ecaf5dc2e2643bec) +- [Dev Deps] update `jscs` [`4aa1699`](https://github.com/es-shims/RegExp.prototype.flags/commit/4aa1699a0582b7739f14c6cd8d5ae1a4515bd604) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `@ljharb/eslint-config` [`8bc5e6b`](https://github.com/es-shims/RegExp.prototype.flags/commit/8bc5e6ba5befc8f399e00f3c2d064519457fb57c) +- [Tests] fix npm upgrades on older nodes [`ae00bb9`](https://github.com/es-shims/RegExp.prototype.flags/commit/ae00bb9d979605f41fc598156b5c590923ac8184) +- Only apps should have lockfiles. [`6d14965`](https://github.com/es-shims/RegExp.prototype.flags/commit/6d1496550a962ea8525fb7b62dc4ac99d9513a6d) +- [Tests] use pretest/posttest for better organization [`0520cfd`](https://github.com/es-shims/RegExp.prototype.flags/commit/0520cfda23835fb5bff038a6e5cc530b0ce66985) +- [Tests] up to `node` `v5.5` [`810f62b`](https://github.com/es-shims/RegExp.prototype.flags/commit/810f62b6d2418e843b7c2c225841e9305dbc01ee) +- [Tests] on `node` `v5.3` [`f839662`](https://github.com/es-shims/RegExp.prototype.flags/commit/f839662887cbb1a5e472a9302185355b431c85c1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`78ecaa5`](https://github.com/es-shims/RegExp.prototype.flags/commit/78ecaa5b203a07f76505824f77ce1e5d60d8b0ca) +- [Tests] up to `node` `v5.2` [`c04d762`](https://github.com/es-shims/RegExp.prototype.flags/commit/c04d762a8c09ab544df14c14521f32dac3f67823) +- [Tests] up to `node` `v5.0` [`7c0d5b9`](https://github.com/es-shims/RegExp.prototype.flags/commit/7c0d5b944d9ba30f38227d0750109d582be254e2) +- [Tests] on `node` `v5.10` [`40ddafd`](https://github.com/es-shims/RegExp.prototype.flags/commit/40ddafd83e2e1c959ee8ba24cb296559f2545a0c) +- [Deps] update `define-properties` [`98ea89d`](https://github.com/es-shims/RegExp.prototype.flags/commit/98ea89dc9c41b81b84d4071105048687dab0660e) + +## [v1.1.1](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.1.0...v1.1.1) - 2015-08-16 + +### Commits + +- [Fix] cover the case where there is no descriptor on the prototype [`67014c3`](https://github.com/es-shims/RegExp.prototype.flags/commit/67014c35a93c76e28c4ab5cd3e5a54f7f40c2ddf) + +## [v1.1.0](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.0.1...v1.1.0) - 2015-08-16 + +### Commits + +- Update `jscs`, `eslint`; use my personal shared `eslint` config. [`37ca379`](https://github.com/es-shims/RegExp.prototype.flags/commit/37ca379bc72620fa6785b0a9ca791b160328c236) +- Update `eslint`, `tape`, `editorconfig-tools`, `nsp` [`cb92d6e`](https://github.com/es-shims/RegExp.prototype.flags/commit/cb92d6e8a8c1df5f00a226e11a78f38c6f7c3055) +- Implement the [es-shim API](es-shims/api). [`15eb821`](https://github.com/es-shims/RegExp.prototype.flags/commit/15eb821be2771e03a1341a08483513702118b45c) +- Refactoring to reduce complexity. [`aeb4785`](https://github.com/es-shims/RegExp.prototype.flags/commit/aeb47854f6b00355702104066c63f6eed38b5e81) +- Move implementation to `implementation.js` [`a698925`](https://github.com/es-shims/RegExp.prototype.flags/commit/a698925b4c1c78cd1ed4315b9deb5bb1707d5203) +- Update `eslint`, `jscs` [`277a4a1`](https://github.com/es-shims/RegExp.prototype.flags/commit/277a4a15e663eb823b63743b84645158b9bb9a43) +- Update `nsp`, `eslint` [`c9f3866`](https://github.com/es-shims/RegExp.prototype.flags/commit/c9f3866e25b52050f6bfe3fd0de8849de0271ea4) +- Update `tape`, `eslint` [`a08795b`](https://github.com/es-shims/RegExp.prototype.flags/commit/a08795b688b186fa5a2ec207358d81c16a07d30d) +- Make some things a bit more robust. [`450abb4`](https://github.com/es-shims/RegExp.prototype.flags/commit/450abb48974f10bfd2d9478e7ea1b9d87f004fb9) +- Update `eslint` [`25d898f`](https://github.com/es-shims/RegExp.prototype.flags/commit/25d898f62719b26fea5f9245be141103d4ec58cd) +- Test on latest two `io.js` versions. [`2e17ca3`](https://github.com/es-shims/RegExp.prototype.flags/commit/2e17ca304e12fb5071a091706a4d559b3eac968a) +- All grade A-supported `node`/`iojs` versions now ship with an `npm` that understands `^`. [`4a2a548`](https://github.com/es-shims/RegExp.prototype.flags/commit/4a2a5480c50f30814000684462a8a3b44c87ae2e) +- Update `eslint` [`64df4e0`](https://github.com/es-shims/RegExp.prototype.flags/commit/64df4e0a2d0e2901b57652e30913db797dc0829b) +- Update `eslint` [`ac05ae5`](https://github.com/es-shims/RegExp.prototype.flags/commit/ac05ae509a4a70d107820a749ea6f02784fc41eb) +- Clean up `supportsDescriptors` check. [`e44d0de`](https://github.com/es-shims/RegExp.prototype.flags/commit/e44d0dec9c8415ff9a911b8806e1d245d6919a11) +- [Dev Deps] Update `jscs` [`8741758`](https://github.com/es-shims/RegExp.prototype.flags/commit/87417588f52f1176fc37d7c32221aa85f749aa34) +- Update `tape`, `jscs`, `nsp`, `eslint` [`db1f658`](https://github.com/es-shims/RegExp.prototype.flags/commit/db1f6584b18cc035ef3b5aec556f54e0ee8c639d) +- Test on `io.js` `v2.3` [`18c948f`](https://github.com/es-shims/RegExp.prototype.flags/commit/18c948f033c87ab2657a0395052cbec531c40900) +- Run `travis-ci` tests on `iojs` and `node` v0.12; speed up builds; allow 0.8 failures. [`c37e79f`](https://github.com/es-shims/RegExp.prototype.flags/commit/c37e79f380d87a226a6cdaa5f09f832f5dc21b7d) +- Update `tape`, `jscs`, `eslint` [`4b652bf`](https://github.com/es-shims/RegExp.prototype.flags/commit/4b652bf5f2f0e36a15227d0b4048de91ee6c4433) +- [Dev Deps] Update `tape`, `eslint` [`29d4ac0`](https://github.com/es-shims/RegExp.prototype.flags/commit/29d4ac0bea16c6a9f611cb15baccd30449f30a91) +- Test up to `io.js` `v2.1` [`9f9e342`](https://github.com/es-shims/RegExp.prototype.flags/commit/9f9e34295ced1b288dea08e0a66dffd2bc03ff8b) +- Update `covert`, `jscs` [`c98f3b4`](https://github.com/es-shims/RegExp.prototype.flags/commit/c98f3b47f01f317e8a589486dfaee482c66b8b64) +- Update `jscs` [`9e5e220`](https://github.com/es-shims/RegExp.prototype.flags/commit/9e5e220be6ec5d5b9b658235287e35bded580b06) +- [Dev Deps] update `tape` [`cdd3af2`](https://github.com/es-shims/RegExp.prototype.flags/commit/cdd3af21507b01aa524f8b87f158dfc8a8153c85) +- [Dev Deps] update `tape` [`d42d0bf`](https://github.com/es-shims/RegExp.prototype.flags/commit/d42d0bf28f8da2cb47fff49283a07a693f8cb626) +- Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. [`a5e7453`](https://github.com/es-shims/RegExp.prototype.flags/commit/a5e745375c01e9f90ff632c55a5b44b6ada38217) +- Update `tape` [`2a675ec`](https://github.com/es-shims/RegExp.prototype.flags/commit/2a675ec707a9d89aea403d0b9a723ea531e50c2d) +- Test on `io.js` `v2.5` [`448cbdb`](https://github.com/es-shims/RegExp.prototype.flags/commit/448cbdb7df47e52677daea4e0c41e892ad8770e4) +- Test on `io.js` `v2.4` [`948e511`](https://github.com/es-shims/RegExp.prototype.flags/commit/948e51129c01147ffe4dedc3a7d4980128d0cf73) +- Test on `io.js` `v2.2` [`4793278`](https://github.com/es-shims/RegExp.prototype.flags/commit/4793278f5aca187e36b42b08fc1388d8021400e2) +- Update `eslint` [`0f463da`](https://github.com/es-shims/RegExp.prototype.flags/commit/0f463daa14a193ed94b16c46832074d63e861c91) +- Update `eslint` [`5a16967`](https://github.com/es-shims/RegExp.prototype.flags/commit/5a16967db71bb8a24c81a27ee366f0b02b663e34) +- Test on `io.js` `v3.0` [`7ba8706`](https://github.com/es-shims/RegExp.prototype.flags/commit/7ba87064bc8520d34a9560bea8e366d70c93dbbb) +- Test on `iojs-v1.2` [`b521e09`](https://github.com/es-shims/RegExp.prototype.flags/commit/b521e099b7de48cfbdd6860265eb5e972d2859a5) + +## [v1.0.1](https://github.com/es-shims/RegExp.prototype.flags/compare/v1.0.0...v1.0.1) - 2014-12-13 + +### Merged + +- Match the spec properly: throw when not an object; make getter generic. [`#3`](https://github.com/es-shims/RegExp.prototype.flags/pull/3) + +### Fixed + +- Match the spec properly [`#1`](https://github.com/es-shims/RegExp.prototype.flags/issues/1) + +### Commits + +- Speed up the “is object” check in case of `null` or `undefined` [`77137f9`](https://github.com/es-shims/RegExp.prototype.flags/commit/77137f99449c9b6583cdfda295a00b832dfd45f3) + +## v1.0.0 - 2014-12-10 + +### Commits + +- Adding dotfiles [`313812e`](https://github.com/es-shims/RegExp.prototype.flags/commit/313812e1d8ff42a13dbc8689f2e719324c46c9ca) +- Tests [`625a042`](https://github.com/es-shims/RegExp.prototype.flags/commit/625a042220a3152b49608fb6f187f67bff02b6fb) +- Add package.json [`8b98257`](https://github.com/es-shims/RegExp.prototype.flags/commit/8b98257f900d0a73c8eb3805b9b01999e05e880a) +- Adding the README [`884798b`](https://github.com/es-shims/RegExp.prototype.flags/commit/884798b710d5a85bc6d9a6879f509766e2e57c0e) +- Implementation. [`4186cc9`](https://github.com/es-shims/RegExp.prototype.flags/commit/4186cc9d9a7533f78d88be976f0a8a2757604fc5) +- Adding LICENSE and CHANGELOG [`f87fa81`](https://github.com/es-shims/RegExp.prototype.flags/commit/f87fa8126cc6c39747fbe0dc6cb40ca0ff77fbbc) +- Fixing README URLs [`b821703`](https://github.com/es-shims/RegExp.prototype.flags/commit/b821703d5e5b01ee4f526f15c8e525645cf95ef7) +- Clean up dependencies; update `tape`, `jscs`, `nsp` [`0e13fc1`](https://github.com/es-shims/RegExp.prototype.flags/commit/0e13fc12df09f3a7ac30116ef13bba820c220730) +- Initial commit. [`8a9e35e`](https://github.com/es-shims/RegExp.prototype.flags/commit/8a9e35e15f65c9640e64ee14fab190a60993efaa) diff --git a/node_modules/regexp.prototype.flags/LICENSE b/node_modules/regexp.prototype.flags/LICENSE new file mode 100644 index 0000000..e5956a8 --- /dev/null +++ b/node_modules/regexp.prototype.flags/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (C) 2014 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/node_modules/regexp.prototype.flags/README.md b/node_modules/regexp.prototype.flags/README.md new file mode 100644 index 0000000..ca5f282 --- /dev/null +++ b/node_modules/regexp.prototype.flags/README.md @@ -0,0 +1,55 @@ +RegExp.prototype.flags [![Version Badge][npm-version-svg]][package-url] + +[![Build Status][travis-svg]][travis-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +[![browser support][testling-svg]][testling-url] + +An ES6 spec-compliant `RegExp.prototype.flags` shim. Invoke its "shim" method to shim RegExp.prototype.flags if it is unavailable. +*Note*: `RegExp#flags` requires a true ES5 environment - specifically, one with ES5 getters. + +This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES5-supported environment and complies with the [spec](http://www.ecma-international.org/ecma-262/6.0/#sec-get-regexp.prototype.flags). + +Most common usage: +```js +var flags = require('regexp.prototype.flags'); +var assert = require('assert'); + +assert(flags(/a/) === ''); +assert(flags(new RegExp('a')) === ''); +assert(flags(/a/mig) === 'gim'); +assert(flags(new RegExp('a', 'mig')) === 'gim'); + +if (!RegExp.prototype.flags) { + flags.shim(); +} + +assert(flags(/a/) === /a/.flags); +assert(flags(new RegExp('a')) === new RegExp('a').flags); +assert(flags(/a/mig) === /a/mig.flags); +assert(flags(new RegExp('a', 'mig')) === new RegExp('a', 'mig').flags); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.com/package/regexp.prototype.flags +[npm-version-svg]: http://versionbadg.es/es-shims/RegExp.prototype.flags.svg +[travis-svg]: https://travis-ci.org/es-shims/RegExp.prototype.flags.svg +[travis-url]: https://travis-ci.org/es-shims/RegExp.prototype.flags +[deps-svg]: https://david-dm.org/es-shims/RegExp.prototype.flags.svg +[deps-url]: https://david-dm.org/es-shims/RegExp.prototype.flags +[dev-deps-svg]: https://david-dm.org/es-shims/RegExp.prototype.flags/dev-status.svg +[dev-deps-url]: https://david-dm.org/es-shims/RegExp.prototype.flags#info=devDependencies +[testling-svg]: https://ci.testling.com/es-shims/RegExp.prototype.flags.png +[testling-url]: https://ci.testling.com/es-shims/RegExp.prototype.flags +[npm-badge-png]: https://nodei.co/npm/regexp.prototype.flags.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/regexp.prototype.flags.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/regexp.prototype.flags.svg +[downloads-url]: http://npm-stat.com/charts.html?package=regexp.prototype.flags diff --git a/node_modules/regexp.prototype.flags/auto.js b/node_modules/regexp.prototype.flags/auto.js new file mode 100644 index 0000000..8ebf606 --- /dev/null +++ b/node_modules/regexp.prototype.flags/auto.js @@ -0,0 +1,3 @@ +'use strict'; + +require('./shim')(); diff --git a/node_modules/regexp.prototype.flags/implementation.js b/node_modules/regexp.prototype.flags/implementation.js new file mode 100644 index 0000000..4005503 --- /dev/null +++ b/node_modules/regexp.prototype.flags/implementation.js @@ -0,0 +1,39 @@ +'use strict'; + +var setFunctionName = require('set-function-name'); +var $TypeError = require('es-errors/type'); + +var $Object = Object; + +module.exports = setFunctionName(function flags() { + if (this == null || this !== $Object(this)) { + throw new $TypeError('RegExp.prototype.flags getter called on non-object'); + } + var result = ''; + if (this.hasIndices) { + result += 'd'; + } + if (this.global) { + result += 'g'; + } + if (this.ignoreCase) { + result += 'i'; + } + if (this.multiline) { + result += 'm'; + } + if (this.dotAll) { + result += 's'; + } + if (this.unicode) { + result += 'u'; + } + if (this.unicodeSets) { + result += 'v'; + } + if (this.sticky) { + result += 'y'; + } + return result; +}, 'get flags', true); + diff --git a/node_modules/regexp.prototype.flags/index.js b/node_modules/regexp.prototype.flags/index.js new file mode 100644 index 0000000..d6054c7 --- /dev/null +++ b/node_modules/regexp.prototype.flags/index.js @@ -0,0 +1,18 @@ +'use strict'; + +var define = require('define-properties'); +var callBind = require('call-bind'); + +var implementation = require('./implementation'); +var getPolyfill = require('./polyfill'); +var shim = require('./shim'); + +var flagsBound = callBind(getPolyfill()); + +define(flagsBound, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = flagsBound; diff --git a/node_modules/regexp.prototype.flags/package.json b/node_modules/regexp.prototype.flags/package.json new file mode 100644 index 0000000..fb4c9e8 --- /dev/null +++ b/node_modules/regexp.prototype.flags/package.json @@ -0,0 +1,103 @@ +{ + "name": "regexp.prototype.flags", + "version": "1.5.3", + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "description": "ES6 spec-compliant RegExp.prototype.flags shim.", + "license": "MIT", + "main": "index.js", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run lint", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "tests-only": "nyc tape 'test/**/*.js'", + "prelint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "evalmd README.md && es-shim-api --bound", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/es-shims/RegExp.prototype.flags.git" + }, + "keywords": [ + "RegExp.prototype.flags", + "regex", + "regular expression", + "ES6", + "shim", + "flag", + "flags", + "regexp", + "RegExp#flags", + "polyfill", + "es-shim API" + ], + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-errors": "^1.3.0", + "set-function-name": "^2.0.2" + }, + "devDependencies": { + "@es-shims/api": "^2.5.1", + "@ljharb/eslint-config": "^21.1.1", + "auto-changelog": "^2.5.0", + "available-regexp-flags": "^1.0.4", + "eclint": "^2.8.1", + "encoding": "^0.1.13", + "es-value-fixtures": "^1.5.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "functions-have-names": "^1.2.3", + "has-strict-mode": "^1.0.1", + "hasown": "^2.0.2", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/9.0..latest", + "firefox/4.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/11.6..latest", + "opera/next", + "safari/5.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/regexp.prototype.flags/polyfill.js b/node_modules/regexp.prototype.flags/polyfill.js new file mode 100644 index 0000000..8c78882 --- /dev/null +++ b/node_modules/regexp.prototype.flags/polyfill.js @@ -0,0 +1,39 @@ +'use strict'; + +var implementation = require('./implementation'); + +var supportsDescriptors = require('define-properties').supportsDescriptors; +var $gOPD = Object.getOwnPropertyDescriptor; + +module.exports = function getPolyfill() { + if (supportsDescriptors && (/a/mig).flags === 'gim') { + var descriptor = $gOPD(RegExp.prototype, 'flags'); + if ( + descriptor + && typeof descriptor.get === 'function' + && 'dotAll' in RegExp.prototype + && 'hasIndices' in RegExp.prototype + ) { + /* eslint getter-return: 0 */ + var calls = ''; + var o = {}; + Object.defineProperty(o, 'hasIndices', { + get: function () { + calls += 'd'; + } + }); + Object.defineProperty(o, 'sticky', { + get: function () { + calls += 'y'; + } + }); + + descriptor.get.call(o); + + if (calls === 'dy') { + return descriptor.get; + } + } + } + return implementation; +}; diff --git a/node_modules/regexp.prototype.flags/shim.js b/node_modules/regexp.prototype.flags/shim.js new file mode 100644 index 0000000..3ec77c1 --- /dev/null +++ b/node_modules/regexp.prototype.flags/shim.js @@ -0,0 +1,26 @@ +'use strict'; + +var supportsDescriptors = require('define-properties').supportsDescriptors; +var getPolyfill = require('./polyfill'); +var gOPD = Object.getOwnPropertyDescriptor; +var defineProperty = Object.defineProperty; +var TypeErr = TypeError; +var getProto = Object.getPrototypeOf; +var regex = /a/; + +module.exports = function shimFlags() { + if (!supportsDescriptors || !getProto) { + throw new TypeErr('RegExp.prototype.flags requires a true ES5 environment that supports property descriptors'); + } + var polyfill = getPolyfill(); + var proto = getProto(regex); + var descriptor = gOPD(proto, 'flags'); + if (!descriptor || descriptor.get !== polyfill) { + defineProperty(proto, 'flags', { + configurable: true, + enumerable: false, + get: polyfill + }); + } + return polyfill; +}; diff --git a/node_modules/regexp.prototype.flags/test/builtin.js b/node_modules/regexp.prototype.flags/test/builtin.js new file mode 100644 index 0000000..ef3dac7 --- /dev/null +++ b/node_modules/regexp.prototype.flags/test/builtin.js @@ -0,0 +1,46 @@ +'use strict'; + +var test = require('tape'); +var defineProperties = require('define-properties'); +var callBind = require('call-bind'); + +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = require('functions-have-names')(); +var functionsHaveConfigurableNames = require('functions-have-names').functionsHaveConfigurableNames(); +var hasStrictMode = require('has-strict-mode')(); + +var runTests = require('./tests'); + +test('builtin', function (t) { + var descriptor = Object.getOwnPropertyDescriptor(RegExp.prototype, 'flags'); + + t.equal(descriptor.get.length, 0, 'RegExp#flags getter has a length of 0'); + + t.test('Function name', { skip: !functionsHaveNames }, function (st) { + st.equal(descriptor.get.name, functionsHaveConfigurableNames ? 'get flags' : 'flags', 'RegExp#flags getter has name "get flags" (or "flags" if function names are not configurable)'); + st.end(); + }); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(RegExp.prototype, 'flags'), 'RegExp#flags is not enumerable'); + et.end(); + }); + + t.test('bad array/this value', { skip: !hasStrictMode }, function (st) { + st['throws'](function () { return descriptor.get.call(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { return descriptor.get.call(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + t.test('has the correct descriptor', function (st) { + st.equal(descriptor.configurable, true); + st.equal(descriptor.enumerable, false); + st.equal(typeof descriptor.get, 'function'); + st.equal(descriptor.set, undefined); + st.end(); + }); + + runTests(callBind(descriptor.get), t); + + t.end(); +}); diff --git a/node_modules/regexp.prototype.flags/test/implementation.js b/node_modules/regexp.prototype.flags/test/implementation.js new file mode 100644 index 0000000..1e3a714 --- /dev/null +++ b/node_modules/regexp.prototype.flags/test/implementation.js @@ -0,0 +1,20 @@ +'use strict'; + +var flags = require('../implementation'); +var callBind = require('call-bind'); +var test = require('tape'); +var hasStrictMode = require('has-strict-mode')(); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad array/this value', { skip: !hasStrictMode }, function (st) { + /* eslint no-useless-call: 0 */ + st['throws'](function () { flags.call(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { flags.call(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(callBind(flags), t); + + t.end(); +}); diff --git a/node_modules/regexp.prototype.flags/test/index.js b/node_modules/regexp.prototype.flags/test/index.js new file mode 100644 index 0000000..10d1071 --- /dev/null +++ b/node_modules/regexp.prototype.flags/test/index.js @@ -0,0 +1,17 @@ +'use strict'; + +var flags = require('../'); +var test = require('tape'); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad array/this value', function (st) { + st['throws'](function () { flags(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { flags(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(flags, t); + + t.end(); +}); diff --git a/node_modules/regexp.prototype.flags/test/shimmed.js b/node_modules/regexp.prototype.flags/test/shimmed.js new file mode 100644 index 0000000..059e0e1 --- /dev/null +++ b/node_modules/regexp.prototype.flags/test/shimmed.js @@ -0,0 +1,48 @@ +'use strict'; + +require('../auto'); + +var test = require('tape'); +var defineProperties = require('define-properties'); +var callBind = require('call-bind'); + +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = require('functions-have-names')(); +var functionsHaveConfigurableNames = require('functions-have-names').functionsHaveConfigurableNames(); +var hasStrictMode = require('has-strict-mode')(); + +var runTests = require('./tests'); + +test('shimmed', function (t) { + var descriptor = Object.getOwnPropertyDescriptor(RegExp.prototype, 'flags'); + + t.equal(descriptor.get.length, 0, 'RegExp#flags getter has a length of 0'); + + t.test('Function name', { skip: !functionsHaveNames }, function (st) { + st.equal(descriptor.get.name, functionsHaveConfigurableNames ? 'get flags' : 'flags', 'RegExp#flags getter has name "get flags" (or "flags" if function names are not configurable)'); + st.end(); + }); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(RegExp.prototype, 'flags'), 'RegExp#flags is not enumerable'); + et.end(); + }); + + t.test('bad array/this value', { skip: !hasStrictMode }, function (st) { + st['throws'](function () { return descriptor.get.call(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { return descriptor.get.call(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + t.test('has the correct descriptor', function (st) { + st.equal(descriptor.configurable, true); + st.equal(descriptor.enumerable, false); + st.equal(typeof descriptor.get, 'function'); + st.equal(descriptor.set, undefined); + st.end(); + }); + + runTests(callBind(descriptor.get), t); + + t.end(); +}); diff --git a/node_modules/regexp.prototype.flags/test/tests.js b/node_modules/regexp.prototype.flags/test/tests.js new file mode 100644 index 0000000..fbe4194 --- /dev/null +++ b/node_modules/regexp.prototype.flags/test/tests.js @@ -0,0 +1,143 @@ +'use strict'; + +var hasOwn = require('hasown'); +var inspect = require('object-inspect'); +var supportsDescriptors = require('define-properties').supportsDescriptors; +var v = require('es-value-fixtures'); + +var forEach = require('for-each'); +var availableFlags = require('available-regexp-flags'); +var regexProperties = require('available-regexp-flags/properties'); + +var sortedFlags = availableFlags.slice().sort(function (a, b) { return a.localeCompare(b); }).join(''); + +var getRegexLiteral = function (stringRegex) { + try { + // eslint-disable-next-line no-new-func + return Function('return ' + stringRegex + ';')(); + } catch (e) { /**/ } + return null; +}; + +module.exports = function runTests(flags, t) { + forEach(v.primitives, function (nonObject) { + t['throws']( + function () { flags(nonObject); }, + TypeError, + 'throws when called with a non-object receiver: ' + inspect(nonObject) + ); + }); + + t.equal(flags(/a/g), 'g', 'flags(/a/g) !== "g"'); + t.equal(flags(/a/gmi), 'gim', 'flags(/a/gmi) !== "gim"'); + t.equal(flags(new RegExp('a', 'gmi')), 'gim', 'flags(new RegExp("a", "gmi")) !== "gim"'); + t.equal(flags(/a/), '', 'flags(/a/) !== ""'); + t.equal(flags(new RegExp('a')), '', 'flags(new RegExp("a")) !== ""'); + + forEach(availableFlags, function (flag) { + var property = regexProperties[flag]; + t.test(property + ' flag', function (st) { + st.equal(flags(getRegexLiteral('/a/' + flag)), flag, 'flags(/a/' + flag + ') !== ' + inspect(flag)); + st.equal(flags(new RegExp('a', flag)), flag, 'flags(new RegExp("a", ' + inspect(flag) + ')) !== ' + inspect(flag)); + st.end(); + }); + }); + + t.test('sorting', function (st) { + st.equal(flags(/a/gim), 'gim', 'flags(/a/gim) !== "gim"'); + st.equal(flags(/a/mig), 'gim', 'flags(/a/mig) !== "gim"'); + st.equal(flags(/a/mgi), 'gim', 'flags(/a/mgi) !== "gim"'); + if (hasOwn(RegExp.prototype, 'sticky')) { + st.equal(flags(getRegexLiteral('/a/gyim')), 'gimy', 'flags(/a/gyim) !== "gimy"'); + } + if (hasOwn(RegExp.prototype, 'unicode')) { + st.equal(flags(getRegexLiteral('/a/ugmi')), 'gimu', 'flags(/a/ugmi) !== "gimu"'); + } + if (hasOwn(RegExp.prototype, 'dotAll')) { + st.equal(flags(getRegexLiteral('/a/sgmi')), 'gims', 'flags(/a/sgmi) !== "gims"'); + } + + var randomFlags = availableFlags.slice().sort(function () { return Math.random() > 0.5 ? 1 : -1; }).join('').replace('v', ''); + st.equal( + flags(getRegexLiteral('/a/' + randomFlags)), + sortedFlags.replace('v', ''), + 'random: flags(/a/' + randomFlags + ') === ' + inspect(sortedFlags) + ); + + st.end(); + }); + + t.test('basic examples', function (st) { + st.equal(flags(/a/g), 'g', '(/a/g).flags !== "g"'); + st.equal(flags(/a/gmi), 'gim', '(/a/gmi).flags !== "gim"'); + st.equal(flags(new RegExp('a', 'gmi')), 'gim', 'new RegExp("a", "gmi").flags !== "gim"'); + st.equal(flags(/a/), '', '(/a/).flags !== ""'); + st.equal(flags(new RegExp('a')), '', 'new RegExp("a").flags !== ""'); + + st.end(); + }); + + t.test('generic flags', function (st) { + st.equal(flags({}), ''); + st.equal(flags({ ignoreCase: true }), 'i'); + st.equal(flags({ dotAll: 1, global: 0, sticky: 1, unicode: 1 }), 'suy'); + st.equal(flags({ __proto__: { multiline: true } }), 'm'); + + var obj = {}; + forEach(availableFlags, function (flag) { + if (flag !== 'v') { + obj[regexProperties[flag]] = true; + } + }); + st.equal(flags(obj), sortedFlags.replace('v', ''), 'an object with every available flag: ' + sortedFlags); + + st.end(); + }); + + t.test('getters', { skip: !supportsDescriptors }, function (st) { + /* eslint getter-return: 0 */ + var calls = ''; + var re = {}; + Object.defineProperty(re, 'hasIndices', { + get: function () { + calls += 'd'; + } + }); + Object.defineProperty(re, 'global', { + get: function () { + calls += 'g'; + } + }); + Object.defineProperty(re, 'ignoreCase', { + get: function () { + calls += 'i'; + } + }); + Object.defineProperty(re, 'multiline', { + get: function () { + calls += 'm'; + } + }); + Object.defineProperty(re, 'dotAll', { + get: function () { + calls += 's'; + } + }); + Object.defineProperty(re, 'unicode', { + get: function () { + calls += 'u'; + } + }); + Object.defineProperty(re, 'sticky', { + get: function () { + calls += 'y'; + } + }); + + flags(re); + + st.equal(calls, 'dgimsuy', 'getters are called in expected order'); + + st.end(); + }); +}; diff --git a/node_modules/resolve/.editorconfig b/node_modules/resolve/.editorconfig new file mode 100644 index 0000000..d63f0bb --- /dev/null +++ b/node_modules/resolve/.editorconfig @@ -0,0 +1,37 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 200 + +[*.js] +block_comment_start = /* +block_comment = * +block_comment_end = */ + +[*.yml] +indent_size = 1 + +[package.json] +indent_style = tab + +[lib/core.json] +indent_style = tab + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[{*.json,Makefile}] +max_line_length = off + +[test/{dotdot,resolver,module_dir,multirepo,node_path,pathfilter,precedence}/**/*] +indent_style = off +indent_size = off +max_line_length = off +insert_final_newline = off diff --git a/node_modules/resolve/.eslintrc b/node_modules/resolve/.eslintrc new file mode 100644 index 0000000..ad05dd8 --- /dev/null +++ b/node_modules/resolve/.eslintrc @@ -0,0 +1,65 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "indent": [2, 4], + "strict": 0, + "complexity": 0, + "consistent-return": 0, + "curly": 0, + "dot-notation": [2, { "allowKeywords": true }], + "func-name-matching": 0, + "func-style": 0, + "global-require": 1, + "id-length": [2, { "min": 1, "max": 40 }], + "max-lines": [2, 350], + "max-lines-per-function": 0, + "max-nested-callbacks": 0, + "max-params": 0, + "max-statements-per-line": [2, { "max": 2 }], + "max-statements": 0, + "no-magic-numbers": 0, + "no-shadow": 0, + "no-use-before-define": 0, + "sort-keys": 0, + }, + "overrides": [ + { + "files": "bin/**", + "rules": { + "no-process-exit": "off", + }, + }, + { + "files": "example/**", + "rules": { + "no-console": 0, + }, + }, + { + "files": "test/resolver/nested_symlinks/mylib/*.js", + "rules": { + "no-throw-literal": 0, + }, + }, + { + "files": "test/**", + "parserOptions": { + "ecmaVersion": 5, + "allowReserved": false, + }, + "rules": { + "dot-notation": [2, { "allowPattern": "throws" }], + "max-lines": 0, + "max-lines-per-function": 0, + "no-unused-vars": [2, { "vars": "all", "args": "none" }], + }, + }, + ], + + "ignorePatterns": [ + "./test/resolver/malformed_package_json/package.json", + ], +} diff --git a/node_modules/resolve/.github/FUNDING.yml b/node_modules/resolve/.github/FUNDING.yml new file mode 100644 index 0000000..d9c0595 --- /dev/null +++ b/node_modules/resolve/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/resolve +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/resolve/LICENSE b/node_modules/resolve/LICENSE new file mode 100644 index 0000000..ff4fce2 --- /dev/null +++ b/node_modules/resolve/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2012 James Halliday + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/resolve/SECURITY.md b/node_modules/resolve/SECURITY.md new file mode 100644 index 0000000..82e4285 --- /dev/null +++ b/node_modules/resolve/SECURITY.md @@ -0,0 +1,3 @@ +# Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. diff --git a/node_modules/resolve/async.js b/node_modules/resolve/async.js new file mode 100644 index 0000000..f38c581 --- /dev/null +++ b/node_modules/resolve/async.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/async'); diff --git a/node_modules/resolve/bin/resolve b/node_modules/resolve/bin/resolve new file mode 100755 index 0000000..21d1a87 --- /dev/null +++ b/node_modules/resolve/bin/resolve @@ -0,0 +1,50 @@ +#!/usr/bin/env node + +'use strict'; + +var path = require('path'); +var fs = require('fs'); + +if ( + String(process.env.npm_lifecycle_script).slice(0, 8) !== 'resolve ' + && ( + !process.argv + || process.argv.length < 2 + || (process.argv[1] !== __filename && fs.statSync(process.argv[1]).ino !== fs.statSync(__filename).ino) + || (process.env.npm_lifecycle_event !== 'npx' && process.env._ && fs.realpathSync(path.resolve(process.env._)) !== __filename) + ) +) { + console.error('Error: `resolve` must be run directly as an executable'); + process.exit(1); +} + +var supportsPreserveSymlinkFlag = require('supports-preserve-symlinks-flag'); + +var preserveSymlinks = false; +for (var i = 2; i < process.argv.length; i += 1) { + if (process.argv[i].slice(0, 2) === '--') { + if (supportsPreserveSymlinkFlag && process.argv[i] === '--preserve-symlinks') { + preserveSymlinks = true; + } else if (process.argv[i].length > 2) { + console.error('Unknown argument ' + process.argv[i].replace(/[=].*$/, '')); + process.exit(2); + } + process.argv.splice(i, 1); + i -= 1; + if (process.argv[i] === '--') { break; } // eslint-disable-line no-restricted-syntax + } +} + +if (process.argv.length < 3) { + console.error('Error: `resolve` expects a specifier'); + process.exit(2); +} + +var resolve = require('../'); + +var result = resolve.sync(process.argv[2], { + basedir: process.cwd(), + preserveSymlinks: preserveSymlinks +}); + +console.log(result); diff --git a/node_modules/resolve/example/async.js b/node_modules/resolve/example/async.js new file mode 100644 index 0000000..20e65dc --- /dev/null +++ b/node_modules/resolve/example/async.js @@ -0,0 +1,5 @@ +var resolve = require('../'); +resolve('tap', { basedir: __dirname }, function (err, res) { + if (err) console.error(err); + else console.log(res); +}); diff --git a/node_modules/resolve/example/sync.js b/node_modules/resolve/example/sync.js new file mode 100644 index 0000000..54b2cc1 --- /dev/null +++ b/node_modules/resolve/example/sync.js @@ -0,0 +1,3 @@ +var resolve = require('../'); +var res = resolve.sync('tap', { basedir: __dirname }); +console.log(res); diff --git a/node_modules/resolve/index.js b/node_modules/resolve/index.js new file mode 100644 index 0000000..125d814 --- /dev/null +++ b/node_modules/resolve/index.js @@ -0,0 +1,6 @@ +var async = require('./lib/async'); +async.core = require('./lib/core'); +async.isCore = require('./lib/is-core'); +async.sync = require('./lib/sync'); + +module.exports = async; diff --git a/node_modules/resolve/lib/async.js b/node_modules/resolve/lib/async.js new file mode 100644 index 0000000..60d2555 --- /dev/null +++ b/node_modules/resolve/lib/async.js @@ -0,0 +1,329 @@ +var fs = require('fs'); +var getHomedir = require('./homedir'); +var path = require('path'); +var caller = require('./caller'); +var nodeModulesPaths = require('./node-modules-paths'); +var normalizeOptions = require('./normalize-options'); +var isCore = require('is-core-module'); + +var realpathFS = process.platform !== 'win32' && fs.realpath && typeof fs.realpath.native === 'function' ? fs.realpath.native : fs.realpath; + +var homedir = getHomedir(); +var defaultPaths = function () { + return [ + path.join(homedir, '.node_modules'), + path.join(homedir, '.node_libraries') + ]; +}; + +var defaultIsFile = function isFile(file, cb) { + fs.stat(file, function (err, stat) { + if (!err) { + return cb(null, stat.isFile() || stat.isFIFO()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); +}; + +var defaultIsDir = function isDirectory(dir, cb) { + fs.stat(dir, function (err, stat) { + if (!err) { + return cb(null, stat.isDirectory()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); +}; + +var defaultRealpath = function realpath(x, cb) { + realpathFS(x, function (realpathErr, realPath) { + if (realpathErr && realpathErr.code !== 'ENOENT') cb(realpathErr); + else cb(null, realpathErr ? x : realPath); + }); +}; + +var maybeRealpath = function maybeRealpath(realpath, x, opts, cb) { + if (opts && opts.preserveSymlinks === false) { + realpath(x, cb); + } else { + cb(null, x); + } +}; + +var defaultReadPackage = function defaultReadPackage(readFile, pkgfile, cb) { + readFile(pkgfile, function (readFileErr, body) { + if (readFileErr) cb(readFileErr); + else { + try { + var pkg = JSON.parse(body); + cb(null, pkg); + } catch (jsonErr) { + cb(null); + } + } + }); +}; + +var getPackageCandidates = function getPackageCandidates(x, start, opts) { + var dirs = nodeModulesPaths(start, opts, x); + for (var i = 0; i < dirs.length; i++) { + dirs[i] = path.join(dirs[i], x); + } + return dirs; +}; + +module.exports = function resolve(x, options, callback) { + var cb = callback; + var opts = options; + if (typeof options === 'function') { + cb = opts; + opts = {}; + } + if (typeof x !== 'string') { + var err = new TypeError('Path must be a string.'); + return process.nextTick(function () { + cb(err); + }); + } + + opts = normalizeOptions(x, opts); + + var isFile = opts.isFile || defaultIsFile; + var isDirectory = opts.isDirectory || defaultIsDir; + var readFile = opts.readFile || fs.readFile; + var realpath = opts.realpath || defaultRealpath; + var readPackage = opts.readPackage || defaultReadPackage; + if (opts.readFile && opts.readPackage) { + var conflictErr = new TypeError('`readFile` and `readPackage` are mutually exclusive.'); + return process.nextTick(function () { + cb(conflictErr); + }); + } + var packageIterator = opts.packageIterator; + + var extensions = opts.extensions || ['.js']; + var includeCoreModules = opts.includeCoreModules !== false; + var basedir = opts.basedir || path.dirname(caller()); + var parent = opts.filename || basedir; + + opts.paths = opts.paths || defaultPaths(); + + // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory + var absoluteStart = path.resolve(basedir); + + maybeRealpath( + realpath, + absoluteStart, + opts, + function (err, realStart) { + if (err) cb(err); + else init(realStart); + } + ); + + var res; + function init(basedir) { + if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { + res = path.resolve(basedir, x); + if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; + if ((/\/$/).test(x) && res === basedir) { + loadAsDirectory(res, opts.package, onfile); + } else loadAsFile(res, opts.package, onfile); + } else if (includeCoreModules && isCore(x)) { + return cb(null, x); + } else loadNodeModules(x, basedir, function (err, n, pkg) { + if (err) cb(err); + else if (n) { + return maybeRealpath(realpath, n, opts, function (err, realN) { + if (err) { + cb(err); + } else { + cb(null, realN, pkg); + } + }); + } else { + var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + moduleError.code = 'MODULE_NOT_FOUND'; + cb(moduleError); + } + }); + } + + function onfile(err, m, pkg) { + if (err) cb(err); + else if (m) cb(null, m, pkg); + else loadAsDirectory(res, function (err, d, pkg) { + if (err) cb(err); + else if (d) { + maybeRealpath(realpath, d, opts, function (err, realD) { + if (err) { + cb(err); + } else { + cb(null, realD, pkg); + } + }); + } else { + var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + moduleError.code = 'MODULE_NOT_FOUND'; + cb(moduleError); + } + }); + } + + function loadAsFile(x, thePackage, callback) { + var loadAsFilePackage = thePackage; + var cb = callback; + if (typeof loadAsFilePackage === 'function') { + cb = loadAsFilePackage; + loadAsFilePackage = undefined; + } + + var exts = [''].concat(extensions); + load(exts, x, loadAsFilePackage); + + function load(exts, x, loadPackage) { + if (exts.length === 0) return cb(null, undefined, loadPackage); + var file = x + exts[0]; + + var pkg = loadPackage; + if (pkg) onpkg(null, pkg); + else loadpkg(path.dirname(file), onpkg); + + function onpkg(err, pkg_, dir) { + pkg = pkg_; + if (err) return cb(err); + if (dir && pkg && opts.pathFilter) { + var rfile = path.relative(dir, file); + var rel = rfile.slice(0, rfile.length - exts[0].length); + var r = opts.pathFilter(pkg, x, rel); + if (r) return load( + [''].concat(extensions.slice()), + path.resolve(dir, r), + pkg + ); + } + isFile(file, onex); + } + function onex(err, ex) { + if (err) return cb(err); + if (ex) return cb(null, file, pkg); + load(exts.slice(1), x, pkg); + } + } + } + + function loadpkg(dir, cb) { + if (dir === '' || dir === '/') return cb(null); + if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { + return cb(null); + } + if ((/[/\\]node_modules[/\\]*$/).test(dir)) return cb(null); + + maybeRealpath(realpath, dir, opts, function (unwrapErr, pkgdir) { + if (unwrapErr) return loadpkg(path.dirname(dir), cb); + var pkgfile = path.join(pkgdir, 'package.json'); + isFile(pkgfile, function (err, ex) { + // on err, ex is false + if (!ex) return loadpkg(path.dirname(dir), cb); + + readPackage(readFile, pkgfile, function (err, pkgParam) { + if (err) cb(err); + + var pkg = pkgParam; + + if (pkg && opts.packageFilter) { + pkg = opts.packageFilter(pkg, pkgfile); + } + cb(null, pkg, dir); + }); + }); + }); + } + + function loadAsDirectory(x, loadAsDirectoryPackage, callback) { + var cb = callback; + var fpkg = loadAsDirectoryPackage; + if (typeof fpkg === 'function') { + cb = fpkg; + fpkg = opts.package; + } + + maybeRealpath(realpath, x, opts, function (unwrapErr, pkgdir) { + if (unwrapErr) return cb(unwrapErr); + var pkgfile = path.join(pkgdir, 'package.json'); + isFile(pkgfile, function (err, ex) { + if (err) return cb(err); + if (!ex) return loadAsFile(path.join(x, 'index'), fpkg, cb); + + readPackage(readFile, pkgfile, function (err, pkgParam) { + if (err) return cb(err); + + var pkg = pkgParam; + + if (pkg && opts.packageFilter) { + pkg = opts.packageFilter(pkg, pkgfile); + } + + if (pkg && pkg.main) { + if (typeof pkg.main !== 'string') { + var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); + mainError.code = 'INVALID_PACKAGE_MAIN'; + return cb(mainError); + } + if (pkg.main === '.' || pkg.main === './') { + pkg.main = 'index'; + } + loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) { + if (err) return cb(err); + if (m) return cb(null, m, pkg); + if (!pkg) return loadAsFile(path.join(x, 'index'), pkg, cb); + + var dir = path.resolve(x, pkg.main); + loadAsDirectory(dir, pkg, function (err, n, pkg) { + if (err) return cb(err); + if (n) return cb(null, n, pkg); + loadAsFile(path.join(x, 'index'), pkg, cb); + }); + }); + return; + } + + loadAsFile(path.join(x, '/index'), pkg, cb); + }); + }); + }); + } + + function processDirs(cb, dirs) { + if (dirs.length === 0) return cb(null, undefined); + var dir = dirs[0]; + + isDirectory(path.dirname(dir), isdir); + + function isdir(err, isdir) { + if (err) return cb(err); + if (!isdir) return processDirs(cb, dirs.slice(1)); + loadAsFile(dir, opts.package, onfile); + } + + function onfile(err, m, pkg) { + if (err) return cb(err); + if (m) return cb(null, m, pkg); + loadAsDirectory(dir, opts.package, ondir); + } + + function ondir(err, n, pkg) { + if (err) return cb(err); + if (n) return cb(null, n, pkg); + processDirs(cb, dirs.slice(1)); + } + } + function loadNodeModules(x, start, cb) { + var thunk = function () { return getPackageCandidates(x, start, opts); }; + processDirs( + cb, + packageIterator ? packageIterator(x, start, thunk, opts) : thunk() + ); + } +}; diff --git a/node_modules/resolve/lib/caller.js b/node_modules/resolve/lib/caller.js new file mode 100644 index 0000000..b14a280 --- /dev/null +++ b/node_modules/resolve/lib/caller.js @@ -0,0 +1,8 @@ +module.exports = function () { + // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi + var origPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = function (_, stack) { return stack; }; + var stack = (new Error()).stack; + Error.prepareStackTrace = origPrepareStackTrace; + return stack[2].getFileName(); +}; diff --git a/node_modules/resolve/lib/core.js b/node_modules/resolve/lib/core.js new file mode 100644 index 0000000..57b048f --- /dev/null +++ b/node_modules/resolve/lib/core.js @@ -0,0 +1,12 @@ +'use strict'; + +var isCoreModule = require('is-core-module'); +var data = require('./core.json'); + +var core = {}; +for (var mod in data) { // eslint-disable-line no-restricted-syntax + if (Object.prototype.hasOwnProperty.call(data, mod)) { + core[mod] = isCoreModule(mod); + } +} +module.exports = core; diff --git a/node_modules/resolve/lib/core.json b/node_modules/resolve/lib/core.json new file mode 100644 index 0000000..3cda693 --- /dev/null +++ b/node_modules/resolve/lib/core.json @@ -0,0 +1,158 @@ +{ + "assert": true, + "node:assert": [">= 14.18 && < 15", ">= 16"], + "assert/strict": ">= 15", + "node:assert/strict": ">= 16", + "async_hooks": ">= 8", + "node:async_hooks": [">= 14.18 && < 15", ">= 16"], + "buffer_ieee754": ">= 0.5 && < 0.9.7", + "buffer": true, + "node:buffer": [">= 14.18 && < 15", ">= 16"], + "child_process": true, + "node:child_process": [">= 14.18 && < 15", ">= 16"], + "cluster": ">= 0.5", + "node:cluster": [">= 14.18 && < 15", ">= 16"], + "console": true, + "node:console": [">= 14.18 && < 15", ">= 16"], + "constants": true, + "node:constants": [">= 14.18 && < 15", ">= 16"], + "crypto": true, + "node:crypto": [">= 14.18 && < 15", ">= 16"], + "_debug_agent": ">= 1 && < 8", + "_debugger": "< 8", + "dgram": true, + "node:dgram": [">= 14.18 && < 15", ">= 16"], + "diagnostics_channel": [">= 14.17 && < 15", ">= 15.1"], + "node:diagnostics_channel": [">= 14.18 && < 15", ">= 16"], + "dns": true, + "node:dns": [">= 14.18 && < 15", ">= 16"], + "dns/promises": ">= 15", + "node:dns/promises": ">= 16", + "domain": ">= 0.7.12", + "node:domain": [">= 14.18 && < 15", ">= 16"], + "events": true, + "node:events": [">= 14.18 && < 15", ">= 16"], + "freelist": "< 6", + "fs": true, + "node:fs": [">= 14.18 && < 15", ">= 16"], + "fs/promises": [">= 10 && < 10.1", ">= 14"], + "node:fs/promises": [">= 14.18 && < 15", ">= 16"], + "_http_agent": ">= 0.11.1", + "node:_http_agent": [">= 14.18 && < 15", ">= 16"], + "_http_client": ">= 0.11.1", + "node:_http_client": [">= 14.18 && < 15", ">= 16"], + "_http_common": ">= 0.11.1", + "node:_http_common": [">= 14.18 && < 15", ">= 16"], + "_http_incoming": ">= 0.11.1", + "node:_http_incoming": [">= 14.18 && < 15", ">= 16"], + "_http_outgoing": ">= 0.11.1", + "node:_http_outgoing": [">= 14.18 && < 15", ">= 16"], + "_http_server": ">= 0.11.1", + "node:_http_server": [">= 14.18 && < 15", ">= 16"], + "http": true, + "node:http": [">= 14.18 && < 15", ">= 16"], + "http2": ">= 8.8", + "node:http2": [">= 14.18 && < 15", ">= 16"], + "https": true, + "node:https": [">= 14.18 && < 15", ">= 16"], + "inspector": ">= 8", + "node:inspector": [">= 14.18 && < 15", ">= 16"], + "inspector/promises": [">= 19"], + "node:inspector/promises": [">= 19"], + "_linklist": "< 8", + "module": true, + "node:module": [">= 14.18 && < 15", ">= 16"], + "net": true, + "node:net": [">= 14.18 && < 15", ">= 16"], + "node-inspect/lib/_inspect": ">= 7.6 && < 12", + "node-inspect/lib/internal/inspect_client": ">= 7.6 && < 12", + "node-inspect/lib/internal/inspect_repl": ">= 7.6 && < 12", + "os": true, + "node:os": [">= 14.18 && < 15", ">= 16"], + "path": true, + "node:path": [">= 14.18 && < 15", ">= 16"], + "path/posix": ">= 15.3", + "node:path/posix": ">= 16", + "path/win32": ">= 15.3", + "node:path/win32": ">= 16", + "perf_hooks": ">= 8.5", + "node:perf_hooks": [">= 14.18 && < 15", ">= 16"], + "process": ">= 1", + "node:process": [">= 14.18 && < 15", ">= 16"], + "punycode": ">= 0.5", + "node:punycode": [">= 14.18 && < 15", ">= 16"], + "querystring": true, + "node:querystring": [">= 14.18 && < 15", ">= 16"], + "readline": true, + "node:readline": [">= 14.18 && < 15", ">= 16"], + "readline/promises": ">= 17", + "node:readline/promises": ">= 17", + "repl": true, + "node:repl": [">= 14.18 && < 15", ">= 16"], + "smalloc": ">= 0.11.5 && < 3", + "_stream_duplex": ">= 0.9.4", + "node:_stream_duplex": [">= 14.18 && < 15", ">= 16"], + "_stream_transform": ">= 0.9.4", + "node:_stream_transform": [">= 14.18 && < 15", ">= 16"], + "_stream_wrap": ">= 1.4.1", + "node:_stream_wrap": [">= 14.18 && < 15", ">= 16"], + "_stream_passthrough": ">= 0.9.4", + "node:_stream_passthrough": [">= 14.18 && < 15", ">= 16"], + "_stream_readable": ">= 0.9.4", + "node:_stream_readable": [">= 14.18 && < 15", ">= 16"], + "_stream_writable": ">= 0.9.4", + "node:_stream_writable": [">= 14.18 && < 15", ">= 16"], + "stream": true, + "node:stream": [">= 14.18 && < 15", ">= 16"], + "stream/consumers": ">= 16.7", + "node:stream/consumers": ">= 16.7", + "stream/promises": ">= 15", + "node:stream/promises": ">= 16", + "stream/web": ">= 16.5", + "node:stream/web": ">= 16.5", + "string_decoder": true, + "node:string_decoder": [">= 14.18 && < 15", ">= 16"], + "sys": [">= 0.4 && < 0.7", ">= 0.8"], + "node:sys": [">= 14.18 && < 15", ">= 16"], + "test/reporters": ">= 19.9 && < 20.2", + "node:test/reporters": [">= 18.17 && < 19", ">= 19.9", ">= 20"], + "node:test": [">= 16.17 && < 17", ">= 18"], + "timers": true, + "node:timers": [">= 14.18 && < 15", ">= 16"], + "timers/promises": ">= 15", + "node:timers/promises": ">= 16", + "_tls_common": ">= 0.11.13", + "node:_tls_common": [">= 14.18 && < 15", ">= 16"], + "_tls_legacy": ">= 0.11.3 && < 10", + "_tls_wrap": ">= 0.11.3", + "node:_tls_wrap": [">= 14.18 && < 15", ">= 16"], + "tls": true, + "node:tls": [">= 14.18 && < 15", ">= 16"], + "trace_events": ">= 10", + "node:trace_events": [">= 14.18 && < 15", ">= 16"], + "tty": true, + "node:tty": [">= 14.18 && < 15", ">= 16"], + "url": true, + "node:url": [">= 14.18 && < 15", ">= 16"], + "util": true, + "node:util": [">= 14.18 && < 15", ">= 16"], + "util/types": ">= 15.3", + "node:util/types": ">= 16", + "v8/tools/arguments": ">= 10 && < 12", + "v8/tools/codemap": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/consarray": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/csvparser": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/logreader": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/profile_view": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8/tools/splaytree": [">= 4.4 && < 5", ">= 5.2 && < 12"], + "v8": ">= 1", + "node:v8": [">= 14.18 && < 15", ">= 16"], + "vm": true, + "node:vm": [">= 14.18 && < 15", ">= 16"], + "wasi": [">= 13.4 && < 13.5", ">= 18.17 && < 19", ">= 20"], + "node:wasi": [">= 18.17 && < 19", ">= 20"], + "worker_threads": ">= 11.7", + "node:worker_threads": [">= 14.18 && < 15", ">= 16"], + "zlib": ">= 0.5", + "node:zlib": [">= 14.18 && < 15", ">= 16"] +} diff --git a/node_modules/resolve/lib/homedir.js b/node_modules/resolve/lib/homedir.js new file mode 100644 index 0000000..5ffdf73 --- /dev/null +++ b/node_modules/resolve/lib/homedir.js @@ -0,0 +1,24 @@ +'use strict'; + +var os = require('os'); + +// adapted from https://github.com/sindresorhus/os-homedir/blob/11e089f4754db38bb535e5a8416320c4446e8cfd/index.js + +module.exports = os.homedir || function homedir() { + var home = process.env.HOME; + var user = process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME; + + if (process.platform === 'win32') { + return process.env.USERPROFILE || process.env.HOMEDRIVE + process.env.HOMEPATH || home || null; + } + + if (process.platform === 'darwin') { + return home || (user ? '/Users/' + user : null); + } + + if (process.platform === 'linux') { + return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : null)); // eslint-disable-line no-extra-parens + } + + return home || null; +}; diff --git a/node_modules/resolve/lib/is-core.js b/node_modules/resolve/lib/is-core.js new file mode 100644 index 0000000..537f5c7 --- /dev/null +++ b/node_modules/resolve/lib/is-core.js @@ -0,0 +1,5 @@ +var isCoreModule = require('is-core-module'); + +module.exports = function isCore(x) { + return isCoreModule(x); +}; diff --git a/node_modules/resolve/lib/node-modules-paths.js b/node_modules/resolve/lib/node-modules-paths.js new file mode 100644 index 0000000..1cff010 --- /dev/null +++ b/node_modules/resolve/lib/node-modules-paths.js @@ -0,0 +1,42 @@ +var path = require('path'); +var parse = path.parse || require('path-parse'); // eslint-disable-line global-require + +var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) { + var prefix = '/'; + if ((/^([A-Za-z]:)/).test(absoluteStart)) { + prefix = ''; + } else if ((/^\\\\/).test(absoluteStart)) { + prefix = '\\\\'; + } + + var paths = [absoluteStart]; + var parsed = parse(absoluteStart); + while (parsed.dir !== paths[paths.length - 1]) { + paths.push(parsed.dir); + parsed = parse(parsed.dir); + } + + return paths.reduce(function (dirs, aPath) { + return dirs.concat(modules.map(function (moduleDir) { + return path.resolve(prefix, aPath, moduleDir); + })); + }, []); +}; + +module.exports = function nodeModulesPaths(start, opts, request) { + var modules = opts && opts.moduleDirectory + ? [].concat(opts.moduleDirectory) + : ['node_modules']; + + if (opts && typeof opts.paths === 'function') { + return opts.paths( + request, + start, + function () { return getNodeModulesDirs(start, modules); }, + opts + ); + } + + var dirs = getNodeModulesDirs(start, modules); + return opts && opts.paths ? dirs.concat(opts.paths) : dirs; +}; diff --git a/node_modules/resolve/lib/normalize-options.js b/node_modules/resolve/lib/normalize-options.js new file mode 100644 index 0000000..4b56904 --- /dev/null +++ b/node_modules/resolve/lib/normalize-options.js @@ -0,0 +1,10 @@ +module.exports = function (x, opts) { + /** + * This file is purposefully a passthrough. It's expected that third-party + * environments will override it at runtime in order to inject special logic + * into `resolve` (by manipulating the options). One such example is the PnP + * code path in Yarn. + */ + + return opts || {}; +}; diff --git a/node_modules/resolve/lib/sync.js b/node_modules/resolve/lib/sync.js new file mode 100644 index 0000000..0b6cd58 --- /dev/null +++ b/node_modules/resolve/lib/sync.js @@ -0,0 +1,208 @@ +var isCore = require('is-core-module'); +var fs = require('fs'); +var path = require('path'); +var getHomedir = require('./homedir'); +var caller = require('./caller'); +var nodeModulesPaths = require('./node-modules-paths'); +var normalizeOptions = require('./normalize-options'); + +var realpathFS = process.platform !== 'win32' && fs.realpathSync && typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync; + +var homedir = getHomedir(); +var defaultPaths = function () { + return [ + path.join(homedir, '.node_modules'), + path.join(homedir, '.node_libraries') + ]; +}; + +var defaultIsFile = function isFile(file) { + try { + var stat = fs.statSync(file, { throwIfNoEntry: false }); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return !!stat && (stat.isFile() || stat.isFIFO()); +}; + +var defaultIsDir = function isDirectory(dir) { + try { + var stat = fs.statSync(dir, { throwIfNoEntry: false }); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return !!stat && stat.isDirectory(); +}; + +var defaultRealpathSync = function realpathSync(x) { + try { + return realpathFS(x); + } catch (realpathErr) { + if (realpathErr.code !== 'ENOENT') { + throw realpathErr; + } + } + return x; +}; + +var maybeRealpathSync = function maybeRealpathSync(realpathSync, x, opts) { + if (opts && opts.preserveSymlinks === false) { + return realpathSync(x); + } + return x; +}; + +var defaultReadPackageSync = function defaultReadPackageSync(readFileSync, pkgfile) { + var body = readFileSync(pkgfile); + try { + var pkg = JSON.parse(body); + return pkg; + } catch (jsonErr) {} +}; + +var getPackageCandidates = function getPackageCandidates(x, start, opts) { + var dirs = nodeModulesPaths(start, opts, x); + for (var i = 0; i < dirs.length; i++) { + dirs[i] = path.join(dirs[i], x); + } + return dirs; +}; + +module.exports = function resolveSync(x, options) { + if (typeof x !== 'string') { + throw new TypeError('Path must be a string.'); + } + var opts = normalizeOptions(x, options); + + var isFile = opts.isFile || defaultIsFile; + var readFileSync = opts.readFileSync || fs.readFileSync; + var isDirectory = opts.isDirectory || defaultIsDir; + var realpathSync = opts.realpathSync || defaultRealpathSync; + var readPackageSync = opts.readPackageSync || defaultReadPackageSync; + if (opts.readFileSync && opts.readPackageSync) { + throw new TypeError('`readFileSync` and `readPackageSync` are mutually exclusive.'); + } + var packageIterator = opts.packageIterator; + + var extensions = opts.extensions || ['.js']; + var includeCoreModules = opts.includeCoreModules !== false; + var basedir = opts.basedir || path.dirname(caller()); + var parent = opts.filename || basedir; + + opts.paths = opts.paths || defaultPaths(); + + // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory + var absoluteStart = maybeRealpathSync(realpathSync, path.resolve(basedir), opts); + + if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { + var res = path.resolve(absoluteStart, x); + if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; + var m = loadAsFileSync(res) || loadAsDirectorySync(res); + if (m) return maybeRealpathSync(realpathSync, m, opts); + } else if (includeCoreModules && isCore(x)) { + return x; + } else { + var n = loadNodeModulesSync(x, absoluteStart); + if (n) return maybeRealpathSync(realpathSync, n, opts); + } + + var err = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + err.code = 'MODULE_NOT_FOUND'; + throw err; + + function loadAsFileSync(x) { + var pkg = loadpkg(path.dirname(x)); + + if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) { + var rfile = path.relative(pkg.dir, x); + var r = opts.pathFilter(pkg.pkg, x, rfile); + if (r) { + x = path.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign + } + } + + if (isFile(x)) { + return x; + } + + for (var i = 0; i < extensions.length; i++) { + var file = x + extensions[i]; + if (isFile(file)) { + return file; + } + } + } + + function loadpkg(dir) { + if (dir === '' || dir === '/') return; + if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { + return; + } + if ((/[/\\]node_modules[/\\]*$/).test(dir)) return; + + var pkgfile = path.join(maybeRealpathSync(realpathSync, dir, opts), 'package.json'); + + if (!isFile(pkgfile)) { + return loadpkg(path.dirname(dir)); + } + + var pkg = readPackageSync(readFileSync, pkgfile); + + if (pkg && opts.packageFilter) { + // v2 will pass pkgfile + pkg = opts.packageFilter(pkg, /*pkgfile,*/ dir); // eslint-disable-line spaced-comment + } + + return { pkg: pkg, dir: dir }; + } + + function loadAsDirectorySync(x) { + var pkgfile = path.join(maybeRealpathSync(realpathSync, x, opts), '/package.json'); + if (isFile(pkgfile)) { + try { + var pkg = readPackageSync(readFileSync, pkgfile); + } catch (e) {} + + if (pkg && opts.packageFilter) { + // v2 will pass pkgfile + pkg = opts.packageFilter(pkg, /*pkgfile,*/ x); // eslint-disable-line spaced-comment + } + + if (pkg && pkg.main) { + if (typeof pkg.main !== 'string') { + var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); + mainError.code = 'INVALID_PACKAGE_MAIN'; + throw mainError; + } + if (pkg.main === '.' || pkg.main === './') { + pkg.main = 'index'; + } + try { + var m = loadAsFileSync(path.resolve(x, pkg.main)); + if (m) return m; + var n = loadAsDirectorySync(path.resolve(x, pkg.main)); + if (n) return n; + } catch (e) {} + } + } + + return loadAsFileSync(path.join(x, '/index')); + } + + function loadNodeModulesSync(x, start) { + var thunk = function () { return getPackageCandidates(x, start, opts); }; + var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk(); + + for (var i = 0; i < dirs.length; i++) { + var dir = dirs[i]; + if (isDirectory(path.dirname(dir))) { + var m = loadAsFileSync(dir); + if (m) return m; + var n = loadAsDirectorySync(dir); + if (n) return n; + } + } + } +}; diff --git a/node_modules/resolve/package.json b/node_modules/resolve/package.json new file mode 100644 index 0000000..537388d --- /dev/null +++ b/node_modules/resolve/package.json @@ -0,0 +1,72 @@ +{ + "name": "resolve", + "description": "resolve like require.resolve() on behalf of files asynchronously and synchronously", + "version": "1.22.8", + "repository": { + "type": "git", + "url": "git://github.com/browserify/resolve.git" + }, + "bin": { + "resolve": "./bin/resolve" + }, + "main": "index.js", + "keywords": [ + "resolve", + "require", + "node", + "module" + ], + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated && cp node_modules/is-core-module/core.json ./lib/ ||:", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs --no-eslintrc -c .eslintrc . 'bin/**'", + "pretests-only": "cd ./test/resolver/nested_symlinks && node mylib/sync && node mylib/async", + "tests-only": "tape test/*.js", + "pretest": "npm run lint", + "test": "npm run --silent tests-only", + "posttest": "npm run test:multirepo && aud --production", + "test:multirepo": "cd ./test/resolver/multirepo && npm install && npm test" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "array.prototype.map": "^1.0.6", + "aud": "^2.0.3", + "copy-dir": "^1.3.0", + "eclint": "^2.8.1", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "mkdirp": "^0.5.5", + "mv": "^2.1.1", + "npmignore": "^0.3.0", + "object-keys": "^1.1.1", + "rimraf": "^2.7.1", + "safe-publish-latest": "^2.0.0", + "semver": "^6.3.1", + "tap": "0.4.13", + "tape": "^5.7.0", + "tmp": "^0.0.31" + }, + "license": "MIT", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "appveyor.yml", + "test/resolver/malformed_package_json" + ] + } +} diff --git a/node_modules/resolve/readme.markdown b/node_modules/resolve/readme.markdown new file mode 100644 index 0000000..ad34d60 --- /dev/null +++ b/node_modules/resolve/readme.markdown @@ -0,0 +1,301 @@ +# resolve [![Version Badge][2]][1] + +implements the [node `require.resolve()` algorithm](https://nodejs.org/api/modules.html#modules_all_together) such that you can `require.resolve()` on behalf of a file asynchronously and synchronously + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +# example + +asynchronously resolve: + +```js +var resolve = require('resolve/async'); // or, require('resolve') +resolve('tap', { basedir: __dirname }, function (err, res) { + if (err) console.error(err); + else console.log(res); +}); +``` + +``` +$ node example/async.js +/home/substack/projects/node-resolve/node_modules/tap/lib/main.js +``` + +synchronously resolve: + +```js +var resolve = require('resolve/sync'); // or, `require('resolve').sync +var res = resolve('tap', { basedir: __dirname }); +console.log(res); +``` + +``` +$ node example/sync.js +/home/substack/projects/node-resolve/node_modules/tap/lib/main.js +``` + +# methods + +```js +var resolve = require('resolve'); +var async = require('resolve/async'); +var sync = require('resolve/sync'); +``` + +For both the synchronous and asynchronous methods, errors may have any of the following `err.code` values: + +- `MODULE_NOT_FOUND`: the given path string (`id`) could not be resolved to a module +- `INVALID_BASEDIR`: the specified `opts.basedir` doesn't exist, or is not a directory +- `INVALID_PACKAGE_MAIN`: a `package.json` was encountered with an invalid `main` property (eg. not a string) + +## resolve(id, opts={}, cb) + +Asynchronously resolve the module path string `id` into `cb(err, res [, pkg])`, where `pkg` (if defined) is the data from `package.json`. + +options are: + +* opts.basedir - directory to begin resolving from + +* opts.package - `package.json` data applicable to the module being loaded + +* opts.extensions - array of file extensions to search in order + +* opts.includeCoreModules - set to `false` to exclude node core modules (e.g. `fs`) from the search + +* opts.readFile - how to read files asynchronously + +* opts.isFile - function to asynchronously test whether a file exists + +* opts.isDirectory - function to asynchronously test whether a file exists and is a directory + +* opts.realpath - function to asynchronously resolve a potential symlink to its real path + +* `opts.readPackage(readFile, pkgfile, cb)` - function to asynchronously read and parse a package.json file + * readFile - the passed `opts.readFile` or `fs.readFile` if not specified + * pkgfile - path to package.json + * cb - callback + +* `opts.packageFilter(pkg, pkgfile, dir)` - transform the parsed package.json contents before looking at the "main" field + * pkg - package data + * pkgfile - path to package.json + * dir - directory that contains package.json + +* `opts.pathFilter(pkg, path, relativePath)` - transform a path within a package + * pkg - package data + * path - the path being resolved + * relativePath - the path relative from the package.json location + * returns - a relative path that will be joined from the package.json location + +* opts.paths - require.paths array to use if nothing is found on the normal `node_modules` recursive walk (probably don't use this) + + For advanced users, `paths` can also be a `opts.paths(request, start, opts)` function + * request - the import specifier being resolved + * start - lookup path + * getNodeModulesDirs - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution + * opts - the resolution options + +* `opts.packageIterator(request, start, opts)` - return the list of candidate paths where the packages sources may be found (probably don't use this) + * request - the import specifier being resolved + * start - lookup path + * getPackageCandidates - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution + * opts - the resolution options + +* opts.moduleDirectory - directory (or directories) in which to recursively look for modules. default: `"node_modules"` + +* opts.preserveSymlinks - if true, doesn't resolve `basedir` to real path before resolving. +This is the way Node resolves dependencies when executed with the [--preserve-symlinks](https://nodejs.org/api/all.html#cli_preserve_symlinks) flag. +**Note:** this property is currently `true` by default but it will be changed to +`false` in the next major version because *Node's resolution algorithm does not preserve symlinks by default*. + +default `opts` values: + +```js +{ + paths: [], + basedir: __dirname, + extensions: ['.js'], + includeCoreModules: true, + readFile: fs.readFile, + isFile: function isFile(file, cb) { + fs.stat(file, function (err, stat) { + if (!err) { + return cb(null, stat.isFile() || stat.isFIFO()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); + }, + isDirectory: function isDirectory(dir, cb) { + fs.stat(dir, function (err, stat) { + if (!err) { + return cb(null, stat.isDirectory()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); + }, + realpath: function realpath(file, cb) { + var realpath = typeof fs.realpath.native === 'function' ? fs.realpath.native : fs.realpath; + realpath(file, function (realPathErr, realPath) { + if (realPathErr && realPathErr.code !== 'ENOENT') cb(realPathErr); + else cb(null, realPathErr ? file : realPath); + }); + }, + readPackage: function defaultReadPackage(readFile, pkgfile, cb) { + readFile(pkgfile, function (readFileErr, body) { + if (readFileErr) cb(readFileErr); + else { + try { + var pkg = JSON.parse(body); + cb(null, pkg); + } catch (jsonErr) { + cb(null); + } + } + }); + }, + moduleDirectory: 'node_modules', + preserveSymlinks: true +} +``` + +## resolve.sync(id, opts) + +Synchronously resolve the module path string `id`, returning the result and +throwing an error when `id` can't be resolved. + +options are: + +* opts.basedir - directory to begin resolving from + +* opts.extensions - array of file extensions to search in order + +* opts.includeCoreModules - set to `false` to exclude node core modules (e.g. `fs`) from the search + +* opts.readFileSync - how to read files synchronously + +* opts.isFile - function to synchronously test whether a file exists + +* opts.isDirectory - function to synchronously test whether a file exists and is a directory + +* opts.realpathSync - function to synchronously resolve a potential symlink to its real path + +* `opts.readPackageSync(readFileSync, pkgfile)` - function to synchronously read and parse a package.json file + * readFileSync - the passed `opts.readFileSync` or `fs.readFileSync` if not specified + * pkgfile - path to package.json + +* `opts.packageFilter(pkg, dir)` - transform the parsed package.json contents before looking at the "main" field + * pkg - package data + * dir - directory that contains package.json (Note: the second argument will change to "pkgfile" in v2) + +* `opts.pathFilter(pkg, path, relativePath)` - transform a path within a package + * pkg - package data + * path - the path being resolved + * relativePath - the path relative from the package.json location + * returns - a relative path that will be joined from the package.json location + +* opts.paths - require.paths array to use if nothing is found on the normal `node_modules` recursive walk (probably don't use this) + + For advanced users, `paths` can also be a `opts.paths(request, start, opts)` function + * request - the import specifier being resolved + * start - lookup path + * getNodeModulesDirs - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution + * opts - the resolution options + +* `opts.packageIterator(request, start, opts)` - return the list of candidate paths where the packages sources may be found (probably don't use this) + * request - the import specifier being resolved + * start - lookup path + * getPackageCandidates - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution + * opts - the resolution options + +* opts.moduleDirectory - directory (or directories) in which to recursively look for modules. default: `"node_modules"` + +* opts.preserveSymlinks - if true, doesn't resolve `basedir` to real path before resolving. +This is the way Node resolves dependencies when executed with the [--preserve-symlinks](https://nodejs.org/api/all.html#cli_preserve_symlinks) flag. +**Note:** this property is currently `true` by default but it will be changed to +`false` in the next major version because *Node's resolution algorithm does not preserve symlinks by default*. + +default `opts` values: + +```js +{ + paths: [], + basedir: __dirname, + extensions: ['.js'], + includeCoreModules: true, + readFileSync: fs.readFileSync, + isFile: function isFile(file) { + try { + var stat = fs.statSync(file); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return stat.isFile() || stat.isFIFO(); + }, + isDirectory: function isDirectory(dir) { + try { + var stat = fs.statSync(dir); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + return stat.isDirectory(); + }, + realpathSync: function realpathSync(file) { + try { + var realpath = typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync; + return realpath(file); + } catch (realPathErr) { + if (realPathErr.code !== 'ENOENT') { + throw realPathErr; + } + } + return file; + }, + readPackageSync: function defaultReadPackageSync(readFileSync, pkgfile) { + var body = readFileSync(pkgfile); + try { + var pkg = JSON.parse(body); + return pkg; + } catch (jsonErr) {} + }, + moduleDirectory: 'node_modules', + preserveSymlinks: true +} +``` + +# install + +With [npm](https://npmjs.org) do: + +```sh +npm install resolve +``` + +# license + +MIT + +[1]: https://npmjs.org/package/resolve +[2]: https://versionbadg.es/browserify/resolve.svg +[5]: https://david-dm.org/browserify/resolve.svg +[6]: https://david-dm.org/browserify/resolve +[7]: https://david-dm.org/browserify/resolve/dev-status.svg +[8]: https://david-dm.org/browserify/resolve#info=devDependencies +[11]: https://nodei.co/npm/resolve.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/resolve.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/resolve.svg +[downloads-url]: https://npm-stat.com/charts.html?package=resolve +[codecov-image]: https://codecov.io/gh/browserify/resolve/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/browserify/resolve/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/browserify/resolve +[actions-url]: https://github.com/browserify/resolve/actions diff --git a/node_modules/resolve/sync.js b/node_modules/resolve/sync.js new file mode 100644 index 0000000..cd0ee04 --- /dev/null +++ b/node_modules/resolve/sync.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./lib/sync'); diff --git a/node_modules/resolve/test/core.js b/node_modules/resolve/test/core.js new file mode 100644 index 0000000..a477adc --- /dev/null +++ b/node_modules/resolve/test/core.js @@ -0,0 +1,88 @@ +var test = require('tape'); +var keys = require('object-keys'); +var semver = require('semver'); + +var resolve = require('../'); + +var brokenNode = semver.satisfies(process.version, '11.11 - 11.13'); + +test('core modules', function (t) { + t.test('isCore()', function (st) { + st.ok(resolve.isCore('fs')); + st.ok(resolve.isCore('net')); + st.ok(resolve.isCore('http')); + + st.ok(!resolve.isCore('seq')); + st.ok(!resolve.isCore('../')); + + st.ok(!resolve.isCore('toString')); + + st.end(); + }); + + t.test('core list', function (st) { + var cores = keys(resolve.core); + st.plan(cores.length); + + for (var i = 0; i < cores.length; ++i) { + var mod = cores[i]; + // note: this must be require, not require.resolve, due to https://github.com/nodejs/node/issues/43274 + var requireFunc = function () { require(mod); }; // eslint-disable-line no-loop-func + t.comment(mod + ': ' + resolve.core[mod]); + if (resolve.core[mod]) { + st.doesNotThrow(requireFunc, mod + ' supported; requiring does not throw'); + } else if (brokenNode) { + st.ok(true, 'this version of node is broken: attempting to require things that fail to resolve breaks "home_paths" tests'); + } else { + st.throws(requireFunc, mod + ' not supported; requiring throws'); + } + } + + st.end(); + }); + + t.test('core via repl module', { skip: !resolve.core.repl }, function (st) { + var libs = require('repl')._builtinLibs; // eslint-disable-line no-underscore-dangle + if (!libs) { + st.skip('module.builtinModules does not exist'); + return st.end(); + } + for (var i = 0; i < libs.length; ++i) { + var mod = libs[i]; + st.ok(resolve.core[mod], mod + ' is a core module'); + st.doesNotThrow( + function () { require(mod); }, // eslint-disable-line no-loop-func + 'requiring ' + mod + ' does not throw' + ); + } + st.end(); + }); + + t.test('core via builtinModules list', { skip: !resolve.core.module }, function (st) { + var libs = require('module').builtinModules; + if (!libs) { + st.skip('module.builtinModules does not exist'); + return st.end(); + } + var blacklist = [ + '_debug_agent', + 'v8/tools/tickprocessor-driver', + 'v8/tools/SourceMap', + 'v8/tools/tickprocessor', + 'v8/tools/profile' + ]; + for (var i = 0; i < libs.length; ++i) { + var mod = libs[i]; + if (blacklist.indexOf(mod) === -1) { + st.ok(resolve.core[mod], mod + ' is a core module'); + st.doesNotThrow( + function () { require(mod); }, // eslint-disable-line no-loop-func + 'requiring ' + mod + ' does not throw' + ); + } + } + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/resolve/test/dotdot.js b/node_modules/resolve/test/dotdot.js new file mode 100644 index 0000000..3080665 --- /dev/null +++ b/node_modules/resolve/test/dotdot.js @@ -0,0 +1,29 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('dotdot', function (t) { + t.plan(4); + var dir = path.join(__dirname, '/dotdot/abc'); + + resolve('..', { basedir: dir }, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(__dirname, 'dotdot/index.js')); + }); + + resolve('.', { basedir: dir }, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, 'index.js')); + }); +}); + +test('dotdot sync', function (t) { + t.plan(2); + var dir = path.join(__dirname, '/dotdot/abc'); + + var a = resolve.sync('..', { basedir: dir }); + t.equal(a, path.join(__dirname, 'dotdot/index.js')); + + var b = resolve.sync('.', { basedir: dir }); + t.equal(b, path.join(dir, 'index.js')); +}); diff --git a/node_modules/resolve/test/dotdot/abc/index.js b/node_modules/resolve/test/dotdot/abc/index.js new file mode 100644 index 0000000..67f2534 --- /dev/null +++ b/node_modules/resolve/test/dotdot/abc/index.js @@ -0,0 +1,2 @@ +var x = require('..'); +console.log(x); diff --git a/node_modules/resolve/test/dotdot/index.js b/node_modules/resolve/test/dotdot/index.js new file mode 100644 index 0000000..643f9fc --- /dev/null +++ b/node_modules/resolve/test/dotdot/index.js @@ -0,0 +1 @@ +module.exports = 'whatever'; diff --git a/node_modules/resolve/test/faulty_basedir.js b/node_modules/resolve/test/faulty_basedir.js new file mode 100644 index 0000000..5f2141a --- /dev/null +++ b/node_modules/resolve/test/faulty_basedir.js @@ -0,0 +1,29 @@ +var test = require('tape'); +var path = require('path'); +var resolve = require('../'); + +test('faulty basedir must produce error in windows', { skip: process.platform !== 'win32' }, function (t) { + t.plan(1); + + var resolverDir = 'C:\\a\\b\\c\\d'; + + resolve('tape/lib/test.js', { basedir: resolverDir }, function (err, res, pkg) { + t.equal(!!err, true); + }); +}); + +test('non-existent basedir should not throw when preserveSymlinks is false', function (t) { + t.plan(2); + + var opts = { + basedir: path.join(path.sep, 'unreal', 'path', 'that', 'does', 'not', 'exist'), + preserveSymlinks: false + }; + + var module = './dotdot/abc'; + + resolve(module, opts, function (err, res) { + t.equal(err.code, 'MODULE_NOT_FOUND'); + t.equal(res, undefined); + }); +}); diff --git a/node_modules/resolve/test/filter.js b/node_modules/resolve/test/filter.js new file mode 100644 index 0000000..8f8cccd --- /dev/null +++ b/node_modules/resolve/test/filter.js @@ -0,0 +1,34 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('filter', function (t) { + t.plan(4); + var dir = path.join(__dirname, 'resolver'); + var packageFilterArgs; + resolve('./baz', { + basedir: dir, + packageFilter: function (pkg, pkgfile) { + pkg.main = 'doom'; // eslint-disable-line no-param-reassign + packageFilterArgs = [pkg, pkgfile]; + return pkg; + } + }, function (err, res, pkg) { + if (err) t.fail(err); + + t.equal(res, path.join(dir, 'baz/doom.js'), 'changing the package "main" works'); + + var packageData = packageFilterArgs[0]; + t.equal(pkg, packageData, 'first packageFilter argument is "pkg"'); + t.equal(packageData.main, 'doom', 'package "main" was altered'); + + var packageFile = packageFilterArgs[1]; + t.equal( + packageFile, + path.join(dir, 'baz/package.json'), + 'second packageFilter argument is "pkgfile"' + ); + + t.end(); + }); +}); diff --git a/node_modules/resolve/test/filter_sync.js b/node_modules/resolve/test/filter_sync.js new file mode 100644 index 0000000..8a43b98 --- /dev/null +++ b/node_modules/resolve/test/filter_sync.js @@ -0,0 +1,33 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('filter', function (t) { + var dir = path.join(__dirname, 'resolver'); + var packageFilterArgs; + var res = resolve.sync('./baz', { + basedir: dir, + // NOTE: in v2.x, this will be `pkg, pkgfile, dir`, but must remain "broken" here in v1.x for compatibility + packageFilter: function (pkg, /*pkgfile,*/ dir) { // eslint-disable-line spaced-comment + pkg.main = 'doom'; // eslint-disable-line no-param-reassign + packageFilterArgs = 'is 1.x' ? [pkg, dir] : [pkg, pkgfile, dir]; // eslint-disable-line no-constant-condition, no-undef + return pkg; + } + }); + + t.equal(res, path.join(dir, 'baz/doom.js'), 'changing the package "main" works'); + + var packageData = packageFilterArgs[0]; + t.equal(packageData.main, 'doom', 'package "main" was altered'); + + if (!'is 1.x') { // eslint-disable-line no-constant-condition + var packageFile = packageFilterArgs[1]; + t.equal(packageFile, path.join(dir, 'baz', 'package.json'), 'package.json path is correct'); + } + + var packageDir = packageFilterArgs['is 1.x' ? 1 : 2]; // eslint-disable-line no-constant-condition + // eslint-disable-next-line no-constant-condition + t.equal(packageDir, path.join(dir, 'baz'), ('is 1.x' ? 'second' : 'third') + ' packageFilter argument is "dir"'); + + t.end(); +}); diff --git a/node_modules/resolve/test/home_paths.js b/node_modules/resolve/test/home_paths.js new file mode 100644 index 0000000..3b8c9b3 --- /dev/null +++ b/node_modules/resolve/test/home_paths.js @@ -0,0 +1,127 @@ +'use strict'; + +var fs = require('fs'); +var homedir = require('../lib/homedir'); +var path = require('path'); + +var test = require('tape'); +var mkdirp = require('mkdirp'); +var rimraf = require('rimraf'); +var mv = require('mv'); +var copyDir = require('copy-dir'); +var tmp = require('tmp'); + +var HOME = homedir(); + +var hnm = path.join(HOME, '.node_modules'); +var hnl = path.join(HOME, '.node_libraries'); + +var resolve = require('../async'); + +function makeDir(t, dir, cb) { + mkdirp(dir, function (err) { + if (err) { + cb(err); + } else { + t.teardown(function cleanup() { + rimraf.sync(dir); + }); + cb(); + } + }); +} + +function makeTempDir(t, dir, cb) { + if (fs.existsSync(dir)) { + var tmpResult = tmp.dirSync(); + t.teardown(tmpResult.removeCallback); + var backup = path.join(tmpResult.name, path.basename(dir)); + mv(dir, backup, function (err) { + if (err) { + cb(err); + } else { + t.teardown(function () { + mv(backup, dir, cb); + }); + makeDir(t, dir, cb); + } + }); + } else { + makeDir(t, dir, cb); + } +} + +test('homedir module paths', function (t) { + t.plan(7); + + makeTempDir(t, hnm, function (err) { + t.error(err, 'no error with HNM temp dir'); + if (err) { + return t.end(); + } + + var bazHNMDir = path.join(hnm, 'baz'); + var dotMainDir = path.join(hnm, 'dot_main'); + copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNMDir); + copyDir.sync(path.join(__dirname, 'resolver/dot_main'), dotMainDir); + + var bazPkg = { name: 'baz', main: 'quux.js' }; + var dotMainPkg = { main: 'index' }; + + var bazHNMmain = path.join(bazHNMDir, 'quux.js'); + t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`'); + var dotMainMain = path.join(dotMainDir, 'index.js'); + t.equal(require.resolve('dot_main'), dotMainMain, 'sanity check: require.resolve finds `dot_main`'); + + makeTempDir(t, hnl, function (err) { + t.error(err, 'no error with HNL temp dir'); + if (err) { + return t.end(); + } + var bazHNLDir = path.join(hnl, 'baz'); + copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNLDir); + + var dotSlashMainDir = path.join(hnl, 'dot_slash_main'); + var dotSlashMainMain = path.join(dotSlashMainDir, 'index.js'); + var dotSlashMainPkg = { main: 'index' }; + copyDir.sync(path.join(__dirname, 'resolver/dot_slash_main'), dotSlashMainDir); + + t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`'); + t.equal(require.resolve('dot_slash_main'), dotSlashMainMain, 'sanity check: require.resolve finds HNL `dot_slash_main`'); + + t.test('with temp dirs', function (st) { + st.plan(3); + + st.test('just in `$HOME/.node_modules`', function (s2t) { + s2t.plan(3); + + resolve('dot_main', function (err, res, pkg) { + s2t.error(err, 'no error resolving `dot_main`'); + s2t.equal(res, dotMainMain, '`dot_main` resolves in `$HOME/.node_modules`'); + s2t.deepEqual(pkg, dotMainPkg); + }); + }); + + st.test('just in `$HOME/.node_libraries`', function (s2t) { + s2t.plan(3); + + resolve('dot_slash_main', function (err, res, pkg) { + s2t.error(err, 'no error resolving `dot_slash_main`'); + s2t.equal(res, dotSlashMainMain, '`dot_slash_main` resolves in `$HOME/.node_libraries`'); + s2t.deepEqual(pkg, dotSlashMainPkg); + }); + }); + + st.test('in `$HOME/.node_libraries` and `$HOME/.node_modules`', function (s2t) { + s2t.plan(3); + + resolve('baz', function (err, res, pkg) { + s2t.error(err, 'no error resolving `baz`'); + s2t.equal(res, bazHNMmain, '`baz` resolves in `$HOME/.node_modules` when in both'); + s2t.deepEqual(pkg, bazPkg); + }); + }); + }); + }); + }); +}); diff --git a/node_modules/resolve/test/home_paths_sync.js b/node_modules/resolve/test/home_paths_sync.js new file mode 100644 index 0000000..5d2c56f --- /dev/null +++ b/node_modules/resolve/test/home_paths_sync.js @@ -0,0 +1,114 @@ +'use strict'; + +var fs = require('fs'); +var homedir = require('../lib/homedir'); +var path = require('path'); + +var test = require('tape'); +var mkdirp = require('mkdirp'); +var rimraf = require('rimraf'); +var mv = require('mv'); +var copyDir = require('copy-dir'); +var tmp = require('tmp'); + +var HOME = homedir(); + +var hnm = path.join(HOME, '.node_modules'); +var hnl = path.join(HOME, '.node_libraries'); + +var resolve = require('../sync'); + +function makeDir(t, dir, cb) { + mkdirp(dir, function (err) { + if (err) { + cb(err); + } else { + t.teardown(function cleanup() { + rimraf.sync(dir); + }); + cb(); + } + }); +} + +function makeTempDir(t, dir, cb) { + if (fs.existsSync(dir)) { + var tmpResult = tmp.dirSync(); + t.teardown(tmpResult.removeCallback); + var backup = path.join(tmpResult.name, path.basename(dir)); + mv(dir, backup, function (err) { + if (err) { + cb(err); + } else { + t.teardown(function () { + mv(backup, dir, cb); + }); + makeDir(t, dir, cb); + } + }); + } else { + makeDir(t, dir, cb); + } +} + +test('homedir module paths', function (t) { + t.plan(7); + + makeTempDir(t, hnm, function (err) { + t.error(err, 'no error with HNM temp dir'); + if (err) { + return t.end(); + } + + var bazHNMDir = path.join(hnm, 'baz'); + var dotMainDir = path.join(hnm, 'dot_main'); + copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNMDir); + copyDir.sync(path.join(__dirname, 'resolver/dot_main'), dotMainDir); + + var bazHNMmain = path.join(bazHNMDir, 'quux.js'); + t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`'); + var dotMainMain = path.join(dotMainDir, 'index.js'); + t.equal(require.resolve('dot_main'), dotMainMain, 'sanity check: require.resolve finds `dot_main`'); + + makeTempDir(t, hnl, function (err) { + t.error(err, 'no error with HNL temp dir'); + if (err) { + return t.end(); + } + var bazHNLDir = path.join(hnl, 'baz'); + copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNLDir); + + var dotSlashMainDir = path.join(hnl, 'dot_slash_main'); + var dotSlashMainMain = path.join(dotSlashMainDir, 'index.js'); + copyDir.sync(path.join(__dirname, 'resolver/dot_slash_main'), dotSlashMainDir); + + t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`'); + t.equal(require.resolve('dot_slash_main'), dotSlashMainMain, 'sanity check: require.resolve finds HNL `dot_slash_main`'); + + t.test('with temp dirs', function (st) { + st.plan(3); + + st.test('just in `$HOME/.node_modules`', function (s2t) { + s2t.plan(1); + + var res = resolve('dot_main'); + s2t.equal(res, dotMainMain, '`dot_main` resolves in `$HOME/.node_modules`'); + }); + + st.test('just in `$HOME/.node_libraries`', function (s2t) { + s2t.plan(1); + + var res = resolve('dot_slash_main'); + s2t.equal(res, dotSlashMainMain, '`dot_slash_main` resolves in `$HOME/.node_libraries`'); + }); + + st.test('in `$HOME/.node_libraries` and `$HOME/.node_modules`', function (s2t) { + s2t.plan(1); + + var res = resolve('baz'); + s2t.equal(res, bazHNMmain, '`baz` resolves in `$HOME/.node_modules` when in both'); + }); + }); + }); + }); +}); diff --git a/node_modules/resolve/test/mock.js b/node_modules/resolve/test/mock.js new file mode 100644 index 0000000..6116275 --- /dev/null +++ b/node_modules/resolve/test/mock.js @@ -0,0 +1,315 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('mock', function (t) { + t.plan(8); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('./baz', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg, undefined); + }); + + resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg, undefined); + }); + + resolve('baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module 'baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + resolve('../baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module '../baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('mock from package', function (t) { + t.plan(8); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, file)); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + 'package': { main: 'bar' }, + readFile: function (file, cb) { + cb(null, files[file]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('./baz', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg && pkg.main, 'bar'); + }); + + resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg && pkg.main, 'bar'); + }); + + resolve('baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module 'baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + resolve('../baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module '../baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('mock package', function (t) { + t.plan(2); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('bar', opts('/foo'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/node_modules/bar/baz.js')); + t.equal(pkg && pkg.main, './baz.js'); + }); +}); + +test('mock package from package', function (t) { + t.plan(2); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + 'package': { main: 'bar' }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('bar', opts('/foo'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/node_modules/bar/baz.js')); + t.equal(pkg && pkg.main, './baz.js'); + }); +}); + +test('symlinked', function (t) { + t.plan(4); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/bar/symlinked/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + dirs[path.resolve('/foo/bar/symlinked')] = true; + + function opts(basedir) { + return { + preserveSymlinks: false, + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + var resolved = path.resolve(file); + + if (resolved.indexOf('symlinked') >= 0) { + cb(null, resolved); + return; + } + + var ext = path.extname(resolved); + + if (ext) { + var dir = path.dirname(resolved); + var base = path.basename(resolved); + cb(null, path.join(dir, 'symlinked', base)); + } else { + cb(null, path.join(resolved, 'symlinked')); + } + } + }; + } + + resolve('./baz', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/symlinked/baz.js')); + t.equal(pkg, undefined); + }); + + resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/symlinked/baz.js')); + t.equal(pkg, undefined); + }); +}); + +test('readPackage', function (t) { + t.plan(3); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/something-else.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'boop'; + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + 'package': { main: 'bar' }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + t.test('with readFile', function (st) { + st.plan(3); + + resolve('bar', opts('/foo'), function (err, res, pkg) { + st.error(err); + st.equal(res, path.resolve('/foo/node_modules/bar/baz.js')); + st.equal(pkg && pkg.main, './baz.js'); + }); + }); + + var readPackage = function (readFile, file, cb) { + var barPackage = path.join('bar', 'package.json'); + if (file.slice(-barPackage.length) === barPackage) { + cb(null, { main: './something-else.js' }); + } else { + cb(null, JSON.parse(files[path.resolve(file)])); + } + }; + + t.test('with readPackage', function (st) { + st.plan(3); + + var options = opts('/foo'); + delete options.readFile; + options.readPackage = readPackage; + resolve('bar', options, function (err, res, pkg) { + st.error(err); + st.equal(res, path.resolve('/foo/node_modules/bar/something-else.js')); + st.equal(pkg && pkg.main, './something-else.js'); + }); + }); + + t.test('with readFile and readPackage', function (st) { + st.plan(1); + + var options = opts('/foo'); + options.readPackage = readPackage; + resolve('bar', options, function (err) { + st.throws(function () { throw err; }, TypeError, 'errors when both readFile and readPackage are provided'); + }); + }); +}); diff --git a/node_modules/resolve/test/mock_sync.js b/node_modules/resolve/test/mock_sync.js new file mode 100644 index 0000000..c5a7e2a --- /dev/null +++ b/node_modules/resolve/test/mock_sync.js @@ -0,0 +1,214 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('mock', function (t) { + t.plan(4); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + return file; + } + }; + } + + t.equal( + resolve.sync('./baz', opts('/foo/bar')), + path.resolve('/foo/bar/baz.js') + ); + + t.equal( + resolve.sync('./baz.js', opts('/foo/bar')), + path.resolve('/foo/bar/baz.js') + ); + + t.throws(function () { + resolve.sync('baz', opts('/foo/bar')); + }); + + t.throws(function () { + resolve.sync('../baz', opts('/foo/bar')); + }); +}); + +test('mock package', function (t) { + t.plan(1); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + return file; + } + }; + } + + t.equal( + resolve.sync('bar', opts('/foo')), + path.resolve('/foo/node_modules/bar/baz.js') + ); +}); + +test('symlinked', function (t) { + t.plan(2); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/bar/symlinked/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + dirs[path.resolve('/foo/bar/symlinked')] = true; + + function opts(basedir) { + return { + preserveSymlinks: false, + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + var resolved = path.resolve(file); + + if (resolved.indexOf('symlinked') >= 0) { + return resolved; + } + + var ext = path.extname(resolved); + + if (ext) { + var dir = path.dirname(resolved); + var base = path.basename(resolved); + return path.join(dir, 'symlinked', base); + } + return path.join(resolved, 'symlinked'); + } + }; + } + + t.equal( + resolve.sync('./baz', opts('/foo/bar')), + path.resolve('/foo/bar/symlinked/baz.js') + ); + + t.equal( + resolve.sync('./baz.js', opts('/foo/bar')), + path.resolve('/foo/bar/symlinked/baz.js') + ); +}); + +test('readPackageSync', function (t) { + t.plan(3); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/something-else.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'boop'; + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir, useReadPackage) { + return { + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: useReadPackage ? null : function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + return file; + } + }; + } + t.test('with readFile', function (st) { + st.plan(1); + + st.equal( + resolve.sync('bar', opts('/foo')), + path.resolve('/foo/node_modules/bar/baz.js') + ); + }); + + var readPackageSync = function (readFileSync, file) { + if (file.indexOf(path.join('bar', 'package.json')) >= 0) { + return { main: './something-else.js' }; + } + return JSON.parse(files[path.resolve(file)]); + }; + + t.test('with readPackage', function (st) { + st.plan(1); + + var options = opts('/foo'); + delete options.readFileSync; + options.readPackageSync = readPackageSync; + + st.equal( + resolve.sync('bar', options), + path.resolve('/foo/node_modules/bar/something-else.js') + ); + }); + + t.test('with readFile and readPackage', function (st) { + st.plan(1); + + var options = opts('/foo'); + options.readPackageSync = readPackageSync; + st.throws( + function () { resolve.sync('bar', options); }, + TypeError, + 'errors when both readFile and readPackage are provided' + ); + }); +}); + diff --git a/node_modules/resolve/test/module_dir.js b/node_modules/resolve/test/module_dir.js new file mode 100644 index 0000000..b50e5bb --- /dev/null +++ b/node_modules/resolve/test/module_dir.js @@ -0,0 +1,56 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('moduleDirectory strings', function (t) { + t.plan(4); + var dir = path.join(__dirname, 'module_dir'); + var xopts = { + basedir: dir, + moduleDirectory: 'xmodules' + }; + resolve('aaa', xopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/xmodules/aaa/index.js')); + }); + + var yopts = { + basedir: dir, + moduleDirectory: 'ymodules' + }; + resolve('aaa', yopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/ymodules/aaa/index.js')); + }); +}); + +test('moduleDirectory array', function (t) { + t.plan(6); + var dir = path.join(__dirname, 'module_dir'); + var aopts = { + basedir: dir, + moduleDirectory: ['xmodules', 'ymodules', 'zmodules'] + }; + resolve('aaa', aopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/xmodules/aaa/index.js')); + }); + + var bopts = { + basedir: dir, + moduleDirectory: ['zmodules', 'ymodules', 'xmodules'] + }; + resolve('aaa', bopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/ymodules/aaa/index.js')); + }); + + var copts = { + basedir: dir, + moduleDirectory: ['xmodules', 'ymodules', 'zmodules'] + }; + resolve('bbb', copts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/zmodules/bbb/main.js')); + }); +}); diff --git a/node_modules/resolve/test/module_dir/xmodules/aaa/index.js b/node_modules/resolve/test/module_dir/xmodules/aaa/index.js new file mode 100644 index 0000000..dd7cf7b --- /dev/null +++ b/node_modules/resolve/test/module_dir/xmodules/aaa/index.js @@ -0,0 +1 @@ +module.exports = function (x) { return x * 100; }; diff --git a/node_modules/resolve/test/module_dir/ymodules/aaa/index.js b/node_modules/resolve/test/module_dir/ymodules/aaa/index.js new file mode 100644 index 0000000..ef2d4d4 --- /dev/null +++ b/node_modules/resolve/test/module_dir/ymodules/aaa/index.js @@ -0,0 +1 @@ +module.exports = function (x) { return x + 100; }; diff --git a/node_modules/resolve/test/module_dir/zmodules/bbb/main.js b/node_modules/resolve/test/module_dir/zmodules/bbb/main.js new file mode 100644 index 0000000..e8ba629 --- /dev/null +++ b/node_modules/resolve/test/module_dir/zmodules/bbb/main.js @@ -0,0 +1 @@ +module.exports = function (n) { return n * 111; }; diff --git a/node_modules/resolve/test/module_dir/zmodules/bbb/package.json b/node_modules/resolve/test/module_dir/zmodules/bbb/package.json new file mode 100644 index 0000000..c13b8cf --- /dev/null +++ b/node_modules/resolve/test/module_dir/zmodules/bbb/package.json @@ -0,0 +1,3 @@ +{ + "main": "main.js" +} diff --git a/node_modules/resolve/test/node-modules-paths.js b/node_modules/resolve/test/node-modules-paths.js new file mode 100644 index 0000000..675441d --- /dev/null +++ b/node_modules/resolve/test/node-modules-paths.js @@ -0,0 +1,143 @@ +var test = require('tape'); +var path = require('path'); +var parse = path.parse || require('path-parse'); +var keys = require('object-keys'); + +var nodeModulesPaths = require('../lib/node-modules-paths'); + +var verifyDirs = function verifyDirs(t, start, dirs, moduleDirectories, paths) { + var moduleDirs = [].concat(moduleDirectories || 'node_modules'); + if (paths) { + for (var k = 0; k < paths.length; ++k) { + moduleDirs.push(path.basename(paths[k])); + } + } + + var foundModuleDirs = {}; + var uniqueDirs = {}; + var parsedDirs = {}; + for (var i = 0; i < dirs.length; ++i) { + var parsed = parse(dirs[i]); + if (!foundModuleDirs[parsed.base]) { foundModuleDirs[parsed.base] = 0; } + foundModuleDirs[parsed.base] += 1; + parsedDirs[parsed.dir] = true; + uniqueDirs[dirs[i]] = true; + } + t.equal(keys(parsedDirs).length >= start.split(path.sep).length, true, 'there are >= dirs than "start" has'); + var foundModuleDirNames = keys(foundModuleDirs); + t.deepEqual(foundModuleDirNames, moduleDirs, 'all desired module dirs were found'); + t.equal(keys(uniqueDirs).length, dirs.length, 'all dirs provided were unique'); + + var counts = {}; + for (var j = 0; j < foundModuleDirNames.length; ++j) { + counts[foundModuleDirs[j]] = true; + } + t.equal(keys(counts).length, 1, 'all found module directories had the same count'); +}; + +test('node-modules-paths', function (t) { + t.test('no options', function (t) { + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start); + + verifyDirs(t, start, dirs); + + t.end(); + }); + + t.test('empty options', function (t) { + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start, {}); + + verifyDirs(t, start, dirs); + + t.end(); + }); + + t.test('with paths=array option', function (t) { + var start = path.join(__dirname, 'resolver'); + var paths = ['a', 'b']; + var dirs = nodeModulesPaths(start, { paths: paths }); + + verifyDirs(t, start, dirs, null, paths); + + t.end(); + }); + + t.test('with paths=function option', function (t) { + var paths = function paths(request, absoluteStart, getNodeModulesDirs, opts) { + return getNodeModulesDirs().concat(path.join(absoluteStart, 'not node modules', request)); + }; + + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start, { paths: paths }, 'pkg'); + + verifyDirs(t, start, dirs, null, [path.join(start, 'not node modules', 'pkg')]); + + t.end(); + }); + + t.test('with paths=function skipping node modules resolution', function (t) { + var paths = function paths(request, absoluteStart, getNodeModulesDirs, opts) { + return []; + }; + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start, { paths: paths }); + t.deepEqual(dirs, [], 'no node_modules was computed'); + t.end(); + }); + + t.test('with moduleDirectory option', function (t) { + var start = path.join(__dirname, 'resolver'); + var moduleDirectory = 'not node modules'; + var dirs = nodeModulesPaths(start, { moduleDirectory: moduleDirectory }); + + verifyDirs(t, start, dirs, moduleDirectory); + + t.end(); + }); + + t.test('with 1 moduleDirectory and paths options', function (t) { + var start = path.join(__dirname, 'resolver'); + var paths = ['a', 'b']; + var moduleDirectory = 'not node modules'; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectory }); + + verifyDirs(t, start, dirs, moduleDirectory, paths); + + t.end(); + }); + + t.test('with 1+ moduleDirectory and paths options', function (t) { + var start = path.join(__dirname, 'resolver'); + var paths = ['a', 'b']; + var moduleDirectories = ['not node modules', 'other modules']; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories }); + + verifyDirs(t, start, dirs, moduleDirectories, paths); + + t.end(); + }); + + t.test('combine paths correctly on Windows', function (t) { + var start = 'C:\\Users\\username\\myProject\\src'; + var paths = []; + var moduleDirectories = ['node_modules', start]; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories }); + + t.equal(dirs.indexOf(path.resolve(start)) > -1, true, 'should contain start dir'); + + t.end(); + }); + + t.test('combine paths correctly on non-Windows', { skip: process.platform === 'win32' }, function (t) { + var start = '/Users/username/git/myProject/src'; + var paths = []; + var moduleDirectories = ['node_modules', '/Users/username/git/myProject/src']; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories }); + + t.equal(dirs.indexOf(path.resolve(start)) > -1, true, 'should contain start dir'); + + t.end(); + }); +}); diff --git a/node_modules/resolve/test/node_path.js b/node_modules/resolve/test/node_path.js new file mode 100644 index 0000000..e463d6c --- /dev/null +++ b/node_modules/resolve/test/node_path.js @@ -0,0 +1,70 @@ +var fs = require('fs'); +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('$NODE_PATH', function (t) { + t.plan(8); + + var isDir = function (dir, cb) { + if (dir === '/node_path' || dir === 'node_path/x') { + return cb(null, true); + } + fs.stat(dir, function (err, stat) { + if (!err) { + return cb(null, stat.isDirectory()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); + }; + + resolve('aaa', { + paths: [ + path.join(__dirname, '/node_path/x'), + path.join(__dirname, '/node_path/y') + ], + basedir: __dirname, + isDirectory: isDir + }, function (err, res) { + t.error(err); + t.equal(res, path.join(__dirname, '/node_path/x/aaa/index.js'), 'aaa resolves'); + }); + + resolve('bbb', { + paths: [ + path.join(__dirname, '/node_path/x'), + path.join(__dirname, '/node_path/y') + ], + basedir: __dirname, + isDirectory: isDir + }, function (err, res) { + t.error(err); + t.equal(res, path.join(__dirname, '/node_path/y/bbb/index.js'), 'bbb resolves'); + }); + + resolve('ccc', { + paths: [ + path.join(__dirname, '/node_path/x'), + path.join(__dirname, '/node_path/y') + ], + basedir: __dirname, + isDirectory: isDir + }, function (err, res) { + t.error(err); + t.equal(res, path.join(__dirname, '/node_path/x/ccc/index.js'), 'ccc resolves'); + }); + + // ensure that relative paths still resolve against the regular `node_modules` correctly + resolve('tap', { + paths: [ + 'node_path' + ], + basedir: path.join(__dirname, 'node_path/x'), + isDirectory: isDir + }, function (err, res) { + var root = require('tap/package.json').main; // eslint-disable-line global-require + t.error(err); + t.equal(res, path.resolve(__dirname, '..', 'node_modules/tap', root), 'tap resolves'); + }); +}); diff --git a/node_modules/resolve/test/node_path/x/aaa/index.js b/node_modules/resolve/test/node_path/x/aaa/index.js new file mode 100644 index 0000000..ad70d0b --- /dev/null +++ b/node_modules/resolve/test/node_path/x/aaa/index.js @@ -0,0 +1 @@ +module.exports = 'A'; diff --git a/node_modules/resolve/test/node_path/x/ccc/index.js b/node_modules/resolve/test/node_path/x/ccc/index.js new file mode 100644 index 0000000..a64132e --- /dev/null +++ b/node_modules/resolve/test/node_path/x/ccc/index.js @@ -0,0 +1 @@ +module.exports = 'C'; diff --git a/node_modules/resolve/test/node_path/y/bbb/index.js b/node_modules/resolve/test/node_path/y/bbb/index.js new file mode 100644 index 0000000..4d0f32e --- /dev/null +++ b/node_modules/resolve/test/node_path/y/bbb/index.js @@ -0,0 +1 @@ +module.exports = 'B'; diff --git a/node_modules/resolve/test/node_path/y/ccc/index.js b/node_modules/resolve/test/node_path/y/ccc/index.js new file mode 100644 index 0000000..793315e --- /dev/null +++ b/node_modules/resolve/test/node_path/y/ccc/index.js @@ -0,0 +1 @@ +module.exports = 'CY'; diff --git a/node_modules/resolve/test/nonstring.js b/node_modules/resolve/test/nonstring.js new file mode 100644 index 0000000..ef63c40 --- /dev/null +++ b/node_modules/resolve/test/nonstring.js @@ -0,0 +1,9 @@ +var test = require('tape'); +var resolve = require('../'); + +test('nonstring', function (t) { + t.plan(1); + resolve(555, function (err, res, pkg) { + t.ok(err); + }); +}); diff --git a/node_modules/resolve/test/pathfilter.js b/node_modules/resolve/test/pathfilter.js new file mode 100644 index 0000000..16519ae --- /dev/null +++ b/node_modules/resolve/test/pathfilter.js @@ -0,0 +1,75 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +var resolverDir = path.join(__dirname, '/pathfilter/deep_ref'); + +var pathFilterFactory = function (t) { + return function (pkg, x, remainder) { + t.equal(pkg.version, '1.2.3'); + t.equal(x, path.join(resolverDir, 'node_modules/deep/ref')); + t.equal(remainder, 'ref'); + return 'alt'; + }; +}; + +test('#62: deep module references and the pathFilter', function (t) { + t.test('deep/ref.js', function (st) { + st.plan(3); + + resolve('deep/ref', { basedir: resolverDir }, function (err, res, pkg) { + if (err) st.fail(err); + + st.equal(pkg.version, '1.2.3'); + st.equal(res, path.join(resolverDir, 'node_modules/deep/ref.js')); + }); + + var res = resolve.sync('deep/ref', { basedir: resolverDir }); + st.equal(res, path.join(resolverDir, 'node_modules/deep/ref.js')); + }); + + t.test('deep/deeper/ref', function (st) { + st.plan(4); + + resolve( + 'deep/deeper/ref', + { basedir: resolverDir }, + function (err, res, pkg) { + if (err) t.fail(err); + st.notEqual(pkg, undefined); + st.equal(pkg.version, '1.2.3'); + st.equal(res, path.join(resolverDir, 'node_modules/deep/deeper/ref.js')); + } + ); + + var res = resolve.sync( + 'deep/deeper/ref', + { basedir: resolverDir } + ); + st.equal(res, path.join(resolverDir, 'node_modules/deep/deeper/ref.js')); + }); + + t.test('deep/ref alt', function (st) { + st.plan(8); + + var pathFilter = pathFilterFactory(st); + + var res = resolve.sync( + 'deep/ref', + { basedir: resolverDir, pathFilter: pathFilter } + ); + st.equal(res, path.join(resolverDir, 'node_modules/deep/alt.js')); + + resolve( + 'deep/ref', + { basedir: resolverDir, pathFilter: pathFilter }, + function (err, res, pkg) { + if (err) st.fail(err); + st.equal(res, path.join(resolverDir, 'node_modules/deep/alt.js')); + st.end(); + } + ); + }); + + t.end(); +}); diff --git a/node_modules/resolve/test/pathfilter/deep_ref/main.js b/node_modules/resolve/test/pathfilter/deep_ref/main.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/precedence.js b/node_modules/resolve/test/precedence.js new file mode 100644 index 0000000..2febb59 --- /dev/null +++ b/node_modules/resolve/test/precedence.js @@ -0,0 +1,23 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('precedence', function (t) { + t.plan(3); + var dir = path.join(__dirname, 'precedence/aaa'); + + resolve('./', { basedir: dir }, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, 'index.js')); + t.equal(pkg.name, 'resolve'); + }); +}); + +test('./ should not load ${dir}.js', function (t) { // eslint-disable-line no-template-curly-in-string + t.plan(1); + var dir = path.join(__dirname, 'precedence/bbb'); + + resolve('./', { basedir: dir }, function (err, res, pkg) { + t.ok(err); + }); +}); diff --git a/node_modules/resolve/test/precedence/aaa.js b/node_modules/resolve/test/precedence/aaa.js new file mode 100644 index 0000000..b83a3e7 --- /dev/null +++ b/node_modules/resolve/test/precedence/aaa.js @@ -0,0 +1 @@ +module.exports = 'wtf'; diff --git a/node_modules/resolve/test/precedence/aaa/index.js b/node_modules/resolve/test/precedence/aaa/index.js new file mode 100644 index 0000000..e0f8f6a --- /dev/null +++ b/node_modules/resolve/test/precedence/aaa/index.js @@ -0,0 +1 @@ +module.exports = 'okok'; diff --git a/node_modules/resolve/test/precedence/aaa/main.js b/node_modules/resolve/test/precedence/aaa/main.js new file mode 100644 index 0000000..93542a9 --- /dev/null +++ b/node_modules/resolve/test/precedence/aaa/main.js @@ -0,0 +1 @@ +console.log(require('./')); diff --git a/node_modules/resolve/test/precedence/bbb.js b/node_modules/resolve/test/precedence/bbb.js new file mode 100644 index 0000000..2298f47 --- /dev/null +++ b/node_modules/resolve/test/precedence/bbb.js @@ -0,0 +1 @@ +module.exports = '>_<'; diff --git a/node_modules/resolve/test/precedence/bbb/main.js b/node_modules/resolve/test/precedence/bbb/main.js new file mode 100644 index 0000000..716b81d --- /dev/null +++ b/node_modules/resolve/test/precedence/bbb/main.js @@ -0,0 +1 @@ +console.log(require('./')); // should throw diff --git a/node_modules/resolve/test/resolver.js b/node_modules/resolve/test/resolver.js new file mode 100644 index 0000000..df8211a --- /dev/null +++ b/node_modules/resolve/test/resolver.js @@ -0,0 +1,597 @@ +var path = require('path'); +var fs = require('fs'); +var test = require('tape'); +var resolve = require('../'); +var async = require('../async'); + +test('`./async` entry point', function (t) { + t.equal(resolve, async, '`./async` entry point is the same as `main`'); + t.end(); +}); + +test('async foo', function (t) { + t.plan(12); + var dir = path.join(__dirname, 'resolver'); + + resolve('./foo', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg && pkg.name, 'resolve'); + }); + + resolve('./foo.js', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg && pkg.name, 'resolve'); + }); + + resolve('./foo', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg && pkg.main, 'resolver'); + }); + + resolve('./foo.js', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg.main, 'resolver'); + }); + + resolve('./foo', { basedir: dir, filename: path.join(dir, 'baz.js') }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + }); + + resolve('foo', { basedir: dir }, function (err) { + t.equal(err.message, "Cannot find module 'foo' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + // Test that filename is reported as the "from" value when passed. + resolve('foo', { basedir: dir, filename: path.join(dir, 'baz.js') }, function (err) { + t.equal(err.message, "Cannot find module 'foo' from '" + path.join(dir, 'baz.js') + "'"); + }); +}); + +test('bar', function (t) { + t.plan(6); + var dir = path.join(__dirname, 'resolver'); + + resolve('foo', { basedir: dir + '/bar' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js')); + t.equal(pkg, undefined); + }); + + resolve('foo', { basedir: dir + '/bar' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js')); + t.equal(pkg, undefined); + }); + + resolve('foo', { basedir: dir + '/bar', 'package': { main: 'bar' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js')); + t.equal(pkg.main, 'bar'); + }); +}); + +test('baz', function (t) { + t.plan(4); + var dir = path.join(__dirname, 'resolver'); + + resolve('./baz', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'baz/quux.js')); + t.equal(pkg.main, 'quux.js'); + }); + + resolve('./baz', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'baz/quux.js')); + t.equal(pkg.main, 'quux.js'); + }); +}); + +test('biz', function (t) { + t.plan(24); + var dir = path.join(__dirname, 'resolver/biz/node_modules'); + + resolve('./grux', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg, undefined); + }); + + resolve('./grux', { basedir: dir, 'package': { main: 'biz' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg.main, 'biz'); + }); + + resolve('./garply', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('./garply', { basedir: dir, 'package': { main: 'biz' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('tiv', { basedir: dir + '/grux' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg, undefined); + }); + + resolve('tiv', { basedir: dir + '/grux', 'package': { main: 'grux' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg.main, 'grux'); + }); + + resolve('tiv', { basedir: dir + '/garply' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg, undefined); + }); + + resolve('tiv', { basedir: dir + '/garply', 'package': { main: './lib' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('grux', { basedir: dir + '/tiv' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg, undefined); + }); + + resolve('grux', { basedir: dir + '/tiv', 'package': { main: 'tiv' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg.main, 'tiv'); + }); + + resolve('garply', { basedir: dir + '/tiv' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('garply', { basedir: dir + '/tiv', 'package': { main: 'tiv' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); +}); + +test('quux', function (t) { + t.plan(2); + var dir = path.join(__dirname, 'resolver/quux'); + + resolve('./foo', { basedir: dir, 'package': { main: 'quux' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo/index.js')); + t.equal(pkg.main, 'quux'); + }); +}); + +test('normalize', function (t) { + t.plan(2); + var dir = path.join(__dirname, 'resolver/biz/node_modules/grux'); + + resolve('../grux', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'index.js')); + t.equal(pkg, undefined); + }); +}); + +test('cup', function (t) { + t.plan(5); + var dir = path.join(__dirname, 'resolver'); + + resolve('./cup', { basedir: dir, extensions: ['.js', '.coffee'] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'cup.coffee')); + }); + + resolve('./cup.coffee', { basedir: dir }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'cup.coffee')); + }); + + resolve('./cup', { basedir: dir, extensions: ['.js'] }, function (err, res) { + t.equal(err.message, "Cannot find module './cup' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + // Test that filename is reported as the "from" value when passed. + resolve('./cup', { basedir: dir, extensions: ['.js'], filename: path.join(dir, 'cupboard.js') }, function (err, res) { + t.equal(err.message, "Cannot find module './cup' from '" + path.join(dir, 'cupboard.js') + "'"); + }); +}); + +test('mug', function (t) { + t.plan(3); + var dir = path.join(__dirname, 'resolver'); + + resolve('./mug', { basedir: dir }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'mug.js')); + }); + + resolve('./mug', { basedir: dir, extensions: ['.coffee', '.js'] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, '/mug.coffee')); + }); + + resolve('./mug', { basedir: dir, extensions: ['.js', '.coffee'] }, function (err, res) { + t.equal(res, path.join(dir, '/mug.js')); + }); +}); + +test('other path', function (t) { + t.plan(6); + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'bar'); + var otherDir = path.join(resolverDir, 'other_path'); + + resolve('root', { basedir: dir, paths: [otherDir] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(resolverDir, 'other_path/root.js')); + }); + + resolve('lib/other-lib', { basedir: dir, paths: [otherDir] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(resolverDir, 'other_path/lib/other-lib.js')); + }); + + resolve('root', { basedir: dir }, function (err, res) { + t.equal(err.message, "Cannot find module 'root' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + resolve('zzz', { basedir: dir, paths: [otherDir] }, function (err, res) { + t.equal(err.message, "Cannot find module 'zzz' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('path iterator', function (t) { + t.plan(2); + + var resolverDir = path.join(__dirname, 'resolver'); + + var exactIterator = function (x, start, getPackageCandidates, opts) { + return [path.join(resolverDir, x)]; + }; + + resolve('baz', { packageIterator: exactIterator }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(resolverDir, 'baz/quux.js')); + t.equal(pkg && pkg.name, 'baz'); + }); +}); + +test('incorrect main', function (t) { + t.plan(1); + + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'incorrect_main'); + + resolve('./incorrect_main', { basedir: resolverDir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'index.js')); + }); +}); + +test('missing index', function (t) { + t.plan(2); + + var resolverDir = path.join(__dirname, 'resolver'); + resolve('./missing_index', { basedir: resolverDir }, function (err, res, pkg) { + t.ok(err instanceof Error); + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + }); +}); + +test('missing main', function (t) { + t.plan(1); + + var resolverDir = path.join(__dirname, 'resolver'); + + resolve('./missing_main', { basedir: resolverDir }, function (err, res, pkg) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + }); +}); + +test('null main', function (t) { + t.plan(1); + + var resolverDir = path.join(__dirname, 'resolver'); + + resolve('./null_main', { basedir: resolverDir }, function (err, res, pkg) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + }); +}); + +test('main: false', function (t) { + t.plan(2); + + var basedir = path.join(__dirname, 'resolver'); + var dir = path.join(basedir, 'false_main'); + resolve('./false_main', { basedir: basedir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal( + res, + path.join(dir, 'index.js'), + '`"main": false`: resolves to `index.js`' + ); + t.deepEqual(pkg, { + name: 'false_main', + main: false + }); + }); +}); + +test('without basedir', function (t) { + t.plan(1); + + var dir = path.join(__dirname, 'resolver/without_basedir'); + var tester = require(path.join(dir, 'main.js')); // eslint-disable-line global-require + + tester(t, function (err, res, pkg) { + if (err) { + t.fail(err); + } else { + t.equal(res, path.join(dir, 'node_modules/mymodule.js')); + } + }); +}); + +test('#52 - incorrectly resolves module-paths like "./someFolder/" when there is a file of the same name', function (t) { + t.plan(2); + + var dir = path.join(__dirname, 'resolver'); + + resolve('./foo', { basedir: path.join(dir, 'same_names') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo.js')); + }); + + resolve('./foo/', { basedir: path.join(dir, 'same_names') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo/index.js')); + }); +}); + +test('#211 - incorrectly resolves module-paths like "." when from inside a folder with a sibling file of the same name', function (t) { + t.plan(2); + + var dir = path.join(__dirname, 'resolver'); + + resolve('./', { basedir: path.join(dir, 'same_names/foo') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo/index.js')); + }); + + resolve('.', { basedir: path.join(dir, 'same_names/foo') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo/index.js')); + }); +}); + +test('async: #121 - treating an existing file as a dir when no basedir', function (t) { + var testFile = path.basename(__filename); + + t.test('sanity check', function (st) { + st.plan(1); + resolve('./' + testFile, function (err, res, pkg) { + if (err) t.fail(err); + st.equal(res, __filename, 'sanity check'); + }); + }); + + t.test('with a fake directory', function (st) { + st.plan(4); + + resolve('./' + testFile + '/blah', function (err, res, pkg) { + st.ok(err, 'there is an error'); + st.notOk(res, 'no result'); + + st.equal(err && err.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); + st.equal( + err && err.message, + 'Cannot find module \'./' + testFile + '/blah\' from \'' + __dirname + '\'', + 'can not find nonexistent module' + ); + st.end(); + }); + }); + + t.end(); +}); + +test('async dot main', function (t) { + var start = new Date(); + t.plan(3); + resolve('./resolver/dot_main', function (err, ret) { + t.notOk(err); + t.equal(ret, path.join(__dirname, 'resolver/dot_main/index.js')); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); + }); +}); + +test('async dot slash main', function (t) { + var start = new Date(); + t.plan(3); + resolve('./resolver/dot_slash_main', function (err, ret) { + t.notOk(err); + t.equal(ret, path.join(__dirname, 'resolver/dot_slash_main/index.js')); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); + }); +}); + +test('not a directory', function (t) { + t.plan(6); + var path = './foo'; + resolve(path, { basedir: __filename }, function (err, res, pkg) { + t.ok(err, 'a non-directory errors'); + t.equal(arguments.length, 1); + t.equal(res, undefined); + t.equal(pkg, undefined); + + t.equal(err && err.message, 'Cannot find module \'' + path + '\' from \'' + __filename + '\''); + t.equal(err && err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('non-string "main" field in package.json', function (t) { + t.plan(5); + + var dir = path.join(__dirname, 'resolver'); + resolve('./invalid_main', { basedir: dir }, function (err, res, pkg) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + t.equal(res, undefined, 'res is undefined'); + t.equal(pkg, undefined, 'pkg is undefined'); + }); +}); + +test('non-string "main" field in package.json', function (t) { + t.plan(5); + + var dir = path.join(__dirname, 'resolver'); + resolve('./invalid_main', { basedir: dir }, function (err, res, pkg) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + t.equal(res, undefined, 'res is undefined'); + t.equal(pkg, undefined, 'pkg is undefined'); + }); +}); + +test('browser field in package.json', function (t) { + t.plan(3); + + var dir = path.join(__dirname, 'resolver'); + resolve( + './browser_field', + { + basedir: dir, + packageFilter: function packageFilter(pkg) { + if (pkg.browser) { + pkg.main = pkg.browser; // eslint-disable-line no-param-reassign + delete pkg.browser; // eslint-disable-line no-param-reassign + } + return pkg; + } + }, + function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'browser_field', 'b.js')); + t.equal(pkg && pkg.main, 'b'); + t.equal(pkg && pkg.browser, undefined); + } + ); +}); + +test('absolute paths', function (t) { + t.plan(4); + + var extensionless = __filename.slice(0, -path.extname(__filename).length); + + resolve(__filename, function (err, res) { + t.equal( + res, + __filename, + 'absolute path to this file resolves' + ); + }); + resolve(extensionless, function (err, res) { + t.equal( + res, + __filename, + 'extensionless absolute path to this file resolves' + ); + }); + resolve(__filename, { basedir: process.cwd() }, function (err, res) { + t.equal( + res, + __filename, + 'absolute path to this file with a basedir resolves' + ); + }); + resolve(extensionless, { basedir: process.cwd() }, function (err, res) { + t.equal( + res, + __filename, + 'extensionless absolute path to this file with a basedir resolves' + ); + }); +}); + +var malformedDir = path.join(__dirname, 'resolver/malformed_package_json'); +test('malformed package.json', { skip: !fs.existsSync(malformedDir) }, function (t) { + /* eslint operator-linebreak: ["error", "before"], function-paren-newline: "off" */ + t.plan( + (3 * 3) // 3 sets of 3 assertions in the final callback + + 2 // 1 readPackage call with malformed package.json + ); + + var basedir = malformedDir; + var expected = path.join(basedir, 'index.js'); + + resolve('./index.js', { basedir: basedir }, function (err, res, pkg) { + t.error(err, 'no error'); + t.equal(res, expected, 'malformed package.json is silently ignored'); + t.equal(pkg, undefined, 'malformed package.json gives an undefined `pkg` argument'); + }); + + resolve( + './index.js', + { + basedir: basedir, + packageFilter: function (pkg, pkgfile, dir) { + t.fail('should not reach here'); + } + }, + function (err, res, pkg) { + t.error(err, 'with packageFilter: no error'); + t.equal(res, expected, 'with packageFilter: malformed package.json is silently ignored'); + t.equal(pkg, undefined, 'with packageFilter: malformed package.json gives an undefined `pkg` argument'); + } + ); + + resolve( + './index.js', + { + basedir: basedir, + readPackage: function (readFile, pkgfile, cb) { + t.equal(pkgfile, path.join(basedir, 'package.json'), 'readPackageSync: `pkgfile` is package.json path'); + readFile(pkgfile, function (err, result) { + try { + cb(null, JSON.parse(result)); + } catch (e) { + t.ok(e instanceof SyntaxError, 'readPackage: malformed package.json parses as a syntax error'); + cb(null); + } + }); + } + }, + function (err, res, pkg) { + t.error(err, 'with readPackage: no error'); + t.equal(res, expected, 'with readPackage: malformed package.json is silently ignored'); + t.equal(pkg, undefined, 'with readPackage: malformed package.json gives an undefined `pkg` argument'); + } + ); +}); diff --git a/node_modules/resolve/test/resolver/baz/doom.js b/node_modules/resolve/test/resolver/baz/doom.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/baz/package.json b/node_modules/resolve/test/resolver/baz/package.json new file mode 100644 index 0000000..2f77720 --- /dev/null +++ b/node_modules/resolve/test/resolver/baz/package.json @@ -0,0 +1,4 @@ +{ + "name": "baz", + "main": "quux.js" +} diff --git a/node_modules/resolve/test/resolver/baz/quux.js b/node_modules/resolve/test/resolver/baz/quux.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/resolve/test/resolver/baz/quux.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/browser_field/a.js b/node_modules/resolve/test/resolver/browser_field/a.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/browser_field/b.js b/node_modules/resolve/test/resolver/browser_field/b.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/browser_field/package.json b/node_modules/resolve/test/resolver/browser_field/package.json new file mode 100644 index 0000000..bf406f0 --- /dev/null +++ b/node_modules/resolve/test/resolver/browser_field/package.json @@ -0,0 +1,5 @@ +{ + "name": "browser_field", + "main": "a", + "browser": "b" +} diff --git a/node_modules/resolve/test/resolver/cup.coffee b/node_modules/resolve/test/resolver/cup.coffee new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/node_modules/resolve/test/resolver/cup.coffee @@ -0,0 +1 @@ + diff --git a/node_modules/resolve/test/resolver/dot_main/index.js b/node_modules/resolve/test/resolver/dot_main/index.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/resolve/test/resolver/dot_main/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/dot_main/package.json b/node_modules/resolve/test/resolver/dot_main/package.json new file mode 100644 index 0000000..d7f4fc8 --- /dev/null +++ b/node_modules/resolve/test/resolver/dot_main/package.json @@ -0,0 +1,3 @@ +{ + "main": "." +} diff --git a/node_modules/resolve/test/resolver/dot_slash_main/index.js b/node_modules/resolve/test/resolver/dot_slash_main/index.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/resolve/test/resolver/dot_slash_main/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/dot_slash_main/package.json b/node_modules/resolve/test/resolver/dot_slash_main/package.json new file mode 100644 index 0000000..f51287b --- /dev/null +++ b/node_modules/resolve/test/resolver/dot_slash_main/package.json @@ -0,0 +1,3 @@ +{ + "main": "./" +} diff --git a/node_modules/resolve/test/resolver/false_main/index.js b/node_modules/resolve/test/resolver/false_main/index.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/false_main/package.json b/node_modules/resolve/test/resolver/false_main/package.json new file mode 100644 index 0000000..a7416c0 --- /dev/null +++ b/node_modules/resolve/test/resolver/false_main/package.json @@ -0,0 +1,4 @@ +{ + "name": "false_main", + "main": false +} diff --git a/node_modules/resolve/test/resolver/foo.js b/node_modules/resolve/test/resolver/foo.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/resolve/test/resolver/foo.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/incorrect_main/index.js b/node_modules/resolve/test/resolver/incorrect_main/index.js new file mode 100644 index 0000000..bc1fb0a --- /dev/null +++ b/node_modules/resolve/test/resolver/incorrect_main/index.js @@ -0,0 +1,2 @@ +// this is the actual main file 'index.js', not 'wrong.js' like the package.json would indicate +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/incorrect_main/package.json b/node_modules/resolve/test/resolver/incorrect_main/package.json new file mode 100644 index 0000000..b718804 --- /dev/null +++ b/node_modules/resolve/test/resolver/incorrect_main/package.json @@ -0,0 +1,3 @@ +{ + "main": "wrong.js" +} diff --git a/node_modules/resolve/test/resolver/invalid_main/package.json b/node_modules/resolve/test/resolver/invalid_main/package.json new file mode 100644 index 0000000..0590748 --- /dev/null +++ b/node_modules/resolve/test/resolver/invalid_main/package.json @@ -0,0 +1,7 @@ +{ + "name": "invalid_main", + "main": [ + "why is this a thing", + "srsly omg wtf" + ] +} diff --git a/node_modules/resolve/test/resolver/mug.coffee b/node_modules/resolve/test/resolver/mug.coffee new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/mug.js b/node_modules/resolve/test/resolver/mug.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/multirepo/lerna.json b/node_modules/resolve/test/resolver/multirepo/lerna.json new file mode 100644 index 0000000..d6707ca --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/lerna.json @@ -0,0 +1,6 @@ +{ + "packages": [ + "packages/*" + ], + "version": "0.0.0" +} diff --git a/node_modules/resolve/test/resolver/multirepo/package.json b/node_modules/resolve/test/resolver/multirepo/package.json new file mode 100644 index 0000000..4391d39 --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/package.json @@ -0,0 +1,20 @@ +{ + "name": "ljharb-monorepo-symlink-test", + "private": true, + "version": "0.0.0", + "description": "", + "main": "index.js", + "scripts": { + "postinstall": "lerna bootstrap", + "test": "node packages/package-a" + }, + "author": "", + "license": "MIT", + "dependencies": { + "jquery": "^3.3.1", + "resolve": "../../../" + }, + "devDependencies": { + "lerna": "^3.4.3" + } +} diff --git a/node_modules/resolve/test/resolver/multirepo/packages/package-a/index.js b/node_modules/resolve/test/resolver/multirepo/packages/package-a/index.js new file mode 100644 index 0000000..8875a32 --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/packages/package-a/index.js @@ -0,0 +1,35 @@ +'use strict'; + +var assert = require('assert'); +var path = require('path'); +var resolve = require('resolve'); + +var basedir = __dirname + '/node_modules/@my-scope/package-b'; + +var expected = path.join(__dirname, '../../node_modules/jquery/dist/jquery.js'); + +/* + * preserveSymlinks === false + * will search NPM package from + * - packages/package-b/node_modules + * - packages/node_modules + * - node_modules + */ +assert.equal(resolve.sync('jquery', { basedir: basedir, preserveSymlinks: false }), expected); +assert.equal(resolve.sync('../../node_modules/jquery', { basedir: basedir, preserveSymlinks: false }), expected); + +/* + * preserveSymlinks === true + * will search NPM package from + * - packages/package-a/node_modules/@my-scope/packages/package-b/node_modules + * - packages/package-a/node_modules/@my-scope/packages/node_modules + * - packages/package-a/node_modules/@my-scope/node_modules + * - packages/package-a/node_modules/node_modules + * - packages/package-a/node_modules + * - packages/node_modules + * - node_modules + */ +assert.equal(resolve.sync('jquery', { basedir: basedir, preserveSymlinks: true }), expected); +assert.equal(resolve.sync('../../../../../node_modules/jquery', { basedir: basedir, preserveSymlinks: true }), expected); + +console.log(' * all monorepo paths successfully resolved through symlinks'); diff --git a/node_modules/resolve/test/resolver/multirepo/packages/package-a/package.json b/node_modules/resolve/test/resolver/multirepo/packages/package-a/package.json new file mode 100644 index 0000000..204de51 --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/packages/package-a/package.json @@ -0,0 +1,14 @@ +{ + "name": "@my-scope/package-a", + "version": "0.0.0", + "private": true, + "description": "", + "license": "MIT", + "main": "index.js", + "scripts": { + "test": "echo \"Error: run tests from root\" && exit 1" + }, + "dependencies": { + "@my-scope/package-b": "^0.0.0" + } +} diff --git a/node_modules/resolve/test/resolver/multirepo/packages/package-b/index.js b/node_modules/resolve/test/resolver/multirepo/packages/package-b/index.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/multirepo/packages/package-b/package.json b/node_modules/resolve/test/resolver/multirepo/packages/package-b/package.json new file mode 100644 index 0000000..f57c3b5 --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/packages/package-b/package.json @@ -0,0 +1,14 @@ +{ + "name": "@my-scope/package-b", + "private": true, + "version": "0.0.0", + "description": "", + "license": "MIT", + "main": "index.js", + "scripts": { + "test": "echo \"Error: run tests from root\" && exit 1" + }, + "dependencies": { + "@my-scope/package-a": "^0.0.0" + } +} diff --git a/node_modules/resolve/test/resolver/nested_symlinks/mylib/async.js b/node_modules/resolve/test/resolver/nested_symlinks/mylib/async.js new file mode 100644 index 0000000..9b4846a --- /dev/null +++ b/node_modules/resolve/test/resolver/nested_symlinks/mylib/async.js @@ -0,0 +1,26 @@ +var a = require.resolve('buffer/').replace(process.cwd(), '$CWD'); +var b; +var c; + +var test = function test() { + console.log(a, ': require.resolve, preserveSymlinks ' + (process.execArgv.indexOf('preserve-symlinks') > -1 ? 'true' : 'false')); + console.log(b, ': preserveSymlinks true'); + console.log(c, ': preserveSymlinks false'); + + if (a !== b && a !== c) { + throw 'async: no match'; + } + console.log('async: success! a matched either b or c\n'); +}; + +require('resolve')('buffer/', { preserveSymlinks: true }, function (err, result) { + if (err) { throw err; } + b = result.replace(process.cwd(), '$CWD'); + if (b && c) { test(); } +}); +require('resolve')('buffer/', { preserveSymlinks: false }, function (err, result) { + if (err) { throw err; } + c = result.replace(process.cwd(), '$CWD'); + if (b && c) { test(); } +}); + diff --git a/node_modules/resolve/test/resolver/nested_symlinks/mylib/package.json b/node_modules/resolve/test/resolver/nested_symlinks/mylib/package.json new file mode 100644 index 0000000..acfe9e9 --- /dev/null +++ b/node_modules/resolve/test/resolver/nested_symlinks/mylib/package.json @@ -0,0 +1,15 @@ +{ + "name": "mylib", + "version": "0.0.0", + "description": "", + "private": true, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "buffer": "*" + } +} diff --git a/node_modules/resolve/test/resolver/nested_symlinks/mylib/sync.js b/node_modules/resolve/test/resolver/nested_symlinks/mylib/sync.js new file mode 100644 index 0000000..3283efc --- /dev/null +++ b/node_modules/resolve/test/resolver/nested_symlinks/mylib/sync.js @@ -0,0 +1,12 @@ +var a = require.resolve('buffer/').replace(process.cwd(), '$CWD'); +var b = require('resolve').sync('buffer/', { preserveSymlinks: true }).replace(process.cwd(), '$CWD'); +var c = require('resolve').sync('buffer/', { preserveSymlinks: false }).replace(process.cwd(), '$CWD'); + +console.log(a, ': require.resolve, preserveSymlinks ' + (process.execArgv.indexOf('preserve-symlinks') > -1 ? 'true' : 'false')); +console.log(b, ': preserveSymlinks true'); +console.log(c, ': preserveSymlinks false'); + +if (a !== b && a !== c) { + throw 'sync: no match'; +} +console.log('sync: success! a matched either b or c\n'); diff --git a/node_modules/resolve/test/resolver/other_path/lib/other-lib.js b/node_modules/resolve/test/resolver/other_path/lib/other-lib.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/other_path/root.js b/node_modules/resolve/test/resolver/other_path/root.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/quux/foo/index.js b/node_modules/resolve/test/resolver/quux/foo/index.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/resolve/test/resolver/quux/foo/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/same_names/foo.js b/node_modules/resolve/test/resolver/same_names/foo.js new file mode 100644 index 0000000..888cae3 --- /dev/null +++ b/node_modules/resolve/test/resolver/same_names/foo.js @@ -0,0 +1 @@ +module.exports = 42; diff --git a/node_modules/resolve/test/resolver/same_names/foo/index.js b/node_modules/resolve/test/resolver/same_names/foo/index.js new file mode 100644 index 0000000..bd816ea --- /dev/null +++ b/node_modules/resolve/test/resolver/same_names/foo/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/symlinked/_/node_modules/foo.js b/node_modules/resolve/test/resolver/symlinked/_/node_modules/foo.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/symlinked/_/symlink_target/.gitkeep b/node_modules/resolve/test/resolver/symlinked/_/symlink_target/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/resolver/symlinked/package/bar.js b/node_modules/resolve/test/resolver/symlinked/package/bar.js new file mode 100644 index 0000000..cb1c2c0 --- /dev/null +++ b/node_modules/resolve/test/resolver/symlinked/package/bar.js @@ -0,0 +1 @@ +module.exports = 'bar'; diff --git a/node_modules/resolve/test/resolver/symlinked/package/package.json b/node_modules/resolve/test/resolver/symlinked/package/package.json new file mode 100644 index 0000000..8e1b585 --- /dev/null +++ b/node_modules/resolve/test/resolver/symlinked/package/package.json @@ -0,0 +1,3 @@ +{ + "main": "bar.js" +} \ No newline at end of file diff --git a/node_modules/resolve/test/resolver/without_basedir/main.js b/node_modules/resolve/test/resolver/without_basedir/main.js new file mode 100644 index 0000000..5b31975 --- /dev/null +++ b/node_modules/resolve/test/resolver/without_basedir/main.js @@ -0,0 +1,5 @@ +var resolve = require('../../../'); + +module.exports = function (t, cb) { + resolve('mymodule', null, cb); +}; diff --git a/node_modules/resolve/test/resolver_sync.js b/node_modules/resolve/test/resolver_sync.js new file mode 100644 index 0000000..a6df8ce --- /dev/null +++ b/node_modules/resolve/test/resolver_sync.js @@ -0,0 +1,730 @@ +var path = require('path'); +var fs = require('fs'); +var test = require('tape'); + +var resolve = require('../'); +var sync = require('../sync'); + +var requireResolveSupportsPaths = require.resolve.length > 1 + && !(/^v12\.[012]\./).test(process.version); // broken in v12.0-12.2, see https://github.com/nodejs/node/issues/27794 + +var requireResolveDefaultPathsBroken = (/^v8\.9\.|^v9\.[01]\.0|^v9\.2\./).test(process.version); +// broken in node v8.9.x, v9.0, v9.1, v9.2.x. see https://github.com/nodejs/node/pull/17113 + +test('`./sync` entry point', function (t) { + t.equal(resolve.sync, sync, '`./sync` entry point is the same as `.sync` on `main`'); + t.end(); +}); + +test('foo', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./foo', { basedir: dir }), + path.join(dir, 'foo.js'), + './foo' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo', { basedir: dir }), + require.resolve('./foo', { paths: [dir] }), + './foo: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./foo.js', { basedir: dir }), + path.join(dir, 'foo.js'), + './foo.js' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo.js', { basedir: dir }), + require.resolve('./foo.js', { paths: [dir] }), + './foo.js: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./foo.js', { basedir: dir, filename: path.join(dir, 'bar.js') }), + path.join(dir, 'foo.js') + ); + + t.throws(function () { + resolve.sync('foo', { basedir: dir }); + }); + + // Test that filename is reported as the "from" value when passed. + t.throws( + function () { + resolve.sync('foo', { basedir: dir, filename: path.join(dir, 'bar.js') }); + }, + { + name: 'Error', + message: "Cannot find module 'foo' from '" + path.join(dir, 'bar.js') + "'" + } + ); + + t.end(); +}); + +test('bar', function (t) { + var dir = path.join(__dirname, 'resolver'); + + var basedir = path.join(dir, 'bar'); + + t.equal( + resolve.sync('foo', { basedir: basedir }), + path.join(dir, 'bar/node_modules/foo/index.js'), + 'foo in bar' + ); + if (!requireResolveDefaultPathsBroken && requireResolveSupportsPaths) { + t.equal( + resolve.sync('foo', { basedir: basedir }), + require.resolve('foo', { paths: [basedir] }), + 'foo in bar: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('baz', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./baz', { basedir: dir }), + path.join(dir, 'baz/quux.js'), + './baz' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./baz', { basedir: dir }), + require.resolve('./baz', { paths: [dir] }), + './baz: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('biz', function (t) { + var dir = path.join(__dirname, 'resolver/biz/node_modules'); + + t.equal( + resolve.sync('./grux', { basedir: dir }), + path.join(dir, 'grux/index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./grux', { basedir: dir }), + require.resolve('./grux', { paths: [dir] }), + './grux: resolve.sync === require.resolve' + ); + } + + var tivDir = path.join(dir, 'grux'); + t.equal( + resolve.sync('tiv', { basedir: tivDir }), + path.join(dir, 'tiv/index.js') + ); + if (!requireResolveDefaultPathsBroken && requireResolveSupportsPaths) { + t.equal( + resolve.sync('tiv', { basedir: tivDir }), + require.resolve('tiv', { paths: [tivDir] }), + 'tiv: resolve.sync === require.resolve' + ); + } + + var gruxDir = path.join(dir, 'tiv'); + t.equal( + resolve.sync('grux', { basedir: gruxDir }), + path.join(dir, 'grux/index.js') + ); + if (!requireResolveDefaultPathsBroken && requireResolveSupportsPaths) { + t.equal( + resolve.sync('grux', { basedir: gruxDir }), + require.resolve('grux', { paths: [gruxDir] }), + 'grux: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('normalize', function (t) { + var dir = path.join(__dirname, 'resolver/biz/node_modules/grux'); + + t.equal( + resolve.sync('../grux', { basedir: dir }), + path.join(dir, 'index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('../grux', { basedir: dir }), + require.resolve('../grux', { paths: [dir] }), + '../grux: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('cup', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./cup', { + basedir: dir, + extensions: ['.js', '.coffee'] + }), + path.join(dir, 'cup.coffee'), + './cup -> ./cup.coffee' + ); + + t.equal( + resolve.sync('./cup.coffee', { basedir: dir }), + path.join(dir, 'cup.coffee'), + './cup.coffee' + ); + + t.throws(function () { + resolve.sync('./cup', { + basedir: dir, + extensions: ['.js'] + }); + }); + + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./cup.coffee', { basedir: dir, extensions: ['.js', '.coffee'] }), + require.resolve('./cup.coffee', { paths: [dir] }), + './cup.coffee: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('mug', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./mug', { basedir: dir }), + path.join(dir, 'mug.js'), + './mug -> ./mug.js' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./mug', { basedir: dir }), + require.resolve('./mug', { paths: [dir] }), + './mug: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./mug', { + basedir: dir, + extensions: ['.coffee', '.js'] + }), + path.join(dir, 'mug.coffee'), + './mug -> ./mug.coffee' + ); + + t.equal( + resolve.sync('./mug', { + basedir: dir, + extensions: ['.js', '.coffee'] + }), + path.join(dir, 'mug.js'), + './mug -> ./mug.js' + ); + + t.end(); +}); + +test('other path', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'bar'); + var otherDir = path.join(resolverDir, 'other_path'); + + t.equal( + resolve.sync('root', { + basedir: dir, + paths: [otherDir] + }), + path.join(resolverDir, 'other_path/root.js') + ); + + t.equal( + resolve.sync('lib/other-lib', { + basedir: dir, + paths: [otherDir] + }), + path.join(resolverDir, 'other_path/lib/other-lib.js') + ); + + t.throws(function () { + resolve.sync('root', { basedir: dir }); + }); + + t.throws(function () { + resolve.sync('zzz', { + basedir: dir, + paths: [otherDir] + }); + }); + + t.end(); +}); + +test('path iterator', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + + var exactIterator = function (x, start, getPackageCandidates, opts) { + return [path.join(resolverDir, x)]; + }; + + t.equal( + resolve.sync('baz', { packageIterator: exactIterator }), + path.join(resolverDir, 'baz/quux.js') + ); + + t.end(); +}); + +test('incorrect main', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'incorrect_main'); + + t.equal( + resolve.sync('./incorrect_main', { basedir: resolverDir }), + path.join(dir, 'index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./incorrect_main', { basedir: resolverDir }), + require.resolve('./incorrect_main', { paths: [resolverDir] }), + './incorrect_main: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('missing index', function (t) { + t.plan(requireResolveSupportsPaths ? 2 : 1); + + var resolverDir = path.join(__dirname, 'resolver'); + try { + resolve.sync('./missing_index', { basedir: resolverDir }); + t.fail('did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + if (requireResolveSupportsPaths) { + try { + require.resolve('./missing_index', { basedir: resolverDir }); + t.fail('require.resolve did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + } +}); + +test('missing main', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + + try { + resolve.sync('./missing_main', { basedir: resolverDir }); + t.fail('require.resolve did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + if (requireResolveSupportsPaths) { + try { + resolve.sync('./missing_main', { basedir: resolverDir }); + t.fail('require.resolve did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + } + + t.end(); +}); + +test('null main', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + + try { + resolve.sync('./null_main', { basedir: resolverDir }); + t.fail('require.resolve did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + if (requireResolveSupportsPaths) { + try { + resolve.sync('./null_main', { basedir: resolverDir }); + t.fail('require.resolve did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + } + + t.end(); +}); + +test('main: false', function (t) { + var basedir = path.join(__dirname, 'resolver'); + var dir = path.join(basedir, 'false_main'); + t.equal( + resolve.sync('./false_main', { basedir: basedir }), + path.join(dir, 'index.js'), + '`"main": false`: resolves to `index.js`' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./false_main', { basedir: basedir }), + require.resolve('./false_main', { paths: [basedir] }), + '`"main": false`: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +var stubStatSync = function stubStatSync(fn) { + var statSync = fs.statSync; + try { + fs.statSync = function () { + throw new EvalError('Unknown Error'); + }; + return fn(); + } finally { + fs.statSync = statSync; + } +}; + +test('#79 - re-throw non ENOENT errors from stat', function (t) { + var dir = path.join(__dirname, 'resolver'); + + stubStatSync(function () { + t.throws(function () { + resolve.sync('foo', { basedir: dir }); + }, /Unknown Error/); + }); + + t.end(); +}); + +test('#52 - incorrectly resolves module-paths like "./someFolder/" when there is a file of the same name', function (t) { + var dir = path.join(__dirname, 'resolver'); + var basedir = path.join(dir, 'same_names'); + + t.equal( + resolve.sync('./foo', { basedir: basedir }), + path.join(dir, 'same_names/foo.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo', { basedir: basedir }), + require.resolve('./foo', { paths: [basedir] }), + './foo: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./foo/', { basedir: basedir }), + path.join(dir, 'same_names/foo/index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo/', { basedir: basedir }), + require.resolve('./foo/', { paths: [basedir] }), + './foo/: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('#211 - incorrectly resolves module-paths like "." when from inside a folder with a sibling file of the same name', function (t) { + var dir = path.join(__dirname, 'resolver'); + var basedir = path.join(dir, 'same_names/foo'); + + t.equal( + resolve.sync('./', { basedir: basedir }), + path.join(dir, 'same_names/foo/index.js'), + './' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./', { basedir: basedir }), + require.resolve('./', { paths: [basedir] }), + './: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('.', { basedir: basedir }), + path.join(dir, 'same_names/foo/index.js'), + '.' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('.', { basedir: basedir }), + require.resolve('.', { paths: [basedir] }), + '.: resolve.sync === require.resolve', + { todo: true } + ); + } + + t.end(); +}); + +test('sync: #121 - treating an existing file as a dir when no basedir', function (t) { + var testFile = path.basename(__filename); + + t.test('sanity check', function (st) { + st.equal( + resolve.sync('./' + testFile), + __filename, + 'sanity check' + ); + st.equal( + resolve.sync('./' + testFile), + require.resolve('./' + testFile), + 'sanity check: resolve.sync === require.resolve' + ); + + st.end(); + }); + + t.test('with a fake directory', function (st) { + function run() { return resolve.sync('./' + testFile + '/blah'); } + + st.throws(run, 'throws an error'); + + try { + run(); + } catch (e) { + st.equal(e.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); + st.equal( + e.message, + 'Cannot find module \'./' + testFile + '/blah\' from \'' + __dirname + '\'', + 'can not find nonexistent module' + ); + } + + st.end(); + }); + + t.end(); +}); + +test('sync dot main', function (t) { + var start = new Date(); + + t.equal( + resolve.sync('./resolver/dot_main'), + path.join(__dirname, 'resolver/dot_main/index.js'), + './resolver/dot_main' + ); + t.equal( + resolve.sync('./resolver/dot_main'), + require.resolve('./resolver/dot_main'), + './resolver/dot_main: resolve.sync === require.resolve' + ); + + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + + t.end(); +}); + +test('sync dot slash main', function (t) { + var start = new Date(); + + t.equal( + resolve.sync('./resolver/dot_slash_main'), + path.join(__dirname, 'resolver/dot_slash_main/index.js') + ); + t.equal( + resolve.sync('./resolver/dot_slash_main'), + require.resolve('./resolver/dot_slash_main'), + './resolver/dot_slash_main: resolve.sync === require.resolve' + ); + + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + + t.end(); +}); + +test('not a directory', function (t) { + var path = './foo'; + try { + resolve.sync(path, { basedir: __filename }); + t.fail(); + } catch (err) { + t.ok(err, 'a non-directory errors'); + t.equal(err && err.message, 'Cannot find module \'' + path + "' from '" + __filename + "'"); + t.equal(err && err.code, 'MODULE_NOT_FOUND'); + } + t.end(); +}); + +test('non-string "main" field in package.json', function (t) { + var dir = path.join(__dirname, 'resolver'); + try { + var result = resolve.sync('./invalid_main', { basedir: dir }); + t.equal(result, undefined, 'result should not exist'); + t.fail('should not get here'); + } catch (err) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + } + t.end(); +}); + +test('non-string "main" field in package.json', function (t) { + var dir = path.join(__dirname, 'resolver'); + try { + var result = resolve.sync('./invalid_main', { basedir: dir }); + t.equal(result, undefined, 'result should not exist'); + t.fail('should not get here'); + } catch (err) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + } + t.end(); +}); + +test('browser field in package.json', function (t) { + var dir = path.join(__dirname, 'resolver'); + var res = resolve.sync('./browser_field', { + basedir: dir, + packageFilter: function packageFilter(pkg) { + if (pkg.browser) { + pkg.main = pkg.browser; // eslint-disable-line no-param-reassign + delete pkg.browser; // eslint-disable-line no-param-reassign + } + return pkg; + } + }); + t.equal(res, path.join(dir, 'browser_field', 'b.js')); + t.end(); +}); + +test('absolute paths', function (t) { + var extensionless = __filename.slice(0, -path.extname(__filename).length); + + t.equal( + resolve.sync(__filename), + __filename, + 'absolute path to this file resolves' + ); + t.equal( + resolve.sync(__filename), + require.resolve(__filename), + 'absolute path to this file: resolve.sync === require.resolve' + ); + + t.equal( + resolve.sync(extensionless), + __filename, + 'extensionless absolute path to this file resolves' + ); + t.equal( + resolve.sync(__filename), + require.resolve(__filename), + 'absolute path to this file: resolve.sync === require.resolve' + ); + + t.equal( + resolve.sync(__filename, { basedir: process.cwd() }), + __filename, + 'absolute path to this file with a basedir resolves' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync(__filename, { basedir: process.cwd() }), + require.resolve(__filename, { paths: [process.cwd()] }), + 'absolute path to this file + basedir: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync(extensionless, { basedir: process.cwd() }), + __filename, + 'extensionless absolute path to this file with a basedir resolves' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync(extensionless, { basedir: process.cwd() }), + require.resolve(extensionless, { paths: [process.cwd()] }), + 'extensionless absolute path to this file + basedir: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +var malformedDir = path.join(__dirname, 'resolver/malformed_package_json'); +test('malformed package.json', { skip: !fs.existsSync(malformedDir) }, function (t) { + t.plan(5 + (requireResolveSupportsPaths ? 1 : 0)); + + var basedir = malformedDir; + var expected = path.join(basedir, 'index.js'); + + t.equal( + resolve.sync('./index.js', { basedir: basedir }), + expected, + 'malformed package.json is silently ignored' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./index.js', { basedir: basedir }), + require.resolve('./index.js', { paths: [basedir] }), + 'malformed package.json: resolve.sync === require.resolve' + ); + } + + var res1 = resolve.sync( + './index.js', + { + basedir: basedir, + packageFilter: function (pkg, pkgfile, dir) { + t.fail('should not reach here'); + } + } + ); + + t.equal( + res1, + expected, + 'with packageFilter: malformed package.json is silently ignored' + ); + + var res2 = resolve.sync( + './index.js', + { + basedir: basedir, + readPackageSync: function (readFileSync, pkgfile) { + t.equal(pkgfile, path.join(basedir, 'package.json'), 'readPackageSync: `pkgfile` is package.json path'); + var result = String(readFileSync(pkgfile)); + try { + return JSON.parse(result); + } catch (e) { + t.ok(e instanceof SyntaxError, 'readPackageSync: malformed package.json parses as a syntax error'); + } + } + } + ); + + t.equal( + res2, + expected, + 'with readPackageSync: malformed package.json is silently ignored' + ); +}); diff --git a/node_modules/resolve/test/shadowed_core.js b/node_modules/resolve/test/shadowed_core.js new file mode 100644 index 0000000..3a5f4fc --- /dev/null +++ b/node_modules/resolve/test/shadowed_core.js @@ -0,0 +1,54 @@ +var test = require('tape'); +var resolve = require('../'); +var path = require('path'); + +test('shadowed core modules still return core module', function (t) { + t.plan(2); + + resolve('util', { basedir: path.join(__dirname, 'shadowed_core') }, function (err, res) { + t.ifError(err); + t.equal(res, 'util'); + }); +}); + +test('shadowed core modules still return core module [sync]', function (t) { + t.plan(1); + + var res = resolve.sync('util', { basedir: path.join(__dirname, 'shadowed_core') }); + + t.equal(res, 'util'); +}); + +test('shadowed core modules return shadow when appending `/`', function (t) { + t.plan(2); + + resolve('util/', { basedir: path.join(__dirname, 'shadowed_core') }, function (err, res) { + t.ifError(err); + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); + }); +}); + +test('shadowed core modules return shadow when appending `/` [sync]', function (t) { + t.plan(1); + + var res = resolve.sync('util/', { basedir: path.join(__dirname, 'shadowed_core') }); + + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); +}); + +test('shadowed core modules return shadow with `includeCoreModules: false`', function (t) { + t.plan(2); + + resolve('util', { basedir: path.join(__dirname, 'shadowed_core'), includeCoreModules: false }, function (err, res) { + t.ifError(err); + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); + }); +}); + +test('shadowed core modules return shadow with `includeCoreModules: false` [sync]', function (t) { + t.plan(1); + + var res = resolve.sync('util', { basedir: path.join(__dirname, 'shadowed_core'), includeCoreModules: false }); + + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); +}); diff --git a/node_modules/resolve/test/shadowed_core/node_modules/util/index.js b/node_modules/resolve/test/shadowed_core/node_modules/util/index.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/resolve/test/subdirs.js b/node_modules/resolve/test/subdirs.js new file mode 100644 index 0000000..b7b8450 --- /dev/null +++ b/node_modules/resolve/test/subdirs.js @@ -0,0 +1,13 @@ +var test = require('tape'); +var resolve = require('../'); +var path = require('path'); + +test('subdirs', function (t) { + t.plan(2); + + var dir = path.join(__dirname, '/subdirs'); + resolve('a/b/c/x.json', { basedir: dir }, function (err, res) { + t.ifError(err); + t.equal(res, path.join(dir, 'node_modules/a/b/c/x.json')); + }); +}); diff --git a/node_modules/resolve/test/symlinks.js b/node_modules/resolve/test/symlinks.js new file mode 100644 index 0000000..35f881a --- /dev/null +++ b/node_modules/resolve/test/symlinks.js @@ -0,0 +1,176 @@ +var path = require('path'); +var fs = require('fs'); +var test = require('tape'); +var map = require('array.prototype.map'); +var resolve = require('../'); + +var symlinkDir = path.join(__dirname, 'resolver', 'symlinked', 'symlink'); +var packageDir = path.join(__dirname, 'resolver', 'symlinked', '_', 'node_modules', 'package'); +var modADir = path.join(__dirname, 'symlinks', 'source', 'node_modules', 'mod-a'); +var symlinkModADir = path.join(__dirname, 'symlinks', 'dest', 'node_modules', 'mod-a'); +try { + fs.unlinkSync(symlinkDir); +} catch (err) {} +try { + fs.unlinkSync(packageDir); +} catch (err) {} +try { + fs.unlinkSync(modADir); +} catch (err) {} +try { + fs.unlinkSync(symlinkModADir); +} catch (err) {} + +try { + fs.symlinkSync('./_/symlink_target', symlinkDir, 'dir'); +} catch (err) { + // if fails then it is probably on Windows and lets try to create a junction + fs.symlinkSync(path.join(__dirname, 'resolver', 'symlinked', '_', 'symlink_target') + '\\', symlinkDir, 'junction'); +} +try { + fs.symlinkSync('../../package', packageDir, 'dir'); +} catch (err) { + // if fails then it is probably on Windows and lets try to create a junction + fs.symlinkSync(path.join(__dirname, '..', '..', 'package') + '\\', packageDir, 'junction'); +} +try { + fs.symlinkSync('../../source/node_modules/mod-a', symlinkModADir, 'dir'); +} catch (err) { + // if fails then it is probably on Windows and lets try to create a junction + fs.symlinkSync(path.join(__dirname, '..', '..', 'source', 'node_modules', 'mod-a') + '\\', symlinkModADir, 'junction'); +} + +test('symlink', function (t) { + t.plan(2); + + resolve('foo', { basedir: symlinkDir, preserveSymlinks: false }, function (err, res, pkg) { + t.error(err); + t.equal(res, path.join(__dirname, 'resolver', 'symlinked', '_', 'node_modules', 'foo.js')); + }); +}); + +test('sync symlink when preserveSymlinks = true', function (t) { + t.plan(4); + + resolve('foo', { basedir: symlinkDir }, function (err, res, pkg) { + t.ok(err, 'there is an error'); + t.notOk(res, 'no result'); + + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); + t.equal( + err && err.message, + 'Cannot find module \'foo\' from \'' + symlinkDir + '\'', + 'can not find nonexistent module' + ); + }); +}); + +test('sync symlink', function (t) { + var start = new Date(); + t.doesNotThrow(function () { + t.equal( + resolve.sync('foo', { basedir: symlinkDir, preserveSymlinks: false }), + path.join(__dirname, 'resolver', 'symlinked', '_', 'node_modules', 'foo.js') + ); + }); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); +}); + +test('sync symlink when preserveSymlinks = true', function (t) { + t.throws(function () { + resolve.sync('foo', { basedir: symlinkDir }); + }, /Cannot find module 'foo'/); + t.end(); +}); + +test('sync symlink from node_modules to other dir when preserveSymlinks = false', function (t) { + var basedir = path.join(__dirname, 'resolver', 'symlinked', '_'); + var fn = resolve.sync('package', { basedir: basedir, preserveSymlinks: false }); + + t.equal(fn, path.resolve(__dirname, 'resolver/symlinked/package/bar.js')); + t.end(); +}); + +test('async symlink from node_modules to other dir when preserveSymlinks = false', function (t) { + t.plan(2); + var basedir = path.join(__dirname, 'resolver', 'symlinked', '_'); + resolve('package', { basedir: basedir, preserveSymlinks: false }, function (err, result) { + t.notOk(err, 'no error'); + t.equal(result, path.resolve(__dirname, 'resolver/symlinked/package/bar.js')); + }); +}); + +test('packageFilter', function (t) { + function relative(x) { + return path.relative(__dirname, x); + } + + function testPackageFilter(preserveSymlinks) { + return function (st) { + st.plan('is 1.x' ? 3 : 5); // eslint-disable-line no-constant-condition + + var destMain = 'symlinks/dest/node_modules/mod-a/index.js'; + var destPkg = 'symlinks/dest/node_modules/mod-a/package.json'; + var sourceMain = 'symlinks/source/node_modules/mod-a/index.js'; + var sourcePkg = 'symlinks/source/node_modules/mod-a/package.json'; + var destDir = path.join(__dirname, 'symlinks', 'dest'); + + /* eslint multiline-comment-style: 0 */ + /* v2.x will restore these tests + var packageFilterPath = []; + var actualPath = resolve.sync('mod-a', { + basedir: destDir, + preserveSymlinks: preserveSymlinks, + packageFilter: function (pkg, pkgfile, dir) { + packageFilterPath.push(pkgfile); + } + }); + st.equal( + relative(actualPath), + path.normalize(preserveSymlinks ? destMain : sourceMain), + 'sync: actual path is correct' + ); + st.deepEqual( + map(packageFilterPath, relative), + map(preserveSymlinks ? [destPkg, destPkg] : [sourcePkg, sourcePkg], path.normalize), + 'sync: packageFilter pkgfile arg is correct' + ); + */ + + var asyncPackageFilterPath = []; + resolve( + 'mod-a', + { + basedir: destDir, + preserveSymlinks: preserveSymlinks, + packageFilter: function (pkg, pkgfile) { + asyncPackageFilterPath.push(pkgfile); + } + }, + function (err, actualPath) { + st.error(err, 'no error'); + st.equal( + relative(actualPath), + path.normalize(preserveSymlinks ? destMain : sourceMain), + 'async: actual path is correct' + ); + st.deepEqual( + map(asyncPackageFilterPath, relative), + map( + preserveSymlinks ? [destPkg, destPkg, destPkg] : [sourcePkg, sourcePkg, sourcePkg], + path.normalize + ), + 'async: packageFilter pkgfile arg is correct' + ); + } + ); + }; + } + + t.test('preserveSymlinks: false', testPackageFilter(false)); + + t.test('preserveSymlinks: true', testPackageFilter(true)); + + t.end(); +}); diff --git a/node_modules/reusify/.coveralls.yml b/node_modules/reusify/.coveralls.yml new file mode 100644 index 0000000..359f683 --- /dev/null +++ b/node_modules/reusify/.coveralls.yml @@ -0,0 +1 @@ +repo_token: yIxhFqtaaz5iGVYfie9mODehFYogm8S8L diff --git a/node_modules/reusify/.travis.yml b/node_modules/reusify/.travis.yml new file mode 100644 index 0000000..1970476 --- /dev/null +++ b/node_modules/reusify/.travis.yml @@ -0,0 +1,28 @@ +language: node_js +sudo: false + +node_js: + - 9 + - 8 + - 7 + - 6 + - 5 + - 4 + - 4.0 + - iojs-v3 + - iojs-v2 + - iojs-v1 + - 0.12 + - 0.10 + +cache: + directories: + - node_modules + +after_script: +- npm run coverage + +notifications: + email: + on_success: never + on_failure: always diff --git a/node_modules/reusify/LICENSE b/node_modules/reusify/LICENSE new file mode 100644 index 0000000..fbf3a01 --- /dev/null +++ b/node_modules/reusify/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Matteo Collina + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/reusify/README.md b/node_modules/reusify/README.md new file mode 100644 index 0000000..badcb7c --- /dev/null +++ b/node_modules/reusify/README.md @@ -0,0 +1,145 @@ +# reusify + +[![npm version][npm-badge]][npm-url] +[![Build Status][travis-badge]][travis-url] +[![Coverage Status][coveralls-badge]][coveralls-url] + +Reuse your objects and functions for maximum speed. This technique will +make any function run ~10% faster. You call your functions a +lot, and it adds up quickly in hot code paths. + +``` +$ node benchmarks/createNoCodeFunction.js +Total time 53133 +Total iterations 100000000 +Iteration/s 1882069.5236482036 + +$ node benchmarks/reuseNoCodeFunction.js +Total time 50617 +Total iterations 100000000 +Iteration/s 1975620.838848608 +``` + +The above benchmark uses fibonacci to simulate a real high-cpu load. +The actual numbers might differ for your use case, but the difference +should not. + +The benchmark was taken using Node v6.10.0. + +This library was extracted from +[fastparallel](http://npm.im/fastparallel). + +## Example + +```js +var reusify = require('reusify') +var fib = require('reusify/benchmarks/fib') +var instance = reusify(MyObject) + +// get an object from the cache, +// or creates a new one when cache is empty +var obj = instance.get() + +// set the state +obj.num = 100 +obj.func() + +// reset the state. +// if the state contains any external object +// do not use delete operator (it is slow) +// prefer set them to null +obj.num = 0 + +// store an object in the cache +instance.release(obj) + +function MyObject () { + // you need to define this property + // so V8 can compile MyObject into an + // hidden class + this.next = null + this.num = 0 + + var that = this + + // this function is never reallocated, + // so it can be optimized by V8 + this.func = function () { + if (null) { + // do nothing + } else { + // calculates fibonacci + fib(that.num) + } + } +} +``` + +The above example was intended for synchronous code, let's see async: +```js +var reusify = require('reusify') +var instance = reusify(MyObject) + +for (var i = 0; i < 100; i++) { + getData(i, console.log) +} + +function getData (value, cb) { + var obj = instance.get() + + obj.value = value + obj.cb = cb + obj.run() +} + +function MyObject () { + this.next = null + this.value = null + + var that = this + + this.run = function () { + asyncOperation(that.value, that.handle) + } + + this.handle = function (err, result) { + that.cb(err, result) + that.value = null + that.cb = null + instance.release(that) + } +} +``` + +Also note how in the above examples, the code, that consumes an istance of `MyObject`, +reset the state to initial condition, just before storing it in the cache. +That's needed so that every subsequent request for an instance from the cache, +could get a clean instance. + +## Why + +It is faster because V8 doesn't have to collect all the functions you +create. On a short-lived benchmark, it is as fast as creating the +nested function, but on a longer time frame it creates less +pressure on the garbage collector. + +## Other examples +If you want to see some complex example, checkout [middie](https://github.com/fastify/middie) and [steed](https://github.com/mcollina/steed). + +## Acknowledgements + +Thanks to [Trevor Norris](https://github.com/trevnorris) for +getting me down the rabbit hole of performance, and thanks to [Mathias +Buss](http://github.com/mafintosh) for suggesting me to share this +trick. + +## License + +MIT + +[npm-badge]: https://badge.fury.io/js/reusify.svg +[npm-url]: https://badge.fury.io/js/reusify +[travis-badge]: https://api.travis-ci.org/mcollina/reusify.svg +[travis-url]: https://travis-ci.org/mcollina/reusify +[coveralls-badge]: https://coveralls.io/repos/mcollina/reusify/badge.svg?branch=master&service=github +[coveralls-url]: https://coveralls.io/github/mcollina/reusify?branch=master diff --git a/node_modules/reusify/benchmarks/createNoCodeFunction.js b/node_modules/reusify/benchmarks/createNoCodeFunction.js new file mode 100644 index 0000000..ce1aac7 --- /dev/null +++ b/node_modules/reusify/benchmarks/createNoCodeFunction.js @@ -0,0 +1,30 @@ +'use strict' + +var fib = require('./fib') +var max = 100000000 +var start = Date.now() + +// create a funcion with the typical error +// pattern, that delegates the heavy load +// to something else +function createNoCodeFunction () { + /* eslint no-constant-condition: "off" */ + var num = 100 + + ;(function () { + if (null) { + // do nothing + } else { + fib(num) + } + })() +} + +for (var i = 0; i < max; i++) { + createNoCodeFunction() +} + +var time = Date.now() - start +console.log('Total time', time) +console.log('Total iterations', max) +console.log('Iteration/s', max / time * 1000) diff --git a/node_modules/reusify/benchmarks/fib.js b/node_modules/reusify/benchmarks/fib.js new file mode 100644 index 0000000..e22cc48 --- /dev/null +++ b/node_modules/reusify/benchmarks/fib.js @@ -0,0 +1,13 @@ +'use strict' + +function fib (num) { + var fib = [] + + fib[0] = 0 + fib[1] = 1 + for (var i = 2; i <= num; i++) { + fib[i] = fib[i - 2] + fib[i - 1] + } +} + +module.exports = fib diff --git a/node_modules/reusify/benchmarks/reuseNoCodeFunction.js b/node_modules/reusify/benchmarks/reuseNoCodeFunction.js new file mode 100644 index 0000000..3358d6e --- /dev/null +++ b/node_modules/reusify/benchmarks/reuseNoCodeFunction.js @@ -0,0 +1,38 @@ +'use strict' + +var reusify = require('../') +var fib = require('./fib') +var instance = reusify(MyObject) +var max = 100000000 +var start = Date.now() + +function reuseNoCodeFunction () { + var obj = instance.get() + obj.num = 100 + obj.func() + obj.num = 0 + instance.release(obj) +} + +function MyObject () { + this.next = null + var that = this + this.num = 0 + this.func = function () { + /* eslint no-constant-condition: "off" */ + if (null) { + // do nothing + } else { + fib(that.num) + } + } +} + +for (var i = 0; i < max; i++) { + reuseNoCodeFunction() +} + +var time = Date.now() - start +console.log('Total time', time) +console.log('Total iterations', max) +console.log('Iteration/s', max / time * 1000) diff --git a/node_modules/reusify/package.json b/node_modules/reusify/package.json new file mode 100644 index 0000000..ee66aee --- /dev/null +++ b/node_modules/reusify/package.json @@ -0,0 +1,45 @@ +{ + "name": "reusify", + "version": "1.0.4", + "description": "Reuse objects and functions with style", + "main": "reusify.js", + "scripts": { + "lint": "standard", + "test": "tape test.js | faucet", + "istanbul": "istanbul cover tape test.js", + "coverage": "npm run istanbul; cat coverage/lcov.info | coveralls" + }, + "pre-commit": [ + "lint", + "test" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/mcollina/reusify.git" + }, + "keywords": [ + "reuse", + "object", + "performance", + "function", + "fast" + ], + "author": "Matteo Collina ", + "license": "MIT", + "bugs": { + "url": "https://github.com/mcollina/reusify/issues" + }, + "homepage": "https://github.com/mcollina/reusify#readme", + "engines": { + "node": ">=0.10.0", + "iojs": ">=1.0.0" + }, + "devDependencies": { + "coveralls": "^2.13.3", + "faucet": "0.0.1", + "istanbul": "^0.4.5", + "pre-commit": "^1.2.2", + "standard": "^10.0.3", + "tape": "^4.8.0" + } +} diff --git a/node_modules/reusify/reusify.js b/node_modules/reusify/reusify.js new file mode 100644 index 0000000..e6f36f3 --- /dev/null +++ b/node_modules/reusify/reusify.js @@ -0,0 +1,33 @@ +'use strict' + +function reusify (Constructor) { + var head = new Constructor() + var tail = head + + function get () { + var current = head + + if (current.next) { + head = current.next + } else { + head = new Constructor() + tail = head + } + + current.next = null + + return current + } + + function release (obj) { + tail.next = obj + tail = obj + } + + return { + get: get, + release: release + } +} + +module.exports = reusify diff --git a/node_modules/reusify/test.js b/node_modules/reusify/test.js new file mode 100644 index 0000000..929cfd7 --- /dev/null +++ b/node_modules/reusify/test.js @@ -0,0 +1,66 @@ +'use strict' + +var test = require('tape') +var reusify = require('./') + +test('reuse objects', function (t) { + t.plan(6) + + function MyObject () { + t.pass('constructor called') + this.next = null + } + + var instance = reusify(MyObject) + var obj = instance.get() + + t.notEqual(obj, instance.get(), 'two instance created') + t.notOk(obj.next, 'next must be null') + + instance.release(obj) + + // the internals keeps a hot copy ready for reuse + // putting this one back in the queue + instance.release(instance.get()) + + // comparing the old one with the one we got + // never do this in real code, after release you + // should never reuse that instance + t.equal(obj, instance.get(), 'instance must be reused') +}) + +test('reuse more than 2 objects', function (t) { + function MyObject () { + t.pass('constructor called') + this.next = null + } + + var instance = reusify(MyObject) + var obj = instance.get() + var obj2 = instance.get() + var obj3 = instance.get() + + t.notOk(obj.next, 'next must be null') + t.notOk(obj2.next, 'next must be null') + t.notOk(obj3.next, 'next must be null') + + t.notEqual(obj, obj2) + t.notEqual(obj, obj3) + t.notEqual(obj3, obj2) + + instance.release(obj) + instance.release(obj2) + instance.release(obj3) + + // skip one + instance.get() + + var obj4 = instance.get() + var obj5 = instance.get() + var obj6 = instance.get() + + t.equal(obj4, obj) + t.equal(obj5, obj2) + t.equal(obj6, obj3) + t.end() +}) diff --git a/node_modules/rimraf/LICENSE b/node_modules/rimraf/LICENSE new file mode 100644 index 0000000..1493534 --- /dev/null +++ b/node_modules/rimraf/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2011-2023 Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/rimraf/README.md b/node_modules/rimraf/README.md new file mode 100644 index 0000000..7ab1a5d --- /dev/null +++ b/node_modules/rimraf/README.md @@ -0,0 +1,220 @@ +The [UNIX command]() `rm -rf` for node +in a cross-platform implementation. + +Install with `npm install rimraf`. + +## Major Changes + +### v4 to v5 + +- There is no default export anymore. Import the functions directly + using, e.g., `import { rimrafSync } from 'rimraf'`. + +### v3 to v4 + +- The function returns a `Promise` instead of taking a callback. +- Globbing requires the `--glob` CLI option or `glob` option property + to be set. (Removed in 4.0 and 4.1, opt-in support added in 4.2.) +- Functions take arrays of paths, as well as a single path. +- Native implementation used by default when available, except on + Windows, where this implementation is faster and more reliable. +- New implementation on Windows, falling back to "move then + remove" strategy when exponential backoff for `EBUSY` fails to + resolve the situation. +- Simplified implementation on POSIX, since the Windows + affordances are not necessary there. +- As of 4.3, return/resolve value is boolean instead of undefined. + +## API + +Hybrid module, load either with `import` or `require()`. + +```js +// 'rimraf' export is the one you probably want, but other +// strategies exported as well. +import { rimraf, rimrafSync, native, nativeSync } from 'rimraf' +// or +const { rimraf, rimrafSync, native, nativeSync } = require('rimraf') +``` + +All removal functions return a boolean indicating that all +entries were successfully removed. + +The only case in which this will not return `true` is if +something was omitted from the removal via a `filter` option. + +### `rimraf(f, [opts]) -> Promise` + +This first parameter is a path or array of paths. The second +argument is an options object. + +Options: + +- `preserveRoot`: If set to boolean `false`, then allow the + recursive removal of the root directory. Otherwise, this is + not allowed. +- `tmp`: Windows only. Temp folder to place files and + folders for the "move then remove" fallback. Must be on the + same physical device as the path being deleted. Defaults to + `os.tmpdir()` when that is on the same drive letter as the path + being deleted, or `${drive}:\temp` if present, or `${drive}:\` + if not. +- `maxRetries`: Windows and Native only. Maximum number of + retry attempts in case of `EBUSY`, `EMFILE`, and `ENFILE` + errors. Default `10` for Windows implementation, `0` for Native + implementation. +- `backoff`: Windows only. Rate of exponential backoff for async + removal in case of `EBUSY`, `EMFILE`, and `ENFILE` errors. + Should be a number greater than 1. Default `1.2` +- `maxBackoff`: Windows only. Maximum total backoff time in ms to + attempt asynchronous retries in case of `EBUSY`, `EMFILE`, and + `ENFILE` errors. Default `200`. With the default `1.2` backoff + rate, this results in 14 retries, with the final retry being + delayed 33ms. +- `retryDelay`: Native only. Time to wait between retries, using + linear backoff. Default `100`. +- `signal` Pass in an AbortSignal to cancel the directory + removal. This is useful when removing large folder structures, + if you'd like to limit the time spent. + + Using a `signal` option prevents the use of Node's built-in + `fs.rm` because that implementation does not support abort + signals. + +- `glob` Boolean flag to treat path as glob pattern, or an object + specifying [`glob` options](https://github.com/isaacs/node-glob). +- `filter` Method that returns a boolean indicating whether that + path should be deleted. With async `rimraf` methods, this may + return a Promise that resolves to a boolean. (Since Promises + are truthy, returning a Promise from a sync filter is the same + as just not filtering anything.) + + The first argument to the filter is the path string. The + second argument is either a `Dirent` or `Stats` object for that + path. (The first path explored will be a `Stats`, the rest + will be `Dirent`.) + + If a filter method is provided, it will _only_ remove entries + if the filter returns (or resolves to) a truthy value. Omitting + a directory will still allow its children to be removed, unless + they are also filtered out, but any parents of a filtered entry + will not be removed, since the directory will not be empty in + that case. + + Using a filter method prevents the use of Node's built-in + `fs.rm` because that implementation does not support filtering. + +Any other options are provided to the native Node.js `fs.rm` implementation +when that is used. + +This will attempt to choose the best implementation, based on the Node.js +version and `process.platform`. To force a specific implementation, use +one of the other functions provided. + +### `rimraf.sync(f, [opts])`
`rimraf.rimrafSync(f, [opts])` + +Synchronous form of `rimraf()` + +Note that, unlike many file system operations, the synchronous form will +typically be significantly _slower_ than the async form, because recursive +deletion is extremely parallelizable. + +### `rimraf.native(f, [opts])` + +Uses the built-in `fs.rm` implementation that Node.js provides. This is +used by default on Node.js versions greater than or equal to `14.14.0`. + +### `rimraf.native.sync(f, [opts])`
`rimraf.nativeSync(f, [opts])` + +Synchronous form of `rimraf.native` + +### `rimraf.manual(f, [opts])` + +Use the JavaScript implementation appropriate for your operating system. + +### `rimraf.manual.sync(f, [opts])`
`rimraf.manualSync(f, opts)` + +Synchronous form of `rimraf.manual()` + +### `rimraf.windows(f, [opts])` + +JavaScript implementation of file removal appropriate for Windows +platforms. Works around `unlink` and `rmdir` not being atomic +operations, and `EPERM` when deleting files with certain +permission modes. + +First deletes all non-directory files within the tree, and then +removes all directories, which should ideally be empty by that +time. When an `ENOTEMPTY` is raised in the second pass, falls +back to the `rimraf.moveRemove` strategy as needed. + +### `rimraf.windows.sync(path, [opts])`
`rimraf.windowsSync(path, [opts])` + +Synchronous form of `rimraf.windows()` + +### `rimraf.moveRemove(path, [opts])` + +Moves all files and folders to the parent directory of `path` +with a temporary filename prior to attempting to remove them. + +Note that, in cases where the operation fails, this _may_ leave +files lying around in the parent directory with names like +`.file-basename.txt.0.123412341`. Until the Windows kernel +provides a way to perform atomic `unlink` and `rmdir` operations, +this is, unfortunately, unavoidable. + +To move files to a different temporary directory other than the +parent, provide `opts.tmp`. Note that this _must_ be on the same +physical device as the folder being deleted, or else the +operation will fail. + +This is the slowest strategy, but most reliable on Windows +platforms. Used as a last-ditch fallback by `rimraf.windows()`. + +### `rimraf.moveRemove.sync(path, [opts])`
`rimraf.moveRemoveSync(path, [opts])` + +Synchronous form of `rimraf.moveRemove()` + +### Command Line Interface + +``` +rimraf version 4.3.0 + +Usage: rimraf [ ...] +Deletes all files and folders at "path", recursively. + +Options: + -- Treat all subsequent arguments as paths + -h --help Display this usage info + --preserve-root Do not remove '/' recursively (default) + --no-preserve-root Do not treat '/' specially + -G --no-glob Treat arguments as literal paths, not globs (default) + -g --glob Treat arguments as glob patterns + -v --verbose Be verbose when deleting files, showing them as + they are removed. Not compatible with --impl=native + -V --no-verbose Be silent when deleting files, showing nothing as + they are removed (default) + -i --interactive Ask for confirmation before deleting anything + Not compatible with --impl=native + -I --no-interactive Do not ask for confirmation before deleting + + --impl= Specify the implementation to use: + rimraf: choose the best option (default) + native: the built-in implementation in Node.js + manual: the platform-specific JS implementation + posix: the Posix JS implementation + windows: the Windows JS implementation (falls back to + move-remove on ENOTEMPTY) + move-remove: a slow reliable Windows fallback + +Implementation-specific options: + --tmp= Temp file folder for 'move-remove' implementation + --max-retries= maxRetries for 'native' and 'windows' implementations + --retry-delay= retryDelay for 'native' implementation, default 100 + --backoff= Exponential backoff factor for retries (default: 1.2) +``` + +## mkdirp + +If you need to _create_ a directory recursively, check out +[mkdirp](https://github.com/isaacs/node-mkdirp). diff --git a/node_modules/rimraf/dist/commonjs/default-tmp.d.ts b/node_modules/rimraf/dist/commonjs/default-tmp.d.ts new file mode 100644 index 0000000..a68e925 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/default-tmp.d.ts @@ -0,0 +1,3 @@ +export declare const defaultTmp: (path: string) => Promise; +export declare const defaultTmpSync: (path: string) => string; +//# sourceMappingURL=default-tmp.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/default-tmp.d.ts.map b/node_modules/rimraf/dist/commonjs/default-tmp.d.ts.map new file mode 100644 index 0000000..d0b35f2 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/default-tmp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"default-tmp.d.ts","sourceRoot":"","sources":["../../src/default-tmp.ts"],"names":[],"mappings":"AAiEA,eAAO,MAAM,UAAU,SAnCc,MAAM,oBAoCe,CAAA;AAC1D,eAAO,MAAM,cAAc,SArBQ,MAAM,WAsByB,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/default-tmp.js b/node_modules/rimraf/dist/commonjs/default-tmp.js new file mode 100644 index 0000000..ae90878 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/default-tmp.js @@ -0,0 +1,61 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultTmpSync = exports.defaultTmp = void 0; +// The default temporary folder location for use in the windows algorithm. +// It's TEMPting to use dirname(path), since that's guaranteed to be on the +// same device. However, this means that: +// rimraf(path).then(() => rimraf(dirname(path))) +// will often fail with EBUSY, because the parent dir contains +// marked-for-deletion directory entries (which do not show up in readdir). +// The approach here is to use os.tmpdir() if it's on the same drive letter, +// or resolve(path, '\\temp') if it exists, or the root of the drive if not. +// On Posix (not that you'd be likely to use the windows algorithm there), +// it uses os.tmpdir() always. +const os_1 = require("os"); +const path_1 = require("path"); +const fs_js_1 = require("./fs.js"); +const platform_js_1 = __importDefault(require("./platform.js")); +const { stat } = fs_js_1.promises; +const isDirSync = (path) => { + try { + return (0, fs_js_1.statSync)(path).isDirectory(); + } + catch (er) { + return false; + } +}; +const isDir = (path) => stat(path).then(st => st.isDirectory(), () => false); +const win32DefaultTmp = async (path) => { + const { root } = (0, path_1.parse)(path); + const tmp = (0, os_1.tmpdir)(); + const { root: tmpRoot } = (0, path_1.parse)(tmp); + if (root.toLowerCase() === tmpRoot.toLowerCase()) { + return tmp; + } + const driveTmp = (0, path_1.resolve)(root, '/temp'); + if (await isDir(driveTmp)) { + return driveTmp; + } + return root; +}; +const win32DefaultTmpSync = (path) => { + const { root } = (0, path_1.parse)(path); + const tmp = (0, os_1.tmpdir)(); + const { root: tmpRoot } = (0, path_1.parse)(tmp); + if (root.toLowerCase() === tmpRoot.toLowerCase()) { + return tmp; + } + const driveTmp = (0, path_1.resolve)(root, '/temp'); + if (isDirSync(driveTmp)) { + return driveTmp; + } + return root; +}; +const posixDefaultTmp = async () => (0, os_1.tmpdir)(); +const posixDefaultTmpSync = () => (0, os_1.tmpdir)(); +exports.defaultTmp = platform_js_1.default === 'win32' ? win32DefaultTmp : posixDefaultTmp; +exports.defaultTmpSync = platform_js_1.default === 'win32' ? win32DefaultTmpSync : posixDefaultTmpSync; +//# sourceMappingURL=default-tmp.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/default-tmp.js.map b/node_modules/rimraf/dist/commonjs/default-tmp.js.map new file mode 100644 index 0000000..4984afb --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/default-tmp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"default-tmp.js","sourceRoot":"","sources":["../../src/default-tmp.ts"],"names":[],"mappings":";;;;;;AAAA,0EAA0E;AAC1E,2EAA2E;AAC3E,0CAA0C;AAC1C,iDAAiD;AACjD,8DAA8D;AAC9D,2EAA2E;AAC3E,4EAA4E;AAC5E,4EAA4E;AAC5E,0EAA0E;AAC1E,8BAA8B;AAC9B,2BAA2B;AAC3B,+BAAqC;AACrC,mCAA4C;AAC5C,gEAAoC;AACpC,MAAM,EAAE,IAAI,EAAE,GAAG,gBAAQ,CAAA;AAEzB,MAAM,SAAS,GAAG,CAAC,IAAY,EAAE,EAAE;IACjC,IAAI,CAAC;QACH,OAAO,IAAA,gBAAQ,EAAC,IAAI,CAAC,CAAC,WAAW,EAAE,CAAA;IACrC,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,OAAO,KAAK,CAAA;IACd,CAAC;AACH,CAAC,CAAA;AAED,MAAM,KAAK,GAAG,CAAC,IAAY,EAAE,EAAE,CAC7B,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CACb,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,WAAW,EAAE,EACtB,GAAG,EAAE,CAAC,KAAK,CACZ,CAAA;AAEH,MAAM,eAAe,GAAG,KAAK,EAAE,IAAY,EAAE,EAAE;IAC7C,MAAM,EAAE,IAAI,EAAE,GAAG,IAAA,YAAK,EAAC,IAAI,CAAC,CAAA;IAC5B,MAAM,GAAG,GAAG,IAAA,WAAM,GAAE,CAAA;IACpB,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,IAAA,YAAK,EAAC,GAAG,CAAC,CAAA;IACpC,IAAI,IAAI,CAAC,WAAW,EAAE,KAAK,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC;QACjD,OAAO,GAAG,CAAA;IACZ,CAAC;IAED,MAAM,QAAQ,GAAG,IAAA,cAAO,EAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IACvC,IAAI,MAAM,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC1B,OAAO,QAAQ,CAAA;IACjB,CAAC;IAED,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,MAAM,mBAAmB,GAAG,CAAC,IAAY,EAAE,EAAE;IAC3C,MAAM,EAAE,IAAI,EAAE,GAAG,IAAA,YAAK,EAAC,IAAI,CAAC,CAAA;IAC5B,MAAM,GAAG,GAAG,IAAA,WAAM,GAAE,CAAA;IACpB,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,IAAA,YAAK,EAAC,GAAG,CAAC,CAAA;IACpC,IAAI,IAAI,CAAC,WAAW,EAAE,KAAK,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC;QACjD,OAAO,GAAG,CAAA;IACZ,CAAC;IAED,MAAM,QAAQ,GAAG,IAAA,cAAO,EAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IACvC,IAAI,SAAS,CAAC,QAAQ,CAAC,EAAE,CAAC;QACxB,OAAO,QAAQ,CAAA;IACjB,CAAC;IAED,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,MAAM,eAAe,GAAG,KAAK,IAAI,EAAE,CAAC,IAAA,WAAM,GAAE,CAAA;AAC5C,MAAM,mBAAmB,GAAG,GAAG,EAAE,CAAC,IAAA,WAAM,GAAE,CAAA;AAE7B,QAAA,UAAU,GACrB,qBAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,eAAe,CAAA;AAC7C,QAAA,cAAc,GACzB,qBAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,mBAAmB,CAAA","sourcesContent":["// The default temporary folder location for use in the windows algorithm.\n// It's TEMPting to use dirname(path), since that's guaranteed to be on the\n// same device. However, this means that:\n// rimraf(path).then(() => rimraf(dirname(path)))\n// will often fail with EBUSY, because the parent dir contains\n// marked-for-deletion directory entries (which do not show up in readdir).\n// The approach here is to use os.tmpdir() if it's on the same drive letter,\n// or resolve(path, '\\\\temp') if it exists, or the root of the drive if not.\n// On Posix (not that you'd be likely to use the windows algorithm there),\n// it uses os.tmpdir() always.\nimport { tmpdir } from 'os'\nimport { parse, resolve } from 'path'\nimport { promises, statSync } from './fs.js'\nimport platform from './platform.js'\nconst { stat } = promises\n\nconst isDirSync = (path: string) => {\n try {\n return statSync(path).isDirectory()\n } catch (er) {\n return false\n }\n}\n\nconst isDir = (path: string) =>\n stat(path).then(\n st => st.isDirectory(),\n () => false,\n )\n\nconst win32DefaultTmp = async (path: string) => {\n const { root } = parse(path)\n const tmp = tmpdir()\n const { root: tmpRoot } = parse(tmp)\n if (root.toLowerCase() === tmpRoot.toLowerCase()) {\n return tmp\n }\n\n const driveTmp = resolve(root, '/temp')\n if (await isDir(driveTmp)) {\n return driveTmp\n }\n\n return root\n}\n\nconst win32DefaultTmpSync = (path: string) => {\n const { root } = parse(path)\n const tmp = tmpdir()\n const { root: tmpRoot } = parse(tmp)\n if (root.toLowerCase() === tmpRoot.toLowerCase()) {\n return tmp\n }\n\n const driveTmp = resolve(root, '/temp')\n if (isDirSync(driveTmp)) {\n return driveTmp\n }\n\n return root\n}\n\nconst posixDefaultTmp = async () => tmpdir()\nconst posixDefaultTmpSync = () => tmpdir()\n\nexport const defaultTmp =\n platform === 'win32' ? win32DefaultTmp : posixDefaultTmp\nexport const defaultTmpSync =\n platform === 'win32' ? win32DefaultTmpSync : posixDefaultTmpSync\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/fix-eperm.d.ts b/node_modules/rimraf/dist/commonjs/fix-eperm.d.ts new file mode 100644 index 0000000..20e76a8 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/fix-eperm.d.ts @@ -0,0 +1,3 @@ +export declare const fixEPERM: (fn: (path: string) => Promise) => (path: string) => Promise; +export declare const fixEPERMSync: (fn: (path: string) => any) => (path: string) => any; +//# sourceMappingURL=fix-eperm.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/fix-eperm.d.ts.map b/node_modules/rimraf/dist/commonjs/fix-eperm.d.ts.map new file mode 100644 index 0000000..ac17d6f --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/fix-eperm.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fix-eperm.d.ts","sourceRoot":"","sources":["../../src/fix-eperm.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,QAAQ,OACd,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,GAAG,CAAC,YAAkB,MAAM,iBAsB1D,CAAA;AAEH,eAAO,MAAM,YAAY,OAAQ,CAAC,IAAI,EAAE,MAAM,KAAK,GAAG,YAAY,MAAM,QAsBvE,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/fix-eperm.js b/node_modules/rimraf/dist/commonjs/fix-eperm.js new file mode 100644 index 0000000..7baecb7 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/fix-eperm.js @@ -0,0 +1,58 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fixEPERMSync = exports.fixEPERM = void 0; +const fs_js_1 = require("./fs.js"); +const { chmod } = fs_js_1.promises; +const fixEPERM = (fn) => async (path) => { + try { + return await fn(path); + } + catch (er) { + const fer = er; + if (fer?.code === 'ENOENT') { + return; + } + if (fer?.code === 'EPERM') { + try { + await chmod(path, 0o666); + } + catch (er2) { + const fer2 = er2; + if (fer2?.code === 'ENOENT') { + return; + } + throw er; + } + return await fn(path); + } + throw er; + } +}; +exports.fixEPERM = fixEPERM; +const fixEPERMSync = (fn) => (path) => { + try { + return fn(path); + } + catch (er) { + const fer = er; + if (fer?.code === 'ENOENT') { + return; + } + if (fer?.code === 'EPERM') { + try { + (0, fs_js_1.chmodSync)(path, 0o666); + } + catch (er2) { + const fer2 = er2; + if (fer2?.code === 'ENOENT') { + return; + } + throw er; + } + return fn(path); + } + throw er; + } +}; +exports.fixEPERMSync = fixEPERMSync; +//# sourceMappingURL=fix-eperm.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/fix-eperm.js.map b/node_modules/rimraf/dist/commonjs/fix-eperm.js.map new file mode 100644 index 0000000..250ea5d --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/fix-eperm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fix-eperm.js","sourceRoot":"","sources":["../../src/fix-eperm.ts"],"names":[],"mappings":";;;AAAA,mCAA6C;AAC7C,MAAM,EAAE,KAAK,EAAE,GAAG,gBAAQ,CAAA;AAEnB,MAAM,QAAQ,GACnB,CAAC,EAAkC,EAAE,EAAE,CAAC,KAAK,EAAE,IAAY,EAAE,EAAE;IAC7D,IAAI,CAAC;QACH,OAAO,MAAM,EAAE,CAAC,IAAI,CAAC,CAAA;IACvB,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC3B,OAAM;QACR,CAAC;QACD,IAAI,GAAG,EAAE,IAAI,KAAK,OAAO,EAAE,CAAC;YAC1B,IAAI,CAAC;gBACH,MAAM,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;YAC1B,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,MAAM,IAAI,GAAG,GAA4B,CAAA;gBACzC,IAAI,IAAI,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;oBAC5B,OAAM;gBACR,CAAC;gBACD,MAAM,EAAE,CAAA;YACV,CAAC;YACD,OAAO,MAAM,EAAE,CAAC,IAAI,CAAC,CAAA;QACvB,CAAC;QACD,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAvBU,QAAA,QAAQ,YAuBlB;AAEI,MAAM,YAAY,GAAG,CAAC,EAAyB,EAAE,EAAE,CAAC,CAAC,IAAY,EAAE,EAAE;IAC1E,IAAI,CAAC;QACH,OAAO,EAAE,CAAC,IAAI,CAAC,CAAA;IACjB,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC3B,OAAM;QACR,CAAC;QACD,IAAI,GAAG,EAAE,IAAI,KAAK,OAAO,EAAE,CAAC;YAC1B,IAAI,CAAC;gBACH,IAAA,iBAAS,EAAC,IAAI,EAAE,KAAK,CAAC,CAAA;YACxB,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,MAAM,IAAI,GAAG,GAA4B,CAAA;gBACzC,IAAI,IAAI,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;oBAC5B,OAAM;gBACR,CAAC;gBACD,MAAM,EAAE,CAAA;YACV,CAAC;YACD,OAAO,EAAE,CAAC,IAAI,CAAC,CAAA;QACjB,CAAC;QACD,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAtBY,QAAA,YAAY,gBAsBxB","sourcesContent":["import { chmodSync, promises } from './fs.js'\nconst { chmod } = promises\n\nexport const fixEPERM =\n (fn: (path: string) => Promise) => async (path: string) => {\n try {\n return await fn(path)\n } catch (er) {\n const fer = er as NodeJS.ErrnoException\n if (fer?.code === 'ENOENT') {\n return\n }\n if (fer?.code === 'EPERM') {\n try {\n await chmod(path, 0o666)\n } catch (er2) {\n const fer2 = er2 as NodeJS.ErrnoException\n if (fer2?.code === 'ENOENT') {\n return\n }\n throw er\n }\n return await fn(path)\n }\n throw er\n }\n }\n\nexport const fixEPERMSync = (fn: (path: string) => any) => (path: string) => {\n try {\n return fn(path)\n } catch (er) {\n const fer = er as NodeJS.ErrnoException\n if (fer?.code === 'ENOENT') {\n return\n }\n if (fer?.code === 'EPERM') {\n try {\n chmodSync(path, 0o666)\n } catch (er2) {\n const fer2 = er2 as NodeJS.ErrnoException\n if (fer2?.code === 'ENOENT') {\n return\n }\n throw er\n }\n return fn(path)\n }\n throw er\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/fs.d.ts b/node_modules/rimraf/dist/commonjs/fs.d.ts new file mode 100644 index 0000000..9e4e95b --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/fs.d.ts @@ -0,0 +1,17 @@ +import fs, { Dirent } from 'fs'; +export { chmodSync, mkdirSync, renameSync, rmdirSync, rmSync, statSync, lstatSync, unlinkSync, } from 'fs'; +export declare const readdirSync: (path: fs.PathLike) => Dirent[]; +export declare const promises: { + chmod: (path: fs.PathLike, mode: fs.Mode) => Promise; + mkdir: (path: fs.PathLike, options?: fs.Mode | (fs.MakeDirectoryOptions & { + recursive?: boolean | null; + }) | undefined | null) => Promise; + readdir: (path: fs.PathLike) => Promise; + rename: (oldPath: fs.PathLike, newPath: fs.PathLike) => Promise; + rm: (path: fs.PathLike, options: fs.RmOptions) => Promise; + rmdir: (path: fs.PathLike) => Promise; + stat: (path: fs.PathLike) => Promise; + lstat: (path: fs.PathLike) => Promise; + unlink: (path: fs.PathLike) => Promise; +}; +//# sourceMappingURL=fs.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/fs.d.ts.map b/node_modules/rimraf/dist/commonjs/fs.d.ts.map new file mode 100644 index 0000000..8c8b103 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/fs.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fs.d.ts","sourceRoot":"","sources":["../../src/fs.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,IAAI,CAAA;AAG/B,OAAO,EACL,SAAS,EACT,SAAS,EACT,UAAU,EACV,SAAS,EACT,MAAM,EACN,QAAQ,EACR,SAAS,EACT,UAAU,GACX,MAAM,IAAI,CAAA;AAGX,eAAO,MAAM,WAAW,SAAU,EAAE,CAAC,QAAQ,KAAG,MAAM,EACf,CAAA;AA+DvC,eAAO,MAAM,QAAQ;kBAxDA,EAAE,CAAC,QAAQ,QAAQ,EAAE,CAAC,IAAI,KAAG,OAAO,CAAC,IAAI,CAAC;kBAMvD,EAAE,CAAC,QAAQ,YAEb,EAAE,CAAC,IAAI,GACP,CAAC,EAAE,CAAC,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,GAAG,IAAI,CAAA;KAAE,CAAC,GAC1D,SAAS,GACT,IAAI,KACP,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;oBAKP,EAAE,CAAC,QAAQ,KAAG,OAAO,CAAC,MAAM,EAAE,CAAC;sBAO7B,EAAE,CAAC,QAAQ,WAAW,EAAE,CAAC,QAAQ,KAAG,OAAO,CAAC,IAAI,CAAC;eAOxD,EAAE,CAAC,QAAQ,WAAW,EAAE,CAAC,SAAS,KAAG,OAAO,CAAC,IAAI,CAAC;kBAK/C,EAAE,CAAC,QAAQ,KAAG,OAAO,CAAC,IAAI,CAAC;iBAK5B,EAAE,CAAC,QAAQ,KAAG,OAAO,CAAC,EAAE,CAAC,KAAK,CAAC;kBAK9B,EAAE,CAAC,QAAQ,KAAG,OAAO,CAAC,EAAE,CAAC,KAAK,CAAC;mBAK9B,EAAE,CAAC,QAAQ,KAAG,OAAO,CAAC,IAAI,CAAC;CAehD,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/fs.js b/node_modules/rimraf/dist/commonjs/fs.js new file mode 100644 index 0000000..dba64c9 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/fs.js @@ -0,0 +1,46 @@ +"use strict"; +// promisify ourselves, because older nodes don't have fs.promises +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.promises = exports.readdirSync = exports.unlinkSync = exports.lstatSync = exports.statSync = exports.rmSync = exports.rmdirSync = exports.renameSync = exports.mkdirSync = exports.chmodSync = void 0; +const fs_1 = __importDefault(require("fs")); +// sync ones just take the sync version from node +var fs_2 = require("fs"); +Object.defineProperty(exports, "chmodSync", { enumerable: true, get: function () { return fs_2.chmodSync; } }); +Object.defineProperty(exports, "mkdirSync", { enumerable: true, get: function () { return fs_2.mkdirSync; } }); +Object.defineProperty(exports, "renameSync", { enumerable: true, get: function () { return fs_2.renameSync; } }); +Object.defineProperty(exports, "rmdirSync", { enumerable: true, get: function () { return fs_2.rmdirSync; } }); +Object.defineProperty(exports, "rmSync", { enumerable: true, get: function () { return fs_2.rmSync; } }); +Object.defineProperty(exports, "statSync", { enumerable: true, get: function () { return fs_2.statSync; } }); +Object.defineProperty(exports, "lstatSync", { enumerable: true, get: function () { return fs_2.lstatSync; } }); +Object.defineProperty(exports, "unlinkSync", { enumerable: true, get: function () { return fs_2.unlinkSync; } }); +const fs_3 = require("fs"); +const readdirSync = (path) => (0, fs_3.readdirSync)(path, { withFileTypes: true }); +exports.readdirSync = readdirSync; +// unrolled for better inlining, this seems to get better performance +// than something like: +// const makeCb = (res, rej) => (er, ...d) => er ? rej(er) : res(...d) +// which would be a bit cleaner. +const chmod = (path, mode) => new Promise((res, rej) => fs_1.default.chmod(path, mode, (er, ...d) => (er ? rej(er) : res(...d)))); +const mkdir = (path, options) => new Promise((res, rej) => fs_1.default.mkdir(path, options, (er, made) => (er ? rej(er) : res(made)))); +const readdir = (path) => new Promise((res, rej) => fs_1.default.readdir(path, { withFileTypes: true }, (er, data) => er ? rej(er) : res(data))); +const rename = (oldPath, newPath) => new Promise((res, rej) => fs_1.default.rename(oldPath, newPath, (er, ...d) => er ? rej(er) : res(...d))); +const rm = (path, options) => new Promise((res, rej) => fs_1.default.rm(path, options, (er, ...d) => (er ? rej(er) : res(...d)))); +const rmdir = (path) => new Promise((res, rej) => fs_1.default.rmdir(path, (er, ...d) => (er ? rej(er) : res(...d)))); +const stat = (path) => new Promise((res, rej) => fs_1.default.stat(path, (er, data) => (er ? rej(er) : res(data)))); +const lstat = (path) => new Promise((res, rej) => fs_1.default.lstat(path, (er, data) => (er ? rej(er) : res(data)))); +const unlink = (path) => new Promise((res, rej) => fs_1.default.unlink(path, (er, ...d) => (er ? rej(er) : res(...d)))); +exports.promises = { + chmod, + mkdir, + readdir, + rename, + rm, + rmdir, + stat, + lstat, + unlink, +}; +//# sourceMappingURL=fs.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/fs.js.map b/node_modules/rimraf/dist/commonjs/fs.js.map new file mode 100644 index 0000000..9d9e1fb --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/fs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fs.js","sourceRoot":"","sources":["../../src/fs.ts"],"names":[],"mappings":";AAAA,kEAAkE;;;;;;AAElE,4CAA+B;AAE/B,iDAAiD;AACjD,yBASW;AART,+FAAA,SAAS,OAAA;AACT,+FAAA,SAAS,OAAA;AACT,gGAAA,UAAU,OAAA;AACV,+FAAA,SAAS,OAAA;AACT,4FAAA,MAAM,OAAA;AACN,8FAAA,QAAQ,OAAA;AACR,+FAAA,SAAS,OAAA;AACT,gGAAA,UAAU,OAAA;AAGZ,2BAA0C;AACnC,MAAM,WAAW,GAAG,CAAC,IAAiB,EAAY,EAAE,CACzD,IAAA,gBAAM,EAAC,IAAI,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,CAAA;AAD1B,QAAA,WAAW,eACe;AAEvC,qEAAqE;AACrE,uBAAuB;AACvB,sEAAsE;AACtE,gCAAgC;AAEhC,MAAM,KAAK,GAAG,CAAC,IAAiB,EAAE,IAAa,EAAiB,EAAE,CAChE,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,YAAE,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE,GAAG,CAAQ,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CACtE,CAAA;AAEH,MAAM,KAAK,GAAG,CACZ,IAAiB,EACjB,OAIQ,EACqB,EAAE,CAC/B,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,YAAE,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAClE,CAAA;AAEH,MAAM,OAAO,GAAG,CAAC,IAAiB,EAAqB,EAAE,CACvD,IAAI,OAAO,CAAW,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACjC,YAAE,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,CACrD,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CACzB,CACF,CAAA;AAEH,MAAM,MAAM,GAAG,CAAC,OAAoB,EAAE,OAAoB,EAAiB,EAAE,CAC3E,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,YAAE,CAAC,MAAM,CAAC,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,GAAG,CAAQ,EAAE,EAAE,CAC9C,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CACzB,CACF,CAAA;AAEH,MAAM,EAAE,GAAG,CAAC,IAAiB,EAAE,OAAqB,EAAiB,EAAE,CACrE,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,YAAE,CAAC,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,GAAG,CAAQ,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CACtE,CAAA;AAEH,MAAM,KAAK,GAAG,CAAC,IAAiB,EAAiB,EAAE,CACjD,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,YAAE,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,GAAG,CAAQ,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAChE,CAAA;AAEH,MAAM,IAAI,GAAG,CAAC,IAAiB,EAAqB,EAAE,CACpD,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,YAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CACxD,CAAA;AAEH,MAAM,KAAK,GAAG,CAAC,IAAiB,EAAqB,EAAE,CACrD,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,YAAE,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CACzD,CAAA;AAEH,MAAM,MAAM,GAAG,CAAC,IAAiB,EAAiB,EAAE,CAClD,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,YAAE,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,GAAG,CAAQ,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CACjE,CAAA;AAEU,QAAA,QAAQ,GAAG;IACtB,KAAK;IACL,KAAK;IACL,OAAO;IACP,MAAM;IACN,EAAE;IACF,KAAK;IACL,IAAI;IACJ,KAAK;IACL,MAAM;CACP,CAAA","sourcesContent":["// promisify ourselves, because older nodes don't have fs.promises\n\nimport fs, { Dirent } from 'fs'\n\n// sync ones just take the sync version from node\nexport {\n chmodSync,\n mkdirSync,\n renameSync,\n rmdirSync,\n rmSync,\n statSync,\n lstatSync,\n unlinkSync,\n} from 'fs'\n\nimport { readdirSync as rdSync } from 'fs'\nexport const readdirSync = (path: fs.PathLike): Dirent[] =>\n rdSync(path, { withFileTypes: true })\n\n// unrolled for better inlining, this seems to get better performance\n// than something like:\n// const makeCb = (res, rej) => (er, ...d) => er ? rej(er) : res(...d)\n// which would be a bit cleaner.\n\nconst chmod = (path: fs.PathLike, mode: fs.Mode): Promise =>\n new Promise((res, rej) =>\n fs.chmod(path, mode, (er, ...d: any[]) => (er ? rej(er) : res(...d))),\n )\n\nconst mkdir = (\n path: fs.PathLike,\n options?:\n | fs.Mode\n | (fs.MakeDirectoryOptions & { recursive?: boolean | null })\n | undefined\n | null,\n): Promise =>\n new Promise((res, rej) =>\n fs.mkdir(path, options, (er, made) => (er ? rej(er) : res(made))),\n )\n\nconst readdir = (path: fs.PathLike): Promise =>\n new Promise((res, rej) =>\n fs.readdir(path, { withFileTypes: true }, (er, data) =>\n er ? rej(er) : res(data),\n ),\n )\n\nconst rename = (oldPath: fs.PathLike, newPath: fs.PathLike): Promise =>\n new Promise((res, rej) =>\n fs.rename(oldPath, newPath, (er, ...d: any[]) =>\n er ? rej(er) : res(...d),\n ),\n )\n\nconst rm = (path: fs.PathLike, options: fs.RmOptions): Promise =>\n new Promise((res, rej) =>\n fs.rm(path, options, (er, ...d: any[]) => (er ? rej(er) : res(...d))),\n )\n\nconst rmdir = (path: fs.PathLike): Promise =>\n new Promise((res, rej) =>\n fs.rmdir(path, (er, ...d: any[]) => (er ? rej(er) : res(...d))),\n )\n\nconst stat = (path: fs.PathLike): Promise =>\n new Promise((res, rej) =>\n fs.stat(path, (er, data) => (er ? rej(er) : res(data))),\n )\n\nconst lstat = (path: fs.PathLike): Promise =>\n new Promise((res, rej) =>\n fs.lstat(path, (er, data) => (er ? rej(er) : res(data))),\n )\n\nconst unlink = (path: fs.PathLike): Promise =>\n new Promise((res, rej) =>\n fs.unlink(path, (er, ...d: any[]) => (er ? rej(er) : res(...d))),\n )\n\nexport const promises = {\n chmod,\n mkdir,\n readdir,\n rename,\n rm,\n rmdir,\n stat,\n lstat,\n unlink,\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/ignore-enoent.d.ts b/node_modules/rimraf/dist/commonjs/ignore-enoent.d.ts new file mode 100644 index 0000000..f158cc2 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/ignore-enoent.d.ts @@ -0,0 +1,3 @@ +export declare const ignoreENOENT: (p: Promise) => Promise; +export declare const ignoreENOENTSync: (fn: () => any) => any; +//# sourceMappingURL=ignore-enoent.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/ignore-enoent.d.ts.map b/node_modules/rimraf/dist/commonjs/ignore-enoent.d.ts.map new file mode 100644 index 0000000..2cfb3bb --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/ignore-enoent.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ignore-enoent.d.ts","sourceRoot":"","sources":["../../src/ignore-enoent.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,YAAY,MAAa,OAAO,CAAC,GAAG,CAAC,iBAK9C,CAAA;AAEJ,eAAO,MAAM,gBAAgB,OAAQ,MAAM,GAAG,QAQ7C,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/ignore-enoent.js b/node_modules/rimraf/dist/commonjs/ignore-enoent.js new file mode 100644 index 0000000..0259534 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/ignore-enoent.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ignoreENOENTSync = exports.ignoreENOENT = void 0; +const ignoreENOENT = async (p) => p.catch(er => { + if (er.code !== 'ENOENT') { + throw er; + } +}); +exports.ignoreENOENT = ignoreENOENT; +const ignoreENOENTSync = (fn) => { + try { + return fn(); + } + catch (er) { + if (er?.code !== 'ENOENT') { + throw er; + } + } +}; +exports.ignoreENOENTSync = ignoreENOENTSync; +//# sourceMappingURL=ignore-enoent.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/ignore-enoent.js.map b/node_modules/rimraf/dist/commonjs/ignore-enoent.js.map new file mode 100644 index 0000000..7acf4c2 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/ignore-enoent.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ignore-enoent.js","sourceRoot":"","sources":["../../src/ignore-enoent.ts"],"names":[],"mappings":";;;AAAO,MAAM,YAAY,GAAG,KAAK,EAAE,CAAe,EAAE,EAAE,CACpD,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE;IACX,IAAI,EAAE,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QACzB,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAC,CAAA;AALS,QAAA,YAAY,gBAKrB;AAEG,MAAM,gBAAgB,GAAG,CAAC,EAAa,EAAE,EAAE;IAChD,IAAI,CAAC;QACH,OAAO,EAAE,EAAE,CAAA;IACb,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,IAAK,EAA4B,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;YACrD,MAAM,EAAE,CAAA;QACV,CAAC;IACH,CAAC;AACH,CAAC,CAAA;AARY,QAAA,gBAAgB,oBAQ5B","sourcesContent":["export const ignoreENOENT = async (p: Promise) =>\n p.catch(er => {\n if (er.code !== 'ENOENT') {\n throw er\n }\n })\n\nexport const ignoreENOENTSync = (fn: () => any) => {\n try {\n return fn()\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code !== 'ENOENT') {\n throw er\n }\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/index.d.ts b/node_modules/rimraf/dist/commonjs/index.d.ts new file mode 100644 index 0000000..9ec4a12 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/index.d.ts @@ -0,0 +1,50 @@ +import { RimrafAsyncOptions, RimrafSyncOptions } from './opt-arg.js'; +export { assertRimrafOptions, isRimrafOptions, type RimrafAsyncOptions, type RimrafOptions, type RimrafSyncOptions, } from './opt-arg.js'; +export declare const nativeSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +export declare const native: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +}; +export declare const manualSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +export declare const manual: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +}; +export declare const windowsSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +export declare const windows: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +}; +export declare const posixSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +export declare const posix: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +}; +export declare const moveRemoveSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +export declare const moveRemove: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +}; +export declare const rimrafSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +export declare const sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +export declare const rimraf: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + rimraf: (path: string | string[], opt?: RimrafAsyncOptions) => Promise; + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + rimrafSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + manual: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + }; + manualSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + native: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + }; + nativeSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + posix: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + }; + posixSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + windows: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + }; + windowsSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + moveRemove: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + }; + moveRemoveSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/index.d.ts.map b/node_modules/rimraf/dist/commonjs/index.d.ts.map new file mode 100644 index 0000000..0dc659c --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,kBAAkB,EAClB,iBAAiB,EAClB,MAAM,cAAc,CAAA;AASrB,OAAO,EACL,mBAAmB,EACnB,eAAe,EACf,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,KAAK,iBAAiB,GACvB,MAAM,cAAc,CAAA;AAqCrB,eAAO,MAAM,UAAU,SAdd,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAcF,CAAA;AACpD,eAAO,MAAM,MAAM,UAjCT,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;iBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;CAegB,CAAA;AAE7E,eAAO,MAAM,UAAU,SAjBd,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAiBF,CAAA;AACpD,eAAO,MAAM,MAAM,UApCT,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;iBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;CAkBgB,CAAA;AAE7E,eAAO,MAAM,WAAW,SApBf,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAoBA,CAAA;AACtD,eAAO,MAAM,OAAO,UAvCV,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;iBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;CAqBmB,CAAA;AAEhF,eAAO,MAAM,SAAS,SAvBb,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAuBJ,CAAA;AAClD,eAAO,MAAM,KAAK,UA1CR,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;iBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;CAwBa,CAAA;AAE1E,eAAO,MAAM,cAAc,SA1BlB,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OA0BM,CAAA;AAC5D,eAAO,MAAM,UAAU,UA7Cb,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;iBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;CA6B3D,CAAA;AAEF,eAAO,MAAM,UAAU,SA/Bd,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAmCrD,CAAA;AACD,eAAO,MAAM,IAAI,SApCR,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAoCxB,CAAA;AAK9B,eAAO,MAAM,MAAM,UA3DT,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;mBAFX,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;iBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;uBAApD,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;oBAlBnD,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;qBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;;uBAApD,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;oBAlBnD,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;qBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;;uBAApD,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;mBAlBnD,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;qBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;;sBAApD,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;qBAlBnD,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;qBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;;wBAApD,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;wBAlBnD,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;qBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;;2BAApD,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;CAuD3D,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/index.js b/node_modules/rimraf/dist/commonjs/index.js new file mode 100644 index 0000000..09b5d99 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/index.js @@ -0,0 +1,78 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.rimraf = exports.sync = exports.rimrafSync = exports.moveRemove = exports.moveRemoveSync = exports.posix = exports.posixSync = exports.windows = exports.windowsSync = exports.manual = exports.manualSync = exports.native = exports.nativeSync = exports.isRimrafOptions = exports.assertRimrafOptions = void 0; +const glob_1 = require("glob"); +const opt_arg_js_1 = require("./opt-arg.js"); +const path_arg_js_1 = __importDefault(require("./path-arg.js")); +const rimraf_manual_js_1 = require("./rimraf-manual.js"); +const rimraf_move_remove_js_1 = require("./rimraf-move-remove.js"); +const rimraf_native_js_1 = require("./rimraf-native.js"); +const rimraf_posix_js_1 = require("./rimraf-posix.js"); +const rimraf_windows_js_1 = require("./rimraf-windows.js"); +const use_native_js_1 = require("./use-native.js"); +var opt_arg_js_2 = require("./opt-arg.js"); +Object.defineProperty(exports, "assertRimrafOptions", { enumerable: true, get: function () { return opt_arg_js_2.assertRimrafOptions; } }); +Object.defineProperty(exports, "isRimrafOptions", { enumerable: true, get: function () { return opt_arg_js_2.isRimrafOptions; } }); +const wrap = (fn) => async (path, opt) => { + const options = (0, opt_arg_js_1.optArg)(opt); + if (options.glob) { + path = await (0, glob_1.glob)(path, options.glob); + } + if (Array.isArray(path)) { + return !!(await Promise.all(path.map(p => fn((0, path_arg_js_1.default)(p, options), options)))).reduce((a, b) => a && b, true); + } + else { + return !!(await fn((0, path_arg_js_1.default)(path, options), options)); + } +}; +const wrapSync = (fn) => (path, opt) => { + const options = (0, opt_arg_js_1.optArgSync)(opt); + if (options.glob) { + path = (0, glob_1.globSync)(path, options.glob); + } + if (Array.isArray(path)) { + return !!path + .map(p => fn((0, path_arg_js_1.default)(p, options), options)) + .reduce((a, b) => a && b, true); + } + else { + return !!fn((0, path_arg_js_1.default)(path, options), options); + } +}; +exports.nativeSync = wrapSync(rimraf_native_js_1.rimrafNativeSync); +exports.native = Object.assign(wrap(rimraf_native_js_1.rimrafNative), { sync: exports.nativeSync }); +exports.manualSync = wrapSync(rimraf_manual_js_1.rimrafManualSync); +exports.manual = Object.assign(wrap(rimraf_manual_js_1.rimrafManual), { sync: exports.manualSync }); +exports.windowsSync = wrapSync(rimraf_windows_js_1.rimrafWindowsSync); +exports.windows = Object.assign(wrap(rimraf_windows_js_1.rimrafWindows), { sync: exports.windowsSync }); +exports.posixSync = wrapSync(rimraf_posix_js_1.rimrafPosixSync); +exports.posix = Object.assign(wrap(rimraf_posix_js_1.rimrafPosix), { sync: exports.posixSync }); +exports.moveRemoveSync = wrapSync(rimraf_move_remove_js_1.rimrafMoveRemoveSync); +exports.moveRemove = Object.assign(wrap(rimraf_move_remove_js_1.rimrafMoveRemove), { + sync: exports.moveRemoveSync, +}); +exports.rimrafSync = wrapSync((path, opt) => (0, use_native_js_1.useNativeSync)(opt) ? + (0, rimraf_native_js_1.rimrafNativeSync)(path, opt) + : (0, rimraf_manual_js_1.rimrafManualSync)(path, opt)); +exports.sync = exports.rimrafSync; +const rimraf_ = wrap((path, opt) => (0, use_native_js_1.useNative)(opt) ? (0, rimraf_native_js_1.rimrafNative)(path, opt) : (0, rimraf_manual_js_1.rimrafManual)(path, opt)); +exports.rimraf = Object.assign(rimraf_, { + rimraf: rimraf_, + sync: exports.rimrafSync, + rimrafSync: exports.rimrafSync, + manual: exports.manual, + manualSync: exports.manualSync, + native: exports.native, + nativeSync: exports.nativeSync, + posix: exports.posix, + posixSync: exports.posixSync, + windows: exports.windows, + windowsSync: exports.windowsSync, + moveRemove: exports.moveRemove, + moveRemoveSync: exports.moveRemoveSync, +}); +exports.rimraf.rimraf = exports.rimraf; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/index.js.map b/node_modules/rimraf/dist/commonjs/index.js.map new file mode 100644 index 0000000..5ed1978 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;AAAA,+BAAqC;AACrC,6CAKqB;AACrB,gEAAmC;AACnC,yDAAmE;AACnE,mEAAgF;AAChF,yDAAmE;AACnE,uDAAgE;AAChE,2DAAsE;AACtE,mDAA0D;AAE1D,2CAMqB;AALnB,iHAAA,mBAAmB,OAAA;AACnB,6GAAA,eAAe,OAAA;AAMjB,MAAM,IAAI,GACR,CAAC,EAA0D,EAAE,EAAE,CAC/D,KAAK,EACH,IAAuB,EACvB,GAAwB,EACN,EAAE;IACpB,MAAM,OAAO,GAAG,IAAA,mBAAM,EAAC,GAAG,CAAC,CAAA;IAC3B,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,IAAI,GAAG,MAAM,IAAA,WAAI,EAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,CAAA;IACvC,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;QACxB,OAAO,CAAC,CAAC,CACP,MAAM,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAA,qBAAO,EAAC,CAAC,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CACnE,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAA;IAClC,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,IAAA,qBAAO,EAAC,IAAI,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,CAAA;IACtD,CAAC;AACH,CAAC,CAAA;AAEH,MAAM,QAAQ,GACZ,CAAC,EAAgD,EAAE,EAAE,CACrD,CAAC,IAAuB,EAAE,GAAuB,EAAW,EAAE;IAC5D,MAAM,OAAO,GAAG,IAAA,uBAAU,EAAC,GAAG,CAAC,CAAA;IAC/B,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,IAAI,GAAG,IAAA,eAAQ,EAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,CAAA;IACrC,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;QACxB,OAAO,CAAC,CAAC,IAAI;aACV,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAA,qBAAO,EAAC,CAAC,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC;aAC1C,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAA;IACnC,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,CAAC,EAAE,CAAC,IAAA,qBAAO,EAAC,IAAI,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAA;IAC9C,CAAC;AACH,CAAC,CAAA;AAEU,QAAA,UAAU,GAAG,QAAQ,CAAC,mCAAgB,CAAC,CAAA;AACvC,QAAA,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,+BAAY,CAAC,EAAE,EAAE,IAAI,EAAE,kBAAU,EAAE,CAAC,CAAA;AAEhE,QAAA,UAAU,GAAG,QAAQ,CAAC,mCAAgB,CAAC,CAAA;AACvC,QAAA,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,+BAAY,CAAC,EAAE,EAAE,IAAI,EAAE,kBAAU,EAAE,CAAC,CAAA;AAEhE,QAAA,WAAW,GAAG,QAAQ,CAAC,qCAAiB,CAAC,CAAA;AACzC,QAAA,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,iCAAa,CAAC,EAAE,EAAE,IAAI,EAAE,mBAAW,EAAE,CAAC,CAAA;AAEnE,QAAA,SAAS,GAAG,QAAQ,CAAC,iCAAe,CAAC,CAAA;AACrC,QAAA,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,6BAAW,CAAC,EAAE,EAAE,IAAI,EAAE,iBAAS,EAAE,CAAC,CAAA;AAE7D,QAAA,cAAc,GAAG,QAAQ,CAAC,4CAAoB,CAAC,CAAA;AAC/C,QAAA,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,wCAAgB,CAAC,EAAE;IAC9D,IAAI,EAAE,sBAAc;CACrB,CAAC,CAAA;AAEW,QAAA,UAAU,GAAG,QAAQ,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,CAC/C,IAAA,6BAAa,EAAC,GAAG,CAAC,CAAC,CAAC;IAClB,IAAA,mCAAgB,EAAC,IAAI,EAAE,GAAG,CAAC;IAC7B,CAAC,CAAC,IAAA,mCAAgB,EAAC,IAAI,EAAE,GAAG,CAAC,CAC9B,CAAA;AACY,QAAA,IAAI,GAAG,kBAAU,CAAA;AAE9B,MAAM,OAAO,GAAG,IAAI,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,CACjC,IAAA,yBAAS,EAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAA,+BAAY,EAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,IAAA,+BAAY,EAAC,IAAI,EAAE,GAAG,CAAC,CACnE,CAAA;AACY,QAAA,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE;IAC3C,MAAM,EAAE,OAAO;IACf,IAAI,EAAE,kBAAU;IAChB,UAAU,EAAE,kBAAU;IACtB,MAAM,EAAN,cAAM;IACN,UAAU,EAAV,kBAAU;IACV,MAAM,EAAN,cAAM;IACN,UAAU,EAAV,kBAAU;IACV,KAAK,EAAL,aAAK;IACL,SAAS,EAAT,iBAAS;IACT,OAAO,EAAP,eAAO;IACP,WAAW,EAAX,mBAAW;IACX,UAAU,EAAV,kBAAU;IACV,cAAc,EAAd,sBAAc;CACf,CAAC,CAAA;AACF,cAAM,CAAC,MAAM,GAAG,cAAM,CAAA","sourcesContent":["import { glob, globSync } from 'glob'\nimport {\n optArg,\n optArgSync,\n RimrafAsyncOptions,\n RimrafSyncOptions,\n} from './opt-arg.js'\nimport pathArg from './path-arg.js'\nimport { rimrafManual, rimrafManualSync } from './rimraf-manual.js'\nimport { rimrafMoveRemove, rimrafMoveRemoveSync } from './rimraf-move-remove.js'\nimport { rimrafNative, rimrafNativeSync } from './rimraf-native.js'\nimport { rimrafPosix, rimrafPosixSync } from './rimraf-posix.js'\nimport { rimrafWindows, rimrafWindowsSync } from './rimraf-windows.js'\nimport { useNative, useNativeSync } from './use-native.js'\n\nexport {\n assertRimrafOptions,\n isRimrafOptions,\n type RimrafAsyncOptions,\n type RimrafOptions,\n type RimrafSyncOptions,\n} from './opt-arg.js'\n\nconst wrap =\n (fn: (p: string, o: RimrafAsyncOptions) => Promise) =>\n async (\n path: string | string[],\n opt?: RimrafAsyncOptions,\n ): Promise => {\n const options = optArg(opt)\n if (options.glob) {\n path = await glob(path, options.glob)\n }\n if (Array.isArray(path)) {\n return !!(\n await Promise.all(path.map(p => fn(pathArg(p, options), options)))\n ).reduce((a, b) => a && b, true)\n } else {\n return !!(await fn(pathArg(path, options), options))\n }\n }\n\nconst wrapSync =\n (fn: (p: string, o: RimrafSyncOptions) => boolean) =>\n (path: string | string[], opt?: RimrafSyncOptions): boolean => {\n const options = optArgSync(opt)\n if (options.glob) {\n path = globSync(path, options.glob)\n }\n if (Array.isArray(path)) {\n return !!path\n .map(p => fn(pathArg(p, options), options))\n .reduce((a, b) => a && b, true)\n } else {\n return !!fn(pathArg(path, options), options)\n }\n }\n\nexport const nativeSync = wrapSync(rimrafNativeSync)\nexport const native = Object.assign(wrap(rimrafNative), { sync: nativeSync })\n\nexport const manualSync = wrapSync(rimrafManualSync)\nexport const manual = Object.assign(wrap(rimrafManual), { sync: manualSync })\n\nexport const windowsSync = wrapSync(rimrafWindowsSync)\nexport const windows = Object.assign(wrap(rimrafWindows), { sync: windowsSync })\n\nexport const posixSync = wrapSync(rimrafPosixSync)\nexport const posix = Object.assign(wrap(rimrafPosix), { sync: posixSync })\n\nexport const moveRemoveSync = wrapSync(rimrafMoveRemoveSync)\nexport const moveRemove = Object.assign(wrap(rimrafMoveRemove), {\n sync: moveRemoveSync,\n})\n\nexport const rimrafSync = wrapSync((path, opt) =>\n useNativeSync(opt) ?\n rimrafNativeSync(path, opt)\n : rimrafManualSync(path, opt),\n)\nexport const sync = rimrafSync\n\nconst rimraf_ = wrap((path, opt) =>\n useNative(opt) ? rimrafNative(path, opt) : rimrafManual(path, opt),\n)\nexport const rimraf = Object.assign(rimraf_, {\n rimraf: rimraf_,\n sync: rimrafSync,\n rimrafSync: rimrafSync,\n manual,\n manualSync,\n native,\n nativeSync,\n posix,\n posixSync,\n windows,\n windowsSync,\n moveRemove,\n moveRemoveSync,\n})\nrimraf.rimraf = rimraf\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/opt-arg.d.ts b/node_modules/rimraf/dist/commonjs/opt-arg.d.ts new file mode 100644 index 0000000..c869d4a --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/opt-arg.d.ts @@ -0,0 +1,34 @@ +import { Dirent, Stats } from 'fs'; +import { GlobOptions } from 'glob'; +export declare const isRimrafOptions: (o: any) => o is RimrafOptions; +export declare const assertRimrafOptions: (o: any) => void; +export interface RimrafAsyncOptions { + preserveRoot?: boolean; + tmp?: string; + maxRetries?: number; + retryDelay?: number; + backoff?: number; + maxBackoff?: number; + signal?: AbortSignal; + glob?: boolean | GlobOptions; + filter?: ((path: string, ent: Dirent | Stats) => boolean) | ((path: string, ent: Dirent | Stats) => Promise); +} +export interface RimrafSyncOptions extends RimrafAsyncOptions { + filter?: (path: string, ent: Dirent | Stats) => boolean; +} +export type RimrafOptions = RimrafSyncOptions | RimrafAsyncOptions; +export declare const optArg: (opt?: RimrafAsyncOptions) => (RimrafAsyncOptions & { + glob: GlobOptions & { + withFileTypes: false; + }; +}) | (RimrafAsyncOptions & { + glob: undefined; +}); +export declare const optArgSync: (opt?: RimrafSyncOptions) => (RimrafSyncOptions & { + glob: GlobOptions & { + withFileTypes: false; + }; +}) | (RimrafSyncOptions & { + glob: undefined; +}); +//# sourceMappingURL=opt-arg.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/opt-arg.d.ts.map b/node_modules/rimraf/dist/commonjs/opt-arg.d.ts.map new file mode 100644 index 0000000..89e83b2 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/opt-arg.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"opt-arg.d.ts","sourceRoot":"","sources":["../../src/opt-arg.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,IAAI,CAAA;AAClC,OAAO,EAAE,WAAW,EAAE,MAAM,MAAM,CAAA;AAKlC,eAAO,MAAM,eAAe,MAAO,GAAG,KAAG,CAAC,IAAI,aAUX,CAAA;AAEnC,eAAO,MAAM,mBAAmB,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,IAM7C,CAAA;AAED,MAAM,WAAW,kBAAkB;IACjC,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,IAAI,CAAC,EAAE,OAAO,GAAG,WAAW,CAAA;IAC5B,MAAM,CAAC,EACH,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,KAAK,KAAK,OAAO,CAAC,GAChD,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,KAAK,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC,CAAA;CAC9D;AAED,MAAM,WAAW,iBAAkB,SAAQ,kBAAkB;IAC3D,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,KAAK,KAAK,OAAO,CAAA;CACxD;AAED,MAAM,MAAM,aAAa,GAAG,iBAAiB,GAAG,kBAAkB,CAAA;AAqClE,eAAO,MAAM,MAAM,SAAS,kBAAkB;UA/BlC,WAAW,GAAG;QAAE,aAAa,EAAE,KAAK,CAAA;KAAE;;UAEjC,SAAS;EA6B0C,CAAA;AACpE,eAAO,MAAM,UAAU,SAAS,iBAAiB;UAhCrC,WAAW,GAAG;QAAE,aAAa,EAAE,KAAK,CAAA;KAAE;;UAEjC,SAAS;EA8B6C,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/opt-arg.js b/node_modules/rimraf/dist/commonjs/opt-arg.js new file mode 100644 index 0000000..1d030a1 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/opt-arg.js @@ -0,0 +1,53 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.optArgSync = exports.optArg = exports.assertRimrafOptions = exports.isRimrafOptions = void 0; +const typeOrUndef = (val, t) => typeof val === 'undefined' || typeof val === t; +const isRimrafOptions = (o) => !!o && + typeof o === 'object' && + typeOrUndef(o.preserveRoot, 'boolean') && + typeOrUndef(o.tmp, 'string') && + typeOrUndef(o.maxRetries, 'number') && + typeOrUndef(o.retryDelay, 'number') && + typeOrUndef(o.backoff, 'number') && + typeOrUndef(o.maxBackoff, 'number') && + (typeOrUndef(o.glob, 'boolean') || (o.glob && typeof o.glob === 'object')) && + typeOrUndef(o.filter, 'function'); +exports.isRimrafOptions = isRimrafOptions; +const assertRimrafOptions = (o) => { + if (!(0, exports.isRimrafOptions)(o)) { + throw new Error('invalid rimraf options'); + } +}; +exports.assertRimrafOptions = assertRimrafOptions; +const optArgT = (opt) => { + (0, exports.assertRimrafOptions)(opt); + const { glob, ...options } = opt; + if (!glob) { + return options; + } + const globOpt = glob === true ? + opt.signal ? + { signal: opt.signal } + : {} + : opt.signal ? + { + signal: opt.signal, + ...glob, + } + : glob; + return { + ...options, + glob: { + ...globOpt, + // always get absolute paths from glob, to ensure + // that we are referencing the correct thing. + absolute: true, + withFileTypes: false, + }, + }; +}; +const optArg = (opt = {}) => optArgT(opt); +exports.optArg = optArg; +const optArgSync = (opt = {}) => optArgT(opt); +exports.optArgSync = optArgSync; +//# sourceMappingURL=opt-arg.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/opt-arg.js.map b/node_modules/rimraf/dist/commonjs/opt-arg.js.map new file mode 100644 index 0000000..d815735 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/opt-arg.js.map @@ -0,0 +1 @@ +{"version":3,"file":"opt-arg.js","sourceRoot":"","sources":["../../src/opt-arg.ts"],"names":[],"mappings":";;;AAGA,MAAM,WAAW,GAAG,CAAC,GAAQ,EAAE,CAAS,EAAE,EAAE,CAC1C,OAAO,GAAG,KAAK,WAAW,IAAI,OAAO,GAAG,KAAK,CAAC,CAAA;AAEzC,MAAM,eAAe,GAAG,CAAC,CAAM,EAAsB,EAAE,CAC5D,CAAC,CAAC,CAAC;IACH,OAAO,CAAC,KAAK,QAAQ;IACrB,WAAW,CAAC,CAAC,CAAC,YAAY,EAAE,SAAS,CAAC;IACtC,WAAW,CAAC,CAAC,CAAC,GAAG,EAAE,QAAQ,CAAC;IAC5B,WAAW,CAAC,CAAC,CAAC,UAAU,EAAE,QAAQ,CAAC;IACnC,WAAW,CAAC,CAAC,CAAC,UAAU,EAAE,QAAQ,CAAC;IACnC,WAAW,CAAC,CAAC,CAAC,OAAO,EAAE,QAAQ,CAAC;IAChC,WAAW,CAAC,CAAC,CAAC,UAAU,EAAE,QAAQ,CAAC;IACnC,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,EAAE,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,OAAO,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC;IAC1E,WAAW,CAAC,CAAC,CAAC,MAAM,EAAE,UAAU,CAAC,CAAA;AAVtB,QAAA,eAAe,mBAUO;AAE5B,MAAM,mBAAmB,GAAqB,CACnD,CAAM,EACsB,EAAE;IAC9B,IAAI,CAAC,IAAA,uBAAe,EAAC,CAAC,CAAC,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAA;IAC3C,CAAC;AACH,CAAC,CAAA;AANY,QAAA,mBAAmB,uBAM/B;AAsBD,MAAM,OAAO,GAAG,CACd,GAAM,EAKsB,EAAE;IAC9B,IAAA,2BAAmB,EAAC,GAAG,CAAC,CAAA;IACxB,MAAM,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,GAAG,GAAG,CAAA;IAChC,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,OAAO,OAAkC,CAAA;IAC3C,CAAC;IACD,MAAM,OAAO,GACX,IAAI,KAAK,IAAI,CAAC,CAAC;QACb,GAAG,CAAC,MAAM,CAAC,CAAC;YACV,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE;YACxB,CAAC,CAAC,EAAE;QACN,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YACZ;gBACE,MAAM,EAAE,GAAG,CAAC,MAAM;gBAClB,GAAG,IAAI;aACR;YACH,CAAC,CAAC,IAAI,CAAA;IACR,OAAO;QACL,GAAG,OAAO;QACV,IAAI,EAAE;YACJ,GAAG,OAAO;YACV,iDAAiD;YACjD,6CAA6C;YAC7C,QAAQ,EAAE,IAAI;YACd,aAAa,EAAE,KAAK;SACrB;KACsD,CAAA;AAC3D,CAAC,CAAA;AAEM,MAAM,MAAM,GAAG,CAAC,MAA0B,EAAE,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;AAAvD,QAAA,MAAM,UAAiD;AAC7D,MAAM,UAAU,GAAG,CAAC,MAAyB,EAAE,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;AAA1D,QAAA,UAAU,cAAgD","sourcesContent":["import { Dirent, Stats } from 'fs'\nimport { GlobOptions } from 'glob'\n\nconst typeOrUndef = (val: any, t: string) =>\n typeof val === 'undefined' || typeof val === t\n\nexport const isRimrafOptions = (o: any): o is RimrafOptions =>\n !!o &&\n typeof o === 'object' &&\n typeOrUndef(o.preserveRoot, 'boolean') &&\n typeOrUndef(o.tmp, 'string') &&\n typeOrUndef(o.maxRetries, 'number') &&\n typeOrUndef(o.retryDelay, 'number') &&\n typeOrUndef(o.backoff, 'number') &&\n typeOrUndef(o.maxBackoff, 'number') &&\n (typeOrUndef(o.glob, 'boolean') || (o.glob && typeof o.glob === 'object')) &&\n typeOrUndef(o.filter, 'function')\n\nexport const assertRimrafOptions: (o: any) => void = (\n o: any,\n): asserts o is RimrafOptions => {\n if (!isRimrafOptions(o)) {\n throw new Error('invalid rimraf options')\n }\n}\n\nexport interface RimrafAsyncOptions {\n preserveRoot?: boolean\n tmp?: string\n maxRetries?: number\n retryDelay?: number\n backoff?: number\n maxBackoff?: number\n signal?: AbortSignal\n glob?: boolean | GlobOptions\n filter?:\n | ((path: string, ent: Dirent | Stats) => boolean)\n | ((path: string, ent: Dirent | Stats) => Promise)\n}\n\nexport interface RimrafSyncOptions extends RimrafAsyncOptions {\n filter?: (path: string, ent: Dirent | Stats) => boolean\n}\n\nexport type RimrafOptions = RimrafSyncOptions | RimrafAsyncOptions\n\nconst optArgT = (\n opt: T,\n):\n | (T & {\n glob: GlobOptions & { withFileTypes: false }\n })\n | (T & { glob: undefined }) => {\n assertRimrafOptions(opt)\n const { glob, ...options } = opt\n if (!glob) {\n return options as T & { glob: undefined }\n }\n const globOpt =\n glob === true ?\n opt.signal ?\n { signal: opt.signal }\n : {}\n : opt.signal ?\n {\n signal: opt.signal,\n ...glob,\n }\n : glob\n return {\n ...options,\n glob: {\n ...globOpt,\n // always get absolute paths from glob, to ensure\n // that we are referencing the correct thing.\n absolute: true,\n withFileTypes: false,\n },\n } as T & { glob: GlobOptions & { withFileTypes: false } }\n}\n\nexport const optArg = (opt: RimrafAsyncOptions = {}) => optArgT(opt)\nexport const optArgSync = (opt: RimrafSyncOptions = {}) => optArgT(opt)\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/package.json b/node_modules/rimraf/dist/commonjs/package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/rimraf/dist/commonjs/path-arg.d.ts b/node_modules/rimraf/dist/commonjs/path-arg.d.ts new file mode 100644 index 0000000..c0b7e7c --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/path-arg.d.ts @@ -0,0 +1,4 @@ +import { RimrafAsyncOptions } from './index.js'; +declare const pathArg: (path: string, opt?: RimrafAsyncOptions) => string; +export default pathArg; +//# sourceMappingURL=path-arg.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/path-arg.d.ts.map b/node_modules/rimraf/dist/commonjs/path-arg.d.ts.map new file mode 100644 index 0000000..4fe93c3 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/path-arg.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"path-arg.d.ts","sourceRoot":"","sources":["../../src/path-arg.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAG/C,QAAA,MAAM,OAAO,SAAU,MAAM,QAAO,kBAAkB,WAgDrD,CAAA;AAED,eAAe,OAAO,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/path-arg.js b/node_modules/rimraf/dist/commonjs/path-arg.js new file mode 100644 index 0000000..8a4908a --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/path-arg.js @@ -0,0 +1,52 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const path_1 = require("path"); +const util_1 = require("util"); +const platform_js_1 = __importDefault(require("./platform.js")); +const pathArg = (path, opt = {}) => { + const type = typeof path; + if (type !== 'string') { + const ctor = path && type === 'object' && path.constructor; + const received = ctor && ctor.name ? `an instance of ${ctor.name}` + : type === 'object' ? (0, util_1.inspect)(path) + : `type ${type} ${path}`; + const msg = 'The "path" argument must be of type string. ' + `Received ${received}`; + throw Object.assign(new TypeError(msg), { + path, + code: 'ERR_INVALID_ARG_TYPE', + }); + } + if (/\0/.test(path)) { + // simulate same failure that node raises + const msg = 'path must be a string without null bytes'; + throw Object.assign(new TypeError(msg), { + path, + code: 'ERR_INVALID_ARG_VALUE', + }); + } + path = (0, path_1.resolve)(path); + const { root } = (0, path_1.parse)(path); + if (path === root && opt.preserveRoot !== false) { + const msg = 'refusing to remove root directory without preserveRoot:false'; + throw Object.assign(new Error(msg), { + path, + code: 'ERR_PRESERVE_ROOT', + }); + } + if (platform_js_1.default === 'win32') { + const badWinChars = /[*|"<>?:]/; + const { root } = (0, path_1.parse)(path); + if (badWinChars.test(path.substring(root.length))) { + throw Object.assign(new Error('Illegal characters in path.'), { + path, + code: 'EINVAL', + }); + } + } + return path; +}; +exports.default = pathArg; +//# sourceMappingURL=path-arg.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/path-arg.js.map b/node_modules/rimraf/dist/commonjs/path-arg.js.map new file mode 100644 index 0000000..40e4a19 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/path-arg.js.map @@ -0,0 +1 @@ +{"version":3,"file":"path-arg.js","sourceRoot":"","sources":["../../src/path-arg.ts"],"names":[],"mappings":";;;;;AAAA,+BAAqC;AACrC,+BAA8B;AAE9B,gEAAoC;AAEpC,MAAM,OAAO,GAAG,CAAC,IAAY,EAAE,MAA0B,EAAE,EAAE,EAAE;IAC7D,MAAM,IAAI,GAAG,OAAO,IAAI,CAAA;IACxB,IAAI,IAAI,KAAK,QAAQ,EAAE,CAAC;QACtB,MAAM,IAAI,GAAG,IAAI,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,WAAW,CAAA;QAC1D,MAAM,QAAQ,GACZ,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,kBAAkB,IAAI,CAAC,IAAI,EAAE;YACjD,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAA,cAAO,EAAC,IAAI,CAAC;gBACnC,CAAC,CAAC,QAAQ,IAAI,IAAI,IAAI,EAAE,CAAA;QAC1B,MAAM,GAAG,GACP,8CAA8C,GAAG,YAAY,QAAQ,EAAE,CAAA;QACzE,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,SAAS,CAAC,GAAG,CAAC,EAAE;YACtC,IAAI;YACJ,IAAI,EAAE,sBAAsB;SAC7B,CAAC,CAAA;IACJ,CAAC;IAED,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACpB,yCAAyC;QACzC,MAAM,GAAG,GAAG,0CAA0C,CAAA;QACtD,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,SAAS,CAAC,GAAG,CAAC,EAAE;YACtC,IAAI;YACJ,IAAI,EAAE,uBAAuB;SAC9B,CAAC,CAAA;IACJ,CAAC;IAED,IAAI,GAAG,IAAA,cAAO,EAAC,IAAI,CAAC,CAAA;IACpB,MAAM,EAAE,IAAI,EAAE,GAAG,IAAA,YAAK,EAAC,IAAI,CAAC,CAAA;IAE5B,IAAI,IAAI,KAAK,IAAI,IAAI,GAAG,CAAC,YAAY,KAAK,KAAK,EAAE,CAAC;QAChD,MAAM,GAAG,GAAG,8DAA8D,CAAA;QAC1E,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,GAAG,CAAC,EAAE;YAClC,IAAI;YACJ,IAAI,EAAE,mBAAmB;SAC1B,CAAC,CAAA;IACJ,CAAC;IAED,IAAI,qBAAQ,KAAK,OAAO,EAAE,CAAC;QACzB,MAAM,WAAW,GAAG,WAAW,CAAA;QAC/B,MAAM,EAAE,IAAI,EAAE,GAAG,IAAA,YAAK,EAAC,IAAI,CAAC,CAAA;QAC5B,IAAI,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC;YAClD,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,6BAA6B,CAAC,EAAE;gBAC5D,IAAI;gBACJ,IAAI,EAAE,QAAQ;aACf,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;IAED,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,kBAAe,OAAO,CAAA","sourcesContent":["import { parse, resolve } from 'path'\nimport { inspect } from 'util'\nimport { RimrafAsyncOptions } from './index.js'\nimport platform from './platform.js'\n\nconst pathArg = (path: string, opt: RimrafAsyncOptions = {}) => {\n const type = typeof path\n if (type !== 'string') {\n const ctor = path && type === 'object' && path.constructor\n const received =\n ctor && ctor.name ? `an instance of ${ctor.name}`\n : type === 'object' ? inspect(path)\n : `type ${type} ${path}`\n const msg =\n 'The \"path\" argument must be of type string. ' + `Received ${received}`\n throw Object.assign(new TypeError(msg), {\n path,\n code: 'ERR_INVALID_ARG_TYPE',\n })\n }\n\n if (/\\0/.test(path)) {\n // simulate same failure that node raises\n const msg = 'path must be a string without null bytes'\n throw Object.assign(new TypeError(msg), {\n path,\n code: 'ERR_INVALID_ARG_VALUE',\n })\n }\n\n path = resolve(path)\n const { root } = parse(path)\n\n if (path === root && opt.preserveRoot !== false) {\n const msg = 'refusing to remove root directory without preserveRoot:false'\n throw Object.assign(new Error(msg), {\n path,\n code: 'ERR_PRESERVE_ROOT',\n })\n }\n\n if (platform === 'win32') {\n const badWinChars = /[*|\"<>?:]/\n const { root } = parse(path)\n if (badWinChars.test(path.substring(root.length))) {\n throw Object.assign(new Error('Illegal characters in path.'), {\n path,\n code: 'EINVAL',\n })\n }\n }\n\n return path\n}\n\nexport default pathArg\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/platform.d.ts b/node_modules/rimraf/dist/commonjs/platform.d.ts new file mode 100644 index 0000000..e127a8e --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/platform.d.ts @@ -0,0 +1,3 @@ +declare const _default: string; +export default _default; +//# sourceMappingURL=platform.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/platform.d.ts.map b/node_modules/rimraf/dist/commonjs/platform.d.ts.map new file mode 100644 index 0000000..ef2e673 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/platform.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"platform.d.ts","sourceRoot":"","sources":["../../src/platform.ts"],"names":[],"mappings":";AAAA,wBAA0E"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/platform.js b/node_modules/rimraf/dist/commonjs/platform.js new file mode 100644 index 0000000..58f197f --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/platform.js @@ -0,0 +1,4 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = process.env.__TESTING_RIMRAF_PLATFORM__ || process.platform; +//# sourceMappingURL=platform.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/platform.js.map b/node_modules/rimraf/dist/commonjs/platform.js.map new file mode 100644 index 0000000..814cdb8 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/platform.js.map @@ -0,0 +1 @@ +{"version":3,"file":"platform.js","sourceRoot":"","sources":["../../src/platform.ts"],"names":[],"mappings":";;AAAA,kBAAe,OAAO,CAAC,GAAG,CAAC,2BAA2B,IAAI,OAAO,CAAC,QAAQ,CAAA","sourcesContent":["export default process.env.__TESTING_RIMRAF_PLATFORM__ || process.platform\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/readdir-or-error.d.ts b/node_modules/rimraf/dist/commonjs/readdir-or-error.d.ts new file mode 100644 index 0000000..cce7309 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/readdir-or-error.d.ts @@ -0,0 +1,3 @@ +export declare const readdirOrError: (path: string) => Promise; +export declare const readdirOrErrorSync: (path: string) => import("fs").Dirent[] | NodeJS.ErrnoException; +//# sourceMappingURL=readdir-or-error.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/readdir-or-error.d.ts.map b/node_modules/rimraf/dist/commonjs/readdir-or-error.d.ts.map new file mode 100644 index 0000000..8a19f6b --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/readdir-or-error.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"readdir-or-error.d.ts","sourceRoot":"","sources":["../../src/readdir-or-error.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,cAAc,SAAU,MAAM,2DACa,CAAA;AACxD,eAAO,MAAM,kBAAkB,SAAU,MAAM,kDAM9C,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/readdir-or-error.js b/node_modules/rimraf/dist/commonjs/readdir-or-error.js new file mode 100644 index 0000000..75330cb --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/readdir-or-error.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readdirOrErrorSync = exports.readdirOrError = void 0; +// returns an array of entries if readdir() works, +// or the error that readdir() raised if not. +const fs_js_1 = require("./fs.js"); +const { readdir } = fs_js_1.promises; +const readdirOrError = (path) => readdir(path).catch(er => er); +exports.readdirOrError = readdirOrError; +const readdirOrErrorSync = (path) => { + try { + return (0, fs_js_1.readdirSync)(path); + } + catch (er) { + return er; + } +}; +exports.readdirOrErrorSync = readdirOrErrorSync; +//# sourceMappingURL=readdir-or-error.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/readdir-or-error.js.map b/node_modules/rimraf/dist/commonjs/readdir-or-error.js.map new file mode 100644 index 0000000..61dbfe1 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/readdir-or-error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"readdir-or-error.js","sourceRoot":"","sources":["../../src/readdir-or-error.ts"],"names":[],"mappings":";;;AAAA,kDAAkD;AAClD,6CAA6C;AAC7C,mCAA+C;AAC/C,MAAM,EAAE,OAAO,EAAE,GAAG,gBAAQ,CAAA;AACrB,MAAM,cAAc,GAAG,CAAC,IAAY,EAAE,EAAE,CAC7C,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,CAAC,EAA2B,CAAC,CAAA;AAD3C,QAAA,cAAc,kBAC6B;AACjD,MAAM,kBAAkB,GAAG,CAAC,IAAY,EAAE,EAAE;IACjD,IAAI,CAAC;QACH,OAAO,IAAA,mBAAW,EAAC,IAAI,CAAC,CAAA;IAC1B,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,OAAO,EAA2B,CAAA;IACpC,CAAC;AACH,CAAC,CAAA;AANY,QAAA,kBAAkB,sBAM9B","sourcesContent":["// returns an array of entries if readdir() works,\n// or the error that readdir() raised if not.\nimport { promises, readdirSync } from './fs.js'\nconst { readdir } = promises\nexport const readdirOrError = (path: string) =>\n readdir(path).catch(er => er as NodeJS.ErrnoException)\nexport const readdirOrErrorSync = (path: string) => {\n try {\n return readdirSync(path)\n } catch (er) {\n return er as NodeJS.ErrnoException\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/retry-busy.d.ts b/node_modules/rimraf/dist/commonjs/retry-busy.d.ts new file mode 100644 index 0000000..c0af0dd --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/retry-busy.d.ts @@ -0,0 +1,8 @@ +import { RimrafAsyncOptions, RimrafOptions } from './index.js'; +export declare const MAXBACKOFF = 200; +export declare const RATE = 1.2; +export declare const MAXRETRIES = 10; +export declare const codes: Set; +export declare const retryBusy: (fn: (path: string) => Promise) => (path: string, opt: RimrafAsyncOptions, backoff?: number, total?: number) => Promise; +export declare const retryBusySync: (fn: (path: string) => any) => (path: string, opt: RimrafOptions) => any; +//# sourceMappingURL=retry-busy.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/retry-busy.d.ts.map b/node_modules/rimraf/dist/commonjs/retry-busy.d.ts.map new file mode 100644 index 0000000..21960c5 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/retry-busy.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"retry-busy.d.ts","sourceRoot":"","sources":["../../src/retry-busy.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAE9D,eAAO,MAAM,UAAU,MAAM,CAAA;AAC7B,eAAO,MAAM,IAAI,MAAM,CAAA;AACvB,eAAO,MAAM,UAAU,KAAK,CAAA;AAC5B,eAAO,MAAM,KAAK,aAAyC,CAAA;AAE3D,eAAO,MAAM,SAAS,OAAQ,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,GAAG,CAAC,YAElD,MAAM,OACP,kBAAkB,mDAkC1B,CAAA;AAGD,eAAO,MAAM,aAAa,OAAQ,CAAC,IAAI,EAAE,MAAM,KAAK,GAAG,YAC/B,MAAM,OAAO,aAAa,QAsBjD,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/retry-busy.js b/node_modules/rimraf/dist/commonjs/retry-busy.js new file mode 100644 index 0000000..5f9d152 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/retry-busy.js @@ -0,0 +1,68 @@ +"use strict"; +// note: max backoff is the maximum that any *single* backoff will do +Object.defineProperty(exports, "__esModule", { value: true }); +exports.retryBusySync = exports.retryBusy = exports.codes = exports.MAXRETRIES = exports.RATE = exports.MAXBACKOFF = void 0; +exports.MAXBACKOFF = 200; +exports.RATE = 1.2; +exports.MAXRETRIES = 10; +exports.codes = new Set(['EMFILE', 'ENFILE', 'EBUSY']); +const retryBusy = (fn) => { + const method = async (path, opt, backoff = 1, total = 0) => { + const mbo = opt.maxBackoff || exports.MAXBACKOFF; + const rate = opt.backoff || exports.RATE; + const max = opt.maxRetries || exports.MAXRETRIES; + let retries = 0; + while (true) { + try { + return await fn(path); + } + catch (er) { + const fer = er; + if (fer?.path === path && fer?.code && exports.codes.has(fer.code)) { + backoff = Math.ceil(backoff * rate); + total = backoff + total; + if (total < mbo) { + return new Promise((res, rej) => { + setTimeout(() => { + method(path, opt, backoff, total).then(res, rej); + }, backoff); + }); + } + if (retries < max) { + retries++; + continue; + } + } + throw er; + } + } + }; + return method; +}; +exports.retryBusy = retryBusy; +// just retries, no async so no backoff +const retryBusySync = (fn) => { + const method = (path, opt) => { + const max = opt.maxRetries || exports.MAXRETRIES; + let retries = 0; + while (true) { + try { + return fn(path); + } + catch (er) { + const fer = er; + if (fer?.path === path && + fer?.code && + exports.codes.has(fer.code) && + retries < max) { + retries++; + continue; + } + throw er; + } + } + }; + return method; +}; +exports.retryBusySync = retryBusySync; +//# sourceMappingURL=retry-busy.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/retry-busy.js.map b/node_modules/rimraf/dist/commonjs/retry-busy.js.map new file mode 100644 index 0000000..1f1051d --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/retry-busy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"retry-busy.js","sourceRoot":"","sources":["../../src/retry-busy.ts"],"names":[],"mappings":";AAAA,qEAAqE;;;AAIxD,QAAA,UAAU,GAAG,GAAG,CAAA;AAChB,QAAA,IAAI,GAAG,GAAG,CAAA;AACV,QAAA,UAAU,GAAG,EAAE,CAAA;AACf,QAAA,KAAK,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAA;AAEpD,MAAM,SAAS,GAAG,CAAC,EAAkC,EAAE,EAAE;IAC9D,MAAM,MAAM,GAAG,KAAK,EAClB,IAAY,EACZ,GAAuB,EACvB,OAAO,GAAG,CAAC,EACX,KAAK,GAAG,CAAC,EACT,EAAE;QACF,MAAM,GAAG,GAAG,GAAG,CAAC,UAAU,IAAI,kBAAU,CAAA;QACxC,MAAM,IAAI,GAAG,GAAG,CAAC,OAAO,IAAI,YAAI,CAAA;QAChC,MAAM,GAAG,GAAG,GAAG,CAAC,UAAU,IAAI,kBAAU,CAAA;QACxC,IAAI,OAAO,GAAG,CAAC,CAAA;QACf,OAAO,IAAI,EAAE,CAAC;YACZ,IAAI,CAAC;gBACH,OAAO,MAAM,EAAE,CAAC,IAAI,CAAC,CAAA;YACvB,CAAC;YAAC,OAAO,EAAE,EAAE,CAAC;gBACZ,MAAM,GAAG,GAAG,EAA2B,CAAA;gBACvC,IAAI,GAAG,EAAE,IAAI,KAAK,IAAI,IAAI,GAAG,EAAE,IAAI,IAAI,aAAK,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;oBAC3D,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,CAAA;oBACnC,KAAK,GAAG,OAAO,GAAG,KAAK,CAAA;oBACvB,IAAI,KAAK,GAAG,GAAG,EAAE,CAAC;wBAChB,OAAO,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;4BAC9B,UAAU,CAAC,GAAG,EAAE;gCACd,MAAM,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;4BAClD,CAAC,EAAE,OAAO,CAAC,CAAA;wBACb,CAAC,CAAC,CAAA;oBACJ,CAAC;oBACD,IAAI,OAAO,GAAG,GAAG,EAAE,CAAC;wBAClB,OAAO,EAAE,CAAA;wBACT,SAAQ;oBACV,CAAC;gBACH,CAAC;gBACD,MAAM,EAAE,CAAA;YACV,CAAC;QACH,CAAC;IACH,CAAC,CAAA;IAED,OAAO,MAAM,CAAA;AACf,CAAC,CAAA;AArCY,QAAA,SAAS,aAqCrB;AAED,uCAAuC;AAChC,MAAM,aAAa,GAAG,CAAC,EAAyB,EAAE,EAAE;IACzD,MAAM,MAAM,GAAG,CAAC,IAAY,EAAE,GAAkB,EAAE,EAAE;QAClD,MAAM,GAAG,GAAG,GAAG,CAAC,UAAU,IAAI,kBAAU,CAAA;QACxC,IAAI,OAAO,GAAG,CAAC,CAAA;QACf,OAAO,IAAI,EAAE,CAAC;YACZ,IAAI,CAAC;gBACH,OAAO,EAAE,CAAC,IAAI,CAAC,CAAA;YACjB,CAAC;YAAC,OAAO,EAAE,EAAE,CAAC;gBACZ,MAAM,GAAG,GAAG,EAA2B,CAAA;gBACvC,IACE,GAAG,EAAE,IAAI,KAAK,IAAI;oBAClB,GAAG,EAAE,IAAI;oBACT,aAAK,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC;oBACnB,OAAO,GAAG,GAAG,EACb,CAAC;oBACD,OAAO,EAAE,CAAA;oBACT,SAAQ;gBACV,CAAC;gBACD,MAAM,EAAE,CAAA;YACV,CAAC;QACH,CAAC;IACH,CAAC,CAAA;IACD,OAAO,MAAM,CAAA;AACf,CAAC,CAAA;AAvBY,QAAA,aAAa,iBAuBzB","sourcesContent":["// note: max backoff is the maximum that any *single* backoff will do\n\nimport { RimrafAsyncOptions, RimrafOptions } from './index.js'\n\nexport const MAXBACKOFF = 200\nexport const RATE = 1.2\nexport const MAXRETRIES = 10\nexport const codes = new Set(['EMFILE', 'ENFILE', 'EBUSY'])\n\nexport const retryBusy = (fn: (path: string) => Promise) => {\n const method = async (\n path: string,\n opt: RimrafAsyncOptions,\n backoff = 1,\n total = 0,\n ) => {\n const mbo = opt.maxBackoff || MAXBACKOFF\n const rate = opt.backoff || RATE\n const max = opt.maxRetries || MAXRETRIES\n let retries = 0\n while (true) {\n try {\n return await fn(path)\n } catch (er) {\n const fer = er as NodeJS.ErrnoException\n if (fer?.path === path && fer?.code && codes.has(fer.code)) {\n backoff = Math.ceil(backoff * rate)\n total = backoff + total\n if (total < mbo) {\n return new Promise((res, rej) => {\n setTimeout(() => {\n method(path, opt, backoff, total).then(res, rej)\n }, backoff)\n })\n }\n if (retries < max) {\n retries++\n continue\n }\n }\n throw er\n }\n }\n }\n\n return method\n}\n\n// just retries, no async so no backoff\nexport const retryBusySync = (fn: (path: string) => any) => {\n const method = (path: string, opt: RimrafOptions) => {\n const max = opt.maxRetries || MAXRETRIES\n let retries = 0\n while (true) {\n try {\n return fn(path)\n } catch (er) {\n const fer = er as NodeJS.ErrnoException\n if (\n fer?.path === path &&\n fer?.code &&\n codes.has(fer.code) &&\n retries < max\n ) {\n retries++\n continue\n }\n throw er\n }\n }\n }\n return method\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-manual.d.ts b/node_modules/rimraf/dist/commonjs/rimraf-manual.d.ts new file mode 100644 index 0000000..35c5c86 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-manual.d.ts @@ -0,0 +1,3 @@ +export declare const rimrafManual: (path: string, opt: import("./opt-arg.js").RimrafAsyncOptions) => Promise; +export declare const rimrafManualSync: (path: string, opt: import("./opt-arg.js").RimrafSyncOptions) => boolean; +//# sourceMappingURL=rimraf-manual.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-manual.d.ts.map b/node_modules/rimraf/dist/commonjs/rimraf-manual.d.ts.map new file mode 100644 index 0000000..19bd251 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-manual.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-manual.d.ts","sourceRoot":"","sources":["../../src/rimraf-manual.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,YAAY,oFAAqD,CAAA;AAC9E,eAAO,MAAM,gBAAgB,0EAC+B,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-manual.js b/node_modules/rimraf/dist/commonjs/rimraf-manual.js new file mode 100644 index 0000000..1c95ae2 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-manual.js @@ -0,0 +1,12 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.rimrafManualSync = exports.rimrafManual = void 0; +const platform_js_1 = __importDefault(require("./platform.js")); +const rimraf_posix_js_1 = require("./rimraf-posix.js"); +const rimraf_windows_js_1 = require("./rimraf-windows.js"); +exports.rimrafManual = platform_js_1.default === 'win32' ? rimraf_windows_js_1.rimrafWindows : rimraf_posix_js_1.rimrafPosix; +exports.rimrafManualSync = platform_js_1.default === 'win32' ? rimraf_windows_js_1.rimrafWindowsSync : rimraf_posix_js_1.rimrafPosixSync; +//# sourceMappingURL=rimraf-manual.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-manual.js.map b/node_modules/rimraf/dist/commonjs/rimraf-manual.js.map new file mode 100644 index 0000000..e26e445 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-manual.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-manual.js","sourceRoot":"","sources":["../../src/rimraf-manual.ts"],"names":[],"mappings":";;;;;;AAAA,gEAAoC;AAEpC,uDAAgE;AAChE,2DAAsE;AAEzD,QAAA,YAAY,GAAG,qBAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,iCAAa,CAAC,CAAC,CAAC,6BAAW,CAAA;AACjE,QAAA,gBAAgB,GAC3B,qBAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,qCAAiB,CAAC,CAAC,CAAC,iCAAe,CAAA","sourcesContent":["import platform from './platform.js'\n\nimport { rimrafPosix, rimrafPosixSync } from './rimraf-posix.js'\nimport { rimrafWindows, rimrafWindowsSync } from './rimraf-windows.js'\n\nexport const rimrafManual = platform === 'win32' ? rimrafWindows : rimrafPosix\nexport const rimrafManualSync =\n platform === 'win32' ? rimrafWindowsSync : rimrafPosixSync\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-move-remove.d.ts b/node_modules/rimraf/dist/commonjs/rimraf-move-remove.d.ts new file mode 100644 index 0000000..5d41d40 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-move-remove.d.ts @@ -0,0 +1,4 @@ +import { RimrafAsyncOptions, RimrafSyncOptions } from './index.js'; +export declare const rimrafMoveRemove: (path: string, opt: RimrafAsyncOptions) => Promise; +export declare const rimrafMoveRemoveSync: (path: string, opt: RimrafSyncOptions) => boolean; +//# sourceMappingURL=rimraf-move-remove.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-move-remove.d.ts.map b/node_modules/rimraf/dist/commonjs/rimraf-move-remove.d.ts.map new file mode 100644 index 0000000..4062eae --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-move-remove.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-move-remove.d.ts","sourceRoot":"","sources":["../../src/rimraf-move-remove.ts"],"names":[],"mappings":"AA6BA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AA4ClE,eAAO,MAAM,gBAAgB,SACrB,MAAM,OACP,kBAAkB,qBAWxB,CAAA;AA4ED,eAAO,MAAM,oBAAoB,SAAU,MAAM,OAAO,iBAAiB,YAUxE,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-move-remove.js b/node_modules/rimraf/dist/commonjs/rimraf-move-remove.js new file mode 100644 index 0000000..ac668d1 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-move-remove.js @@ -0,0 +1,192 @@ +"use strict"; +// https://youtu.be/uhRWMGBjlO8?t=537 +// +// 1. readdir +// 2. for each entry +// a. if a non-empty directory, recurse +// b. if an empty directory, move to random hidden file name in $TEMP +// c. unlink/rmdir $TEMP +// +// This works around the fact that unlink/rmdir is non-atomic and takes +// a non-deterministic amount of time to complete. +// +// However, it is HELLA SLOW, like 2-10x slower than a naive recursive rm. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.rimrafMoveRemoveSync = exports.rimrafMoveRemove = void 0; +const path_1 = require("path"); +const default_tmp_js_1 = require("./default-tmp.js"); +const ignore_enoent_js_1 = require("./ignore-enoent.js"); +const fs_js_1 = require("./fs.js"); +const { lstat, rename, unlink, rmdir, chmod } = fs_js_1.promises; +const readdir_or_error_js_1 = require("./readdir-or-error.js"); +// crypto.randomBytes is much slower, and Math.random() is enough here +const uniqueFilename = (path) => `.${(0, path_1.basename)(path)}.${Math.random()}`; +const unlinkFixEPERM = async (path) => unlink(path).catch((er) => { + if (er.code === 'EPERM') { + return chmod(path, 0o666).then(() => unlink(path), er2 => { + if (er2.code === 'ENOENT') { + return; + } + throw er; + }); + } + else if (er.code === 'ENOENT') { + return; + } + throw er; +}); +const unlinkFixEPERMSync = (path) => { + try { + (0, fs_js_1.unlinkSync)(path); + } + catch (er) { + if (er?.code === 'EPERM') { + try { + return (0, fs_js_1.chmodSync)(path, 0o666); + } + catch (er2) { + if (er2?.code === 'ENOENT') { + return; + } + throw er; + } + } + else if (er?.code === 'ENOENT') { + return; + } + throw er; + } +}; +const rimrafMoveRemove = async (path, opt) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + try { + return await rimrafMoveRemoveDir(path, opt, await lstat(path)); + } + catch (er) { + if (er?.code === 'ENOENT') + return true; + throw er; + } +}; +exports.rimrafMoveRemove = rimrafMoveRemove; +const rimrafMoveRemoveDir = async (path, opt, ent) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + if (!opt.tmp) { + return rimrafMoveRemoveDir(path, { ...opt, tmp: await (0, default_tmp_js_1.defaultTmp)(path) }, ent); + } + if (path === opt.tmp && (0, path_1.parse)(path).root !== path) { + throw new Error('cannot delete temp directory used for deletion'); + } + const entries = ent.isDirectory() ? await (0, readdir_or_error_js_1.readdirOrError)(path) : null; + if (!Array.isArray(entries)) { + // this can only happen if lstat/readdir lied, or if the dir was + // swapped out with a file at just the right moment. + /* c8 ignore start */ + if (entries) { + if (entries.code === 'ENOENT') { + return true; + } + if (entries.code !== 'ENOTDIR') { + throw entries; + } + } + /* c8 ignore stop */ + if (opt.filter && !(await opt.filter(path, ent))) { + return false; + } + await (0, ignore_enoent_js_1.ignoreENOENT)(tmpUnlink(path, opt.tmp, unlinkFixEPERM)); + return true; + } + const removedAll = (await Promise.all(entries.map(ent => rimrafMoveRemoveDir((0, path_1.resolve)(path, ent.name), opt, ent)))).reduce((a, b) => a && b, true); + if (!removedAll) { + return false; + } + // we don't ever ACTUALLY try to unlink /, because that can never work + // but when preserveRoot is false, we could be operating on it. + // No need to check if preserveRoot is not false. + if (opt.preserveRoot === false && path === (0, path_1.parse)(path).root) { + return false; + } + if (opt.filter && !(await opt.filter(path, ent))) { + return false; + } + await (0, ignore_enoent_js_1.ignoreENOENT)(tmpUnlink(path, opt.tmp, rmdir)); + return true; +}; +const tmpUnlink = async (path, tmp, rm) => { + const tmpFile = (0, path_1.resolve)(tmp, uniqueFilename(path)); + await rename(path, tmpFile); + return await rm(tmpFile); +}; +const rimrafMoveRemoveSync = (path, opt) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + try { + return rimrafMoveRemoveDirSync(path, opt, (0, fs_js_1.lstatSync)(path)); + } + catch (er) { + if (er?.code === 'ENOENT') + return true; + throw er; + } +}; +exports.rimrafMoveRemoveSync = rimrafMoveRemoveSync; +const rimrafMoveRemoveDirSync = (path, opt, ent) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + if (!opt.tmp) { + return rimrafMoveRemoveDirSync(path, { ...opt, tmp: (0, default_tmp_js_1.defaultTmpSync)(path) }, ent); + } + const tmp = opt.tmp; + if (path === opt.tmp && (0, path_1.parse)(path).root !== path) { + throw new Error('cannot delete temp directory used for deletion'); + } + const entries = ent.isDirectory() ? (0, readdir_or_error_js_1.readdirOrErrorSync)(path) : null; + if (!Array.isArray(entries)) { + // this can only happen if lstat/readdir lied, or if the dir was + // swapped out with a file at just the right moment. + /* c8 ignore start */ + if (entries) { + if (entries.code === 'ENOENT') { + return true; + } + if (entries.code !== 'ENOTDIR') { + throw entries; + } + } + /* c8 ignore stop */ + if (opt.filter && !opt.filter(path, ent)) { + return false; + } + (0, ignore_enoent_js_1.ignoreENOENTSync)(() => tmpUnlinkSync(path, tmp, unlinkFixEPERMSync)); + return true; + } + let removedAll = true; + for (const ent of entries) { + const p = (0, path_1.resolve)(path, ent.name); + removedAll = rimrafMoveRemoveDirSync(p, opt, ent) && removedAll; + } + if (!removedAll) { + return false; + } + if (opt.preserveRoot === false && path === (0, path_1.parse)(path).root) { + return false; + } + if (opt.filter && !opt.filter(path, ent)) { + return false; + } + (0, ignore_enoent_js_1.ignoreENOENTSync)(() => tmpUnlinkSync(path, tmp, fs_js_1.rmdirSync)); + return true; +}; +const tmpUnlinkSync = (path, tmp, rmSync) => { + const tmpFile = (0, path_1.resolve)(tmp, uniqueFilename(path)); + (0, fs_js_1.renameSync)(path, tmpFile); + return rmSync(tmpFile); +}; +//# sourceMappingURL=rimraf-move-remove.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-move-remove.js.map b/node_modules/rimraf/dist/commonjs/rimraf-move-remove.js.map new file mode 100644 index 0000000..4460250 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-move-remove.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-move-remove.js","sourceRoot":"","sources":["../../src/rimraf-move-remove.ts"],"names":[],"mappings":";AAAA,qCAAqC;AACrC,EAAE;AACF,aAAa;AACb,oBAAoB;AACpB,yCAAyC;AACzC,uEAAuE;AACvE,0BAA0B;AAC1B,EAAE;AACF,uEAAuE;AACvE,kDAAkD;AAClD,EAAE;AACF,0EAA0E;;;AAE1E,+BAA+C;AAC/C,qDAA6D;AAE7D,yDAAmE;AAEnE,mCAOgB;AAChB,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,gBAAU,CAAA;AAI1D,+DAA0E;AAE1E,sEAAsE;AACtE,MAAM,cAAc,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,IAAA,eAAQ,EAAC,IAAI,CAAC,IAAI,IAAI,CAAC,MAAM,EAAE,EAAE,CAAA;AAE9E,MAAM,cAAc,GAAG,KAAK,EAAE,IAAY,EAAE,EAAE,CAC5C,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,EAA6B,EAAE,EAAE;IACnD,IAAI,EAAE,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;QACxB,OAAO,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,IAAI,CAC5B,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,EAClB,GAAG,CAAC,EAAE;YACJ,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC1B,OAAM;YACR,CAAC;YACD,MAAM,EAAE,CAAA;QACV,CAAC,CACF,CAAA;IACH,CAAC;SAAM,IAAI,EAAE,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QAChC,OAAM;IACR,CAAC;IACD,MAAM,EAAE,CAAA;AACV,CAAC,CAAC,CAAA;AAEJ,MAAM,kBAAkB,GAAG,CAAC,IAAY,EAAE,EAAE;IAC1C,IAAI,CAAC;QACH,IAAA,kBAAU,EAAC,IAAI,CAAC,CAAA;IAClB,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,IAAK,EAA4B,EAAE,IAAI,KAAK,OAAO,EAAE,CAAC;YACpD,IAAI,CAAC;gBACH,OAAO,IAAA,iBAAS,EAAC,IAAI,EAAE,KAAK,CAAC,CAAA;YAC/B,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,IAAK,GAA6B,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;oBACtD,OAAM;gBACR,CAAC;gBACD,MAAM,EAAE,CAAA;YACV,CAAC;QACH,CAAC;aAAM,IAAK,EAA4B,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC5D,OAAM;QACR,CAAC;QACD,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAEM,MAAM,gBAAgB,GAAG,KAAK,EACnC,IAAY,EACZ,GAAuB,EACvB,EAAE;IACF,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,IAAI,CAAC;QACH,OAAO,MAAM,mBAAmB,CAAC,IAAI,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC,IAAI,CAAC,CAAC,CAAA;IAChE,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,IAAK,EAA4B,EAAE,IAAI,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAA;QACjE,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAbY,QAAA,gBAAgB,oBAa5B;AAED,MAAM,mBAAmB,GAAG,KAAK,EAC/B,IAAY,EACZ,GAAuB,EACvB,GAAmB,EACD,EAAE;IACpB,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;QACb,OAAO,mBAAmB,CACxB,IAAI,EACJ,EAAE,GAAG,GAAG,EAAE,GAAG,EAAE,MAAM,IAAA,2BAAU,EAAC,IAAI,CAAC,EAAE,EACvC,GAAG,CACJ,CAAA;IACH,CAAC;IACD,IAAI,IAAI,KAAK,GAAG,CAAC,GAAG,IAAI,IAAA,YAAK,EAAC,IAAI,CAAC,CAAC,IAAI,KAAK,IAAI,EAAE,CAAC;QAClD,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAA;IACnE,CAAC;IAED,MAAM,OAAO,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,MAAM,IAAA,oCAAc,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACrE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,gEAAgE;QAChE,oDAAoD;QACpD,qBAAqB;QACrB,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC9B,OAAO,IAAI,CAAA;YACb,CAAC;YACD,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;gBAC/B,MAAM,OAAO,CAAA;YACf,CAAC;QACH,CAAC;QACD,oBAAoB;QACpB,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC;YACjD,OAAO,KAAK,CAAA;QACd,CAAC;QACD,MAAM,IAAA,+BAAY,EAAC,SAAS,CAAC,IAAI,EAAE,GAAG,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC,CAAA;QAC5D,OAAO,IAAI,CAAA;IACb,CAAC;IAED,MAAM,UAAU,GAAG,CACjB,MAAM,OAAO,CAAC,GAAG,CACf,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAChB,mBAAmB,CAAC,IAAA,cAAO,EAAC,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,CACvD,CACF,CACF,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAA;IAChC,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,KAAK,CAAA;IACd,CAAC;IAED,sEAAsE;IACtE,+DAA+D;IAC/D,iDAAiD;IACjD,IAAI,GAAG,CAAC,YAAY,KAAK,KAAK,IAAI,IAAI,KAAK,IAAA,YAAK,EAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;QAC5D,OAAO,KAAK,CAAA;IACd,CAAC;IACD,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC;QACjD,OAAO,KAAK,CAAA;IACd,CAAC;IACD,MAAM,IAAA,+BAAY,EAAC,SAAS,CAAC,IAAI,EAAE,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAA;IACnD,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,MAAM,SAAS,GAAG,KAAK,EACrB,IAAY,EACZ,GAAW,EACX,EAA+B,EAC/B,EAAE;IACF,MAAM,OAAO,GAAG,IAAA,cAAO,EAAC,GAAG,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC,CAAA;IAClD,MAAM,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IAC3B,OAAO,MAAM,EAAE,CAAC,OAAO,CAAC,CAAA;AAC1B,CAAC,CAAA;AAEM,MAAM,oBAAoB,GAAG,CAAC,IAAY,EAAE,GAAsB,EAAE,EAAE;IAC3E,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,IAAI,CAAC;QACH,OAAO,uBAAuB,CAAC,IAAI,EAAE,GAAG,EAAE,IAAA,iBAAS,EAAC,IAAI,CAAC,CAAC,CAAA;IAC5D,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,IAAK,EAA4B,EAAE,IAAI,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAA;QACjE,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAVY,QAAA,oBAAoB,wBAUhC;AAED,MAAM,uBAAuB,GAAG,CAC9B,IAAY,EACZ,GAAsB,EACtB,GAAmB,EACV,EAAE;IACX,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;QACb,OAAO,uBAAuB,CAC5B,IAAI,EACJ,EAAE,GAAG,GAAG,EAAE,GAAG,EAAE,IAAA,+BAAc,EAAC,IAAI,CAAC,EAAE,EACrC,GAAG,CACJ,CAAA;IACH,CAAC;IACD,MAAM,GAAG,GAAW,GAAG,CAAC,GAAG,CAAA;IAE3B,IAAI,IAAI,KAAK,GAAG,CAAC,GAAG,IAAI,IAAA,YAAK,EAAC,IAAI,CAAC,CAAC,IAAI,KAAK,IAAI,EAAE,CAAC;QAClD,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAA;IACnE,CAAC;IAED,MAAM,OAAO,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,IAAA,wCAAkB,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACnE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,gEAAgE;QAChE,oDAAoD;QACpD,qBAAqB;QACrB,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC9B,OAAO,IAAI,CAAA;YACb,CAAC;YACD,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;gBAC/B,MAAM,OAAO,CAAA;YACf,CAAC;QACH,CAAC;QACD,oBAAoB;QACpB,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzC,OAAO,KAAK,CAAA;QACd,CAAC;QACD,IAAA,mCAAgB,EAAC,GAAG,EAAE,CAAC,aAAa,CAAC,IAAI,EAAE,GAAG,EAAE,kBAAkB,CAAC,CAAC,CAAA;QACpE,OAAO,IAAI,CAAA;IACb,CAAC;IAED,IAAI,UAAU,GAAG,IAAI,CAAA;IACrB,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE,CAAC;QAC1B,MAAM,CAAC,GAAG,IAAA,cAAO,EAAC,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,CAAA;QACjC,UAAU,GAAG,uBAAuB,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,IAAI,UAAU,CAAA;IACjE,CAAC;IACD,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,KAAK,CAAA;IACd,CAAC;IACD,IAAI,GAAG,CAAC,YAAY,KAAK,KAAK,IAAI,IAAI,KAAK,IAAA,YAAK,EAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;QAC5D,OAAO,KAAK,CAAA;IACd,CAAC;IACD,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;QACzC,OAAO,KAAK,CAAA;IACd,CAAC;IACD,IAAA,mCAAgB,EAAC,GAAG,EAAE,CAAC,aAAa,CAAC,IAAI,EAAE,GAAG,EAAE,iBAAS,CAAC,CAAC,CAAA;IAC3D,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,MAAM,aAAa,GAAG,CACpB,IAAY,EACZ,GAAW,EACX,MAA2B,EAC3B,EAAE;IACF,MAAM,OAAO,GAAG,IAAA,cAAO,EAAC,GAAG,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC,CAAA;IAClD,IAAA,kBAAU,EAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IACzB,OAAO,MAAM,CAAC,OAAO,CAAC,CAAA;AACxB,CAAC,CAAA","sourcesContent":["// https://youtu.be/uhRWMGBjlO8?t=537\n//\n// 1. readdir\n// 2. for each entry\n// a. if a non-empty directory, recurse\n// b. if an empty directory, move to random hidden file name in $TEMP\n// c. unlink/rmdir $TEMP\n//\n// This works around the fact that unlink/rmdir is non-atomic and takes\n// a non-deterministic amount of time to complete.\n//\n// However, it is HELLA SLOW, like 2-10x slower than a naive recursive rm.\n\nimport { basename, parse, resolve } from 'path'\nimport { defaultTmp, defaultTmpSync } from './default-tmp.js'\n\nimport { ignoreENOENT, ignoreENOENTSync } from './ignore-enoent.js'\n\nimport {\n chmodSync,\n lstatSync,\n promises as fsPromises,\n renameSync,\n rmdirSync,\n unlinkSync,\n} from './fs.js'\nconst { lstat, rename, unlink, rmdir, chmod } = fsPromises\n\nimport { Dirent, Stats } from 'fs'\nimport { RimrafAsyncOptions, RimrafSyncOptions } from './index.js'\nimport { readdirOrError, readdirOrErrorSync } from './readdir-or-error.js'\n\n// crypto.randomBytes is much slower, and Math.random() is enough here\nconst uniqueFilename = (path: string) => `.${basename(path)}.${Math.random()}`\n\nconst unlinkFixEPERM = async (path: string) =>\n unlink(path).catch((er: Error & { code?: string }) => {\n if (er.code === 'EPERM') {\n return chmod(path, 0o666).then(\n () => unlink(path),\n er2 => {\n if (er2.code === 'ENOENT') {\n return\n }\n throw er\n },\n )\n } else if (er.code === 'ENOENT') {\n return\n }\n throw er\n })\n\nconst unlinkFixEPERMSync = (path: string) => {\n try {\n unlinkSync(path)\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'EPERM') {\n try {\n return chmodSync(path, 0o666)\n } catch (er2) {\n if ((er2 as NodeJS.ErrnoException)?.code === 'ENOENT') {\n return\n }\n throw er\n }\n } else if ((er as NodeJS.ErrnoException)?.code === 'ENOENT') {\n return\n }\n throw er\n }\n}\n\nexport const rimrafMoveRemove = async (\n path: string,\n opt: RimrafAsyncOptions,\n) => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n try {\n return await rimrafMoveRemoveDir(path, opt, await lstat(path))\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'ENOENT') return true\n throw er\n }\n}\n\nconst rimrafMoveRemoveDir = async (\n path: string,\n opt: RimrafAsyncOptions,\n ent: Dirent | Stats,\n): Promise => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n if (!opt.tmp) {\n return rimrafMoveRemoveDir(\n path,\n { ...opt, tmp: await defaultTmp(path) },\n ent,\n )\n }\n if (path === opt.tmp && parse(path).root !== path) {\n throw new Error('cannot delete temp directory used for deletion')\n }\n\n const entries = ent.isDirectory() ? await readdirOrError(path) : null\n if (!Array.isArray(entries)) {\n // this can only happen if lstat/readdir lied, or if the dir was\n // swapped out with a file at just the right moment.\n /* c8 ignore start */\n if (entries) {\n if (entries.code === 'ENOENT') {\n return true\n }\n if (entries.code !== 'ENOTDIR') {\n throw entries\n }\n }\n /* c8 ignore stop */\n if (opt.filter && !(await opt.filter(path, ent))) {\n return false\n }\n await ignoreENOENT(tmpUnlink(path, opt.tmp, unlinkFixEPERM))\n return true\n }\n\n const removedAll = (\n await Promise.all(\n entries.map(ent =>\n rimrafMoveRemoveDir(resolve(path, ent.name), opt, ent),\n ),\n )\n ).reduce((a, b) => a && b, true)\n if (!removedAll) {\n return false\n }\n\n // we don't ever ACTUALLY try to unlink /, because that can never work\n // but when preserveRoot is false, we could be operating on it.\n // No need to check if preserveRoot is not false.\n if (opt.preserveRoot === false && path === parse(path).root) {\n return false\n }\n if (opt.filter && !(await opt.filter(path, ent))) {\n return false\n }\n await ignoreENOENT(tmpUnlink(path, opt.tmp, rmdir))\n return true\n}\n\nconst tmpUnlink = async (\n path: string,\n tmp: string,\n rm: (p: string) => Promise,\n) => {\n const tmpFile = resolve(tmp, uniqueFilename(path))\n await rename(path, tmpFile)\n return await rm(tmpFile)\n}\n\nexport const rimrafMoveRemoveSync = (path: string, opt: RimrafSyncOptions) => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n try {\n return rimrafMoveRemoveDirSync(path, opt, lstatSync(path))\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'ENOENT') return true\n throw er\n }\n}\n\nconst rimrafMoveRemoveDirSync = (\n path: string,\n opt: RimrafSyncOptions,\n ent: Dirent | Stats,\n): boolean => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n if (!opt.tmp) {\n return rimrafMoveRemoveDirSync(\n path,\n { ...opt, tmp: defaultTmpSync(path) },\n ent,\n )\n }\n const tmp: string = opt.tmp\n\n if (path === opt.tmp && parse(path).root !== path) {\n throw new Error('cannot delete temp directory used for deletion')\n }\n\n const entries = ent.isDirectory() ? readdirOrErrorSync(path) : null\n if (!Array.isArray(entries)) {\n // this can only happen if lstat/readdir lied, or if the dir was\n // swapped out with a file at just the right moment.\n /* c8 ignore start */\n if (entries) {\n if (entries.code === 'ENOENT') {\n return true\n }\n if (entries.code !== 'ENOTDIR') {\n throw entries\n }\n }\n /* c8 ignore stop */\n if (opt.filter && !opt.filter(path, ent)) {\n return false\n }\n ignoreENOENTSync(() => tmpUnlinkSync(path, tmp, unlinkFixEPERMSync))\n return true\n }\n\n let removedAll = true\n for (const ent of entries) {\n const p = resolve(path, ent.name)\n removedAll = rimrafMoveRemoveDirSync(p, opt, ent) && removedAll\n }\n if (!removedAll) {\n return false\n }\n if (opt.preserveRoot === false && path === parse(path).root) {\n return false\n }\n if (opt.filter && !opt.filter(path, ent)) {\n return false\n }\n ignoreENOENTSync(() => tmpUnlinkSync(path, tmp, rmdirSync))\n return true\n}\n\nconst tmpUnlinkSync = (\n path: string,\n tmp: string,\n rmSync: (p: string) => void,\n) => {\n const tmpFile = resolve(tmp, uniqueFilename(path))\n renameSync(path, tmpFile)\n return rmSync(tmpFile)\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-native.d.ts b/node_modules/rimraf/dist/commonjs/rimraf-native.d.ts new file mode 100644 index 0000000..cc84bf7 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-native.d.ts @@ -0,0 +1,4 @@ +import { RimrafAsyncOptions, RimrafSyncOptions } from './index.js'; +export declare const rimrafNative: (path: string, opt: RimrafAsyncOptions) => Promise; +export declare const rimrafNativeSync: (path: string, opt: RimrafSyncOptions) => boolean; +//# sourceMappingURL=rimraf-native.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-native.d.ts.map b/node_modules/rimraf/dist/commonjs/rimraf-native.d.ts.map new file mode 100644 index 0000000..bea6b79 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-native.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-native.d.ts","sourceRoot":"","sources":["../../src/rimraf-native.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAIlE,eAAO,MAAM,YAAY,SACjB,MAAM,OACP,kBAAkB,KACtB,OAAO,CAAC,OAAO,CAOjB,CAAA;AAED,eAAO,MAAM,gBAAgB,SACrB,MAAM,OACP,iBAAiB,KACrB,OAOF,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-native.js b/node_modules/rimraf/dist/commonjs/rimraf-native.js new file mode 100644 index 0000000..ab9f633 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-native.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.rimrafNativeSync = exports.rimrafNative = void 0; +const fs_js_1 = require("./fs.js"); +const { rm } = fs_js_1.promises; +const rimrafNative = async (path, opt) => { + await rm(path, { + ...opt, + force: true, + recursive: true, + }); + return true; +}; +exports.rimrafNative = rimrafNative; +const rimrafNativeSync = (path, opt) => { + (0, fs_js_1.rmSync)(path, { + ...opt, + force: true, + recursive: true, + }); + return true; +}; +exports.rimrafNativeSync = rimrafNativeSync; +//# sourceMappingURL=rimraf-native.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-native.js.map b/node_modules/rimraf/dist/commonjs/rimraf-native.js.map new file mode 100644 index 0000000..6eddd44 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-native.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-native.js","sourceRoot":"","sources":["../../src/rimraf-native.ts"],"names":[],"mappings":";;;AACA,mCAA0C;AAC1C,MAAM,EAAE,EAAE,EAAE,GAAG,gBAAQ,CAAA;AAEhB,MAAM,YAAY,GAAG,KAAK,EAC/B,IAAY,EACZ,GAAuB,EACL,EAAE;IACpB,MAAM,EAAE,CAAC,IAAI,EAAE;QACb,GAAG,GAAG;QACN,KAAK,EAAE,IAAI;QACX,SAAS,EAAE,IAAI;KAChB,CAAC,CAAA;IACF,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAVY,QAAA,YAAY,gBAUxB;AAEM,MAAM,gBAAgB,GAAG,CAC9B,IAAY,EACZ,GAAsB,EACb,EAAE;IACX,IAAA,cAAM,EAAC,IAAI,EAAE;QACX,GAAG,GAAG;QACN,KAAK,EAAE,IAAI;QACX,SAAS,EAAE,IAAI;KAChB,CAAC,CAAA;IACF,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAVY,QAAA,gBAAgB,oBAU5B","sourcesContent":["import { RimrafAsyncOptions, RimrafSyncOptions } from './index.js'\nimport { promises, rmSync } from './fs.js'\nconst { rm } = promises\n\nexport const rimrafNative = async (\n path: string,\n opt: RimrafAsyncOptions,\n): Promise => {\n await rm(path, {\n ...opt,\n force: true,\n recursive: true,\n })\n return true\n}\n\nexport const rimrafNativeSync = (\n path: string,\n opt: RimrafSyncOptions,\n): boolean => {\n rmSync(path, {\n ...opt,\n force: true,\n recursive: true,\n })\n return true\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-posix.d.ts b/node_modules/rimraf/dist/commonjs/rimraf-posix.d.ts new file mode 100644 index 0000000..8e532ef --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-posix.d.ts @@ -0,0 +1,4 @@ +import { RimrafAsyncOptions, RimrafSyncOptions } from './index.js'; +export declare const rimrafPosix: (path: string, opt: RimrafAsyncOptions) => Promise; +export declare const rimrafPosixSync: (path: string, opt: RimrafSyncOptions) => boolean; +//# sourceMappingURL=rimraf-posix.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-posix.d.ts.map b/node_modules/rimraf/dist/commonjs/rimraf-posix.d.ts.map new file mode 100644 index 0000000..3f9b808 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-posix.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-posix.d.ts","sourceRoot":"","sources":["../../src/rimraf-posix.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAGlE,eAAO,MAAM,WAAW,SAAgB,MAAM,OAAO,kBAAkB,qBAUtE,CAAA;AAED,eAAO,MAAM,eAAe,SAAU,MAAM,OAAO,iBAAiB,YAUnE,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-posix.js b/node_modules/rimraf/dist/commonjs/rimraf-posix.js new file mode 100644 index 0000000..eb0e7f1 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-posix.js @@ -0,0 +1,123 @@ +"use strict"; +// the simple recursive removal, where unlink and rmdir are atomic +// Note that this approach does NOT work on Windows! +// We stat first and only unlink if the Dirent isn't a directory, +// because sunos will let root unlink a directory, and some +// SUPER weird breakage happens as a result. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.rimrafPosixSync = exports.rimrafPosix = void 0; +const fs_js_1 = require("./fs.js"); +const { lstat, rmdir, unlink } = fs_js_1.promises; +const path_1 = require("path"); +const readdir_or_error_js_1 = require("./readdir-or-error.js"); +const ignore_enoent_js_1 = require("./ignore-enoent.js"); +const rimrafPosix = async (path, opt) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + try { + return await rimrafPosixDir(path, opt, await lstat(path)); + } + catch (er) { + if (er?.code === 'ENOENT') + return true; + throw er; + } +}; +exports.rimrafPosix = rimrafPosix; +const rimrafPosixSync = (path, opt) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + try { + return rimrafPosixDirSync(path, opt, (0, fs_js_1.lstatSync)(path)); + } + catch (er) { + if (er?.code === 'ENOENT') + return true; + throw er; + } +}; +exports.rimrafPosixSync = rimrafPosixSync; +const rimrafPosixDir = async (path, opt, ent) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + const entries = ent.isDirectory() ? await (0, readdir_or_error_js_1.readdirOrError)(path) : null; + if (!Array.isArray(entries)) { + // this can only happen if lstat/readdir lied, or if the dir was + // swapped out with a file at just the right moment. + /* c8 ignore start */ + if (entries) { + if (entries.code === 'ENOENT') { + return true; + } + if (entries.code !== 'ENOTDIR') { + throw entries; + } + } + /* c8 ignore stop */ + if (opt.filter && !(await opt.filter(path, ent))) { + return false; + } + await (0, ignore_enoent_js_1.ignoreENOENT)(unlink(path)); + return true; + } + const removedAll = (await Promise.all(entries.map(ent => rimrafPosixDir((0, path_1.resolve)(path, ent.name), opt, ent)))).reduce((a, b) => a && b, true); + if (!removedAll) { + return false; + } + // we don't ever ACTUALLY try to unlink /, because that can never work + // but when preserveRoot is false, we could be operating on it. + // No need to check if preserveRoot is not false. + if (opt.preserveRoot === false && path === (0, path_1.parse)(path).root) { + return false; + } + if (opt.filter && !(await opt.filter(path, ent))) { + return false; + } + await (0, ignore_enoent_js_1.ignoreENOENT)(rmdir(path)); + return true; +}; +const rimrafPosixDirSync = (path, opt, ent) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + const entries = ent.isDirectory() ? (0, readdir_or_error_js_1.readdirOrErrorSync)(path) : null; + if (!Array.isArray(entries)) { + // this can only happen if lstat/readdir lied, or if the dir was + // swapped out with a file at just the right moment. + /* c8 ignore start */ + if (entries) { + if (entries.code === 'ENOENT') { + return true; + } + if (entries.code !== 'ENOTDIR') { + throw entries; + } + } + /* c8 ignore stop */ + if (opt.filter && !opt.filter(path, ent)) { + return false; + } + (0, ignore_enoent_js_1.ignoreENOENTSync)(() => (0, fs_js_1.unlinkSync)(path)); + return true; + } + let removedAll = true; + for (const ent of entries) { + const p = (0, path_1.resolve)(path, ent.name); + removedAll = rimrafPosixDirSync(p, opt, ent) && removedAll; + } + if (opt.preserveRoot === false && path === (0, path_1.parse)(path).root) { + return false; + } + if (!removedAll) { + return false; + } + if (opt.filter && !opt.filter(path, ent)) { + return false; + } + (0, ignore_enoent_js_1.ignoreENOENTSync)(() => (0, fs_js_1.rmdirSync)(path)); + return true; +}; +//# sourceMappingURL=rimraf-posix.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-posix.js.map b/node_modules/rimraf/dist/commonjs/rimraf-posix.js.map new file mode 100644 index 0000000..32a366a --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-posix.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-posix.js","sourceRoot":"","sources":["../../src/rimraf-posix.ts"],"names":[],"mappings":";AAAA,kEAAkE;AAClE,oDAAoD;AACpD,iEAAiE;AACjE,2DAA2D;AAC3D,4CAA4C;;;AAE5C,mCAAoE;AACpE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,gBAAQ,CAAA;AAEzC,+BAAqC;AAErC,+DAA0E;AAI1E,yDAAmE;AAE5D,MAAM,WAAW,GAAG,KAAK,EAAE,IAAY,EAAE,GAAuB,EAAE,EAAE;IACzE,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,IAAI,CAAC;QACH,OAAO,MAAM,cAAc,CAAC,IAAI,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC,IAAI,CAAC,CAAC,CAAA;IAC3D,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,IAAK,EAA4B,EAAE,IAAI,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAA;QACjE,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAVY,QAAA,WAAW,eAUvB;AAEM,MAAM,eAAe,GAAG,CAAC,IAAY,EAAE,GAAsB,EAAE,EAAE;IACtE,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,IAAI,CAAC;QACH,OAAO,kBAAkB,CAAC,IAAI,EAAE,GAAG,EAAE,IAAA,iBAAS,EAAC,IAAI,CAAC,CAAC,CAAA;IACvD,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,IAAK,EAA4B,EAAE,IAAI,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAA;QACjE,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAVY,QAAA,eAAe,mBAU3B;AAED,MAAM,cAAc,GAAG,KAAK,EAC1B,IAAY,EACZ,GAAuB,EACvB,GAAmB,EACD,EAAE;IACpB,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,MAAM,OAAO,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,MAAM,IAAA,oCAAc,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACrE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,gEAAgE;QAChE,oDAAoD;QACpD,qBAAqB;QACrB,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC9B,OAAO,IAAI,CAAA;YACb,CAAC;YACD,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;gBAC/B,MAAM,OAAO,CAAA;YACf,CAAC;QACH,CAAC;QACD,oBAAoB;QACpB,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC;YACjD,OAAO,KAAK,CAAA;QACd,CAAC;QACD,MAAM,IAAA,+BAAY,EAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAA;QAChC,OAAO,IAAI,CAAA;IACb,CAAC;IAED,MAAM,UAAU,GAAG,CACjB,MAAM,OAAO,CAAC,GAAG,CACf,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,cAAc,CAAC,IAAA,cAAO,EAAC,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CACtE,CACF,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAA;IAEhC,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,KAAK,CAAA;IACd,CAAC;IAED,sEAAsE;IACtE,+DAA+D;IAC/D,iDAAiD;IACjD,IAAI,GAAG,CAAC,YAAY,KAAK,KAAK,IAAI,IAAI,KAAK,IAAA,YAAK,EAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;QAC5D,OAAO,KAAK,CAAA;IACd,CAAC;IAED,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC;QACjD,OAAO,KAAK,CAAA;IACd,CAAC;IAED,MAAM,IAAA,+BAAY,EAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAA;IAC/B,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,MAAM,kBAAkB,GAAG,CACzB,IAAY,EACZ,GAAsB,EACtB,GAAmB,EACV,EAAE;IACX,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,MAAM,OAAO,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,IAAA,wCAAkB,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACnE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,gEAAgE;QAChE,oDAAoD;QACpD,qBAAqB;QACrB,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC9B,OAAO,IAAI,CAAA;YACb,CAAC;YACD,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;gBAC/B,MAAM,OAAO,CAAA;YACf,CAAC;QACH,CAAC;QACD,oBAAoB;QACpB,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzC,OAAO,KAAK,CAAA;QACd,CAAC;QACD,IAAA,mCAAgB,EAAC,GAAG,EAAE,CAAC,IAAA,kBAAU,EAAC,IAAI,CAAC,CAAC,CAAA;QACxC,OAAO,IAAI,CAAA;IACb,CAAC;IACD,IAAI,UAAU,GAAY,IAAI,CAAA;IAC9B,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE,CAAC;QAC1B,MAAM,CAAC,GAAG,IAAA,cAAO,EAAC,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,CAAA;QACjC,UAAU,GAAG,kBAAkB,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,IAAI,UAAU,CAAA;IAC5D,CAAC;IACD,IAAI,GAAG,CAAC,YAAY,KAAK,KAAK,IAAI,IAAI,KAAK,IAAA,YAAK,EAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;QAC5D,OAAO,KAAK,CAAA;IACd,CAAC;IAED,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,KAAK,CAAA;IACd,CAAC;IAED,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;QACzC,OAAO,KAAK,CAAA;IACd,CAAC;IAED,IAAA,mCAAgB,EAAC,GAAG,EAAE,CAAC,IAAA,iBAAS,EAAC,IAAI,CAAC,CAAC,CAAA;IACvC,OAAO,IAAI,CAAA;AACb,CAAC,CAAA","sourcesContent":["// the simple recursive removal, where unlink and rmdir are atomic\n// Note that this approach does NOT work on Windows!\n// We stat first and only unlink if the Dirent isn't a directory,\n// because sunos will let root unlink a directory, and some\n// SUPER weird breakage happens as a result.\n\nimport { lstatSync, promises, rmdirSync, unlinkSync } from './fs.js'\nconst { lstat, rmdir, unlink } = promises\n\nimport { parse, resolve } from 'path'\n\nimport { readdirOrError, readdirOrErrorSync } from './readdir-or-error.js'\n\nimport { Dirent, Stats } from 'fs'\nimport { RimrafAsyncOptions, RimrafSyncOptions } from './index.js'\nimport { ignoreENOENT, ignoreENOENTSync } from './ignore-enoent.js'\n\nexport const rimrafPosix = async (path: string, opt: RimrafAsyncOptions) => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n try {\n return await rimrafPosixDir(path, opt, await lstat(path))\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'ENOENT') return true\n throw er\n }\n}\n\nexport const rimrafPosixSync = (path: string, opt: RimrafSyncOptions) => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n try {\n return rimrafPosixDirSync(path, opt, lstatSync(path))\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'ENOENT') return true\n throw er\n }\n}\n\nconst rimrafPosixDir = async (\n path: string,\n opt: RimrafAsyncOptions,\n ent: Dirent | Stats,\n): Promise => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n const entries = ent.isDirectory() ? await readdirOrError(path) : null\n if (!Array.isArray(entries)) {\n // this can only happen if lstat/readdir lied, or if the dir was\n // swapped out with a file at just the right moment.\n /* c8 ignore start */\n if (entries) {\n if (entries.code === 'ENOENT') {\n return true\n }\n if (entries.code !== 'ENOTDIR') {\n throw entries\n }\n }\n /* c8 ignore stop */\n if (opt.filter && !(await opt.filter(path, ent))) {\n return false\n }\n await ignoreENOENT(unlink(path))\n return true\n }\n\n const removedAll = (\n await Promise.all(\n entries.map(ent => rimrafPosixDir(resolve(path, ent.name), opt, ent)),\n )\n ).reduce((a, b) => a && b, true)\n\n if (!removedAll) {\n return false\n }\n\n // we don't ever ACTUALLY try to unlink /, because that can never work\n // but when preserveRoot is false, we could be operating on it.\n // No need to check if preserveRoot is not false.\n if (opt.preserveRoot === false && path === parse(path).root) {\n return false\n }\n\n if (opt.filter && !(await opt.filter(path, ent))) {\n return false\n }\n\n await ignoreENOENT(rmdir(path))\n return true\n}\n\nconst rimrafPosixDirSync = (\n path: string,\n opt: RimrafSyncOptions,\n ent: Dirent | Stats,\n): boolean => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n const entries = ent.isDirectory() ? readdirOrErrorSync(path) : null\n if (!Array.isArray(entries)) {\n // this can only happen if lstat/readdir lied, or if the dir was\n // swapped out with a file at just the right moment.\n /* c8 ignore start */\n if (entries) {\n if (entries.code === 'ENOENT') {\n return true\n }\n if (entries.code !== 'ENOTDIR') {\n throw entries\n }\n }\n /* c8 ignore stop */\n if (opt.filter && !opt.filter(path, ent)) {\n return false\n }\n ignoreENOENTSync(() => unlinkSync(path))\n return true\n }\n let removedAll: boolean = true\n for (const ent of entries) {\n const p = resolve(path, ent.name)\n removedAll = rimrafPosixDirSync(p, opt, ent) && removedAll\n }\n if (opt.preserveRoot === false && path === parse(path).root) {\n return false\n }\n\n if (!removedAll) {\n return false\n }\n\n if (opt.filter && !opt.filter(path, ent)) {\n return false\n }\n\n ignoreENOENTSync(() => rmdirSync(path))\n return true\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-windows.d.ts b/node_modules/rimraf/dist/commonjs/rimraf-windows.d.ts new file mode 100644 index 0000000..5556890 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-windows.d.ts @@ -0,0 +1,4 @@ +import { RimrafAsyncOptions, RimrafSyncOptions } from './index.js'; +export declare const rimrafWindows: (path: string, opt: RimrafAsyncOptions) => Promise; +export declare const rimrafWindowsSync: (path: string, opt: RimrafSyncOptions) => boolean; +//# sourceMappingURL=rimraf-windows.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-windows.d.ts.map b/node_modules/rimraf/dist/commonjs/rimraf-windows.d.ts.map new file mode 100644 index 0000000..56f00d9 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-windows.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-windows.d.ts","sourceRoot":"","sources":["../../src/rimraf-windows.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AA2DlE,eAAO,MAAM,aAAa,SAAgB,MAAM,OAAO,kBAAkB,qBAUxE,CAAA;AAED,eAAO,MAAM,iBAAiB,SAAU,MAAM,OAAO,iBAAiB,YAUrE,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-windows.js b/node_modules/rimraf/dist/commonjs/rimraf-windows.js new file mode 100644 index 0000000..8d19f98 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-windows.js @@ -0,0 +1,182 @@ +"use strict"; +// This is the same as rimrafPosix, with the following changes: +// +// 1. EBUSY, ENFILE, EMFILE trigger retries and/or exponential backoff +// 2. All non-directories are removed first and then all directories are +// removed in a second sweep. +// 3. If we hit ENOTEMPTY in the second sweep, fall back to move-remove on +// the that folder. +// +// Note: "move then remove" is 2-10 times slower, and just as unreliable. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.rimrafWindowsSync = exports.rimrafWindows = void 0; +const path_1 = require("path"); +const fix_eperm_js_1 = require("./fix-eperm.js"); +const fs_js_1 = require("./fs.js"); +const ignore_enoent_js_1 = require("./ignore-enoent.js"); +const readdir_or_error_js_1 = require("./readdir-or-error.js"); +const retry_busy_js_1 = require("./retry-busy.js"); +const rimraf_move_remove_js_1 = require("./rimraf-move-remove.js"); +const { unlink, rmdir, lstat } = fs_js_1.promises; +const rimrafWindowsFile = (0, retry_busy_js_1.retryBusy)((0, fix_eperm_js_1.fixEPERM)(unlink)); +const rimrafWindowsFileSync = (0, retry_busy_js_1.retryBusySync)((0, fix_eperm_js_1.fixEPERMSync)(fs_js_1.unlinkSync)); +const rimrafWindowsDirRetry = (0, retry_busy_js_1.retryBusy)((0, fix_eperm_js_1.fixEPERM)(rmdir)); +const rimrafWindowsDirRetrySync = (0, retry_busy_js_1.retryBusySync)((0, fix_eperm_js_1.fixEPERMSync)(fs_js_1.rmdirSync)); +const rimrafWindowsDirMoveRemoveFallback = async (path, opt) => { + /* c8 ignore start */ + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + /* c8 ignore stop */ + // already filtered, remove from options so we don't call unnecessarily + const { filter, ...options } = opt; + try { + return await rimrafWindowsDirRetry(path, options); + } + catch (er) { + if (er?.code === 'ENOTEMPTY') { + return await (0, rimraf_move_remove_js_1.rimrafMoveRemove)(path, options); + } + throw er; + } +}; +const rimrafWindowsDirMoveRemoveFallbackSync = (path, opt) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + // already filtered, remove from options so we don't call unnecessarily + const { filter, ...options } = opt; + try { + return rimrafWindowsDirRetrySync(path, options); + } + catch (er) { + const fer = er; + if (fer?.code === 'ENOTEMPTY') { + return (0, rimraf_move_remove_js_1.rimrafMoveRemoveSync)(path, options); + } + throw er; + } +}; +const START = Symbol('start'); +const CHILD = Symbol('child'); +const FINISH = Symbol('finish'); +const rimrafWindows = async (path, opt) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + try { + return await rimrafWindowsDir(path, opt, await lstat(path), START); + } + catch (er) { + if (er?.code === 'ENOENT') + return true; + throw er; + } +}; +exports.rimrafWindows = rimrafWindows; +const rimrafWindowsSync = (path, opt) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + try { + return rimrafWindowsDirSync(path, opt, (0, fs_js_1.lstatSync)(path), START); + } + catch (er) { + if (er?.code === 'ENOENT') + return true; + throw er; + } +}; +exports.rimrafWindowsSync = rimrafWindowsSync; +const rimrafWindowsDir = async (path, opt, ent, state = START) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + const entries = ent.isDirectory() ? await (0, readdir_or_error_js_1.readdirOrError)(path) : null; + if (!Array.isArray(entries)) { + // this can only happen if lstat/readdir lied, or if the dir was + // swapped out with a file at just the right moment. + /* c8 ignore start */ + if (entries) { + if (entries.code === 'ENOENT') { + return true; + } + if (entries.code !== 'ENOTDIR') { + throw entries; + } + } + /* c8 ignore stop */ + if (opt.filter && !(await opt.filter(path, ent))) { + return false; + } + // is a file + await (0, ignore_enoent_js_1.ignoreENOENT)(rimrafWindowsFile(path, opt)); + return true; + } + const s = state === START ? CHILD : state; + const removedAll = (await Promise.all(entries.map(ent => rimrafWindowsDir((0, path_1.resolve)(path, ent.name), opt, ent, s)))).reduce((a, b) => a && b, true); + if (state === START) { + return rimrafWindowsDir(path, opt, ent, FINISH); + } + else if (state === FINISH) { + if (opt.preserveRoot === false && path === (0, path_1.parse)(path).root) { + return false; + } + if (!removedAll) { + return false; + } + if (opt.filter && !(await opt.filter(path, ent))) { + return false; + } + await (0, ignore_enoent_js_1.ignoreENOENT)(rimrafWindowsDirMoveRemoveFallback(path, opt)); + } + return true; +}; +const rimrafWindowsDirSync = (path, opt, ent, state = START) => { + const entries = ent.isDirectory() ? (0, readdir_or_error_js_1.readdirOrErrorSync)(path) : null; + if (!Array.isArray(entries)) { + // this can only happen if lstat/readdir lied, or if the dir was + // swapped out with a file at just the right moment. + /* c8 ignore start */ + if (entries) { + if (entries.code === 'ENOENT') { + return true; + } + if (entries.code !== 'ENOTDIR') { + throw entries; + } + } + /* c8 ignore stop */ + if (opt.filter && !opt.filter(path, ent)) { + return false; + } + // is a file + (0, ignore_enoent_js_1.ignoreENOENTSync)(() => rimrafWindowsFileSync(path, opt)); + return true; + } + let removedAll = true; + for (const ent of entries) { + const s = state === START ? CHILD : state; + const p = (0, path_1.resolve)(path, ent.name); + removedAll = rimrafWindowsDirSync(p, opt, ent, s) && removedAll; + } + if (state === START) { + return rimrafWindowsDirSync(path, opt, ent, FINISH); + } + else if (state === FINISH) { + if (opt.preserveRoot === false && path === (0, path_1.parse)(path).root) { + return false; + } + if (!removedAll) { + return false; + } + if (opt.filter && !opt.filter(path, ent)) { + return false; + } + (0, ignore_enoent_js_1.ignoreENOENTSync)(() => { + rimrafWindowsDirMoveRemoveFallbackSync(path, opt); + }); + } + return true; +}; +//# sourceMappingURL=rimraf-windows.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/rimraf-windows.js.map b/node_modules/rimraf/dist/commonjs/rimraf-windows.js.map new file mode 100644 index 0000000..50a97f8 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/rimraf-windows.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-windows.js","sourceRoot":"","sources":["../../src/rimraf-windows.ts"],"names":[],"mappings":";AAAA,+DAA+D;AAC/D,EAAE;AACF,sEAAsE;AACtE,wEAAwE;AACxE,gCAAgC;AAChC,0EAA0E;AAC1E,sBAAsB;AACtB,EAAE;AACF,yEAAyE;;;AAGzE,+BAAqC;AAErC,iDAAuD;AACvD,mCAAoE;AACpE,yDAAmE;AACnE,+DAA0E;AAC1E,mDAA0D;AAC1D,mEAAgF;AAChF,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,gBAAQ,CAAA;AAEzC,MAAM,iBAAiB,GAAG,IAAA,yBAAS,EAAC,IAAA,uBAAQ,EAAC,MAAM,CAAC,CAAC,CAAA;AACrD,MAAM,qBAAqB,GAAG,IAAA,6BAAa,EAAC,IAAA,2BAAY,EAAC,kBAAU,CAAC,CAAC,CAAA;AACrE,MAAM,qBAAqB,GAAG,IAAA,yBAAS,EAAC,IAAA,uBAAQ,EAAC,KAAK,CAAC,CAAC,CAAA;AACxD,MAAM,yBAAyB,GAAG,IAAA,6BAAa,EAAC,IAAA,2BAAY,EAAC,iBAAS,CAAC,CAAC,CAAA;AAExE,MAAM,kCAAkC,GAAG,KAAK,EAC9C,IAAY,EACZ,GAAuB,EACL,EAAE;IACpB,qBAAqB;IACrB,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,oBAAoB;IACpB,uEAAuE;IACvE,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,EAAE,GAAG,GAAG,CAAA;IAClC,IAAI,CAAC;QACH,OAAO,MAAM,qBAAqB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IACnD,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,IAAK,EAA4B,EAAE,IAAI,KAAK,WAAW,EAAE,CAAC;YACxD,OAAO,MAAM,IAAA,wCAAgB,EAAC,IAAI,EAAE,OAAO,CAAC,CAAA;QAC9C,CAAC;QACD,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAED,MAAM,sCAAsC,GAAG,CAC7C,IAAY,EACZ,GAAsB,EACb,EAAE;IACX,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,uEAAuE;IACvE,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,EAAE,GAAG,GAAG,CAAA;IAClC,IAAI,CAAC;QACH,OAAO,yBAAyB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IACjD,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,EAAE,IAAI,KAAK,WAAW,EAAE,CAAC;YAC9B,OAAO,IAAA,4CAAoB,EAAC,IAAI,EAAE,OAAO,CAAC,CAAA;QAC5C,CAAC;QACD,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAED,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,CAAA;AAC7B,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,CAAA;AAC7B,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAA;AAExB,MAAM,aAAa,GAAG,KAAK,EAAE,IAAY,EAAE,GAAuB,EAAE,EAAE;IAC3E,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,IAAI,CAAC;QACH,OAAO,MAAM,gBAAgB,CAAC,IAAI,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,CAAA;IACpE,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,IAAK,EAA4B,EAAE,IAAI,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAA;QACjE,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAVY,QAAA,aAAa,iBAUzB;AAEM,MAAM,iBAAiB,GAAG,CAAC,IAAY,EAAE,GAAsB,EAAE,EAAE;IACxE,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,IAAI,CAAC;QACH,OAAO,oBAAoB,CAAC,IAAI,EAAE,GAAG,EAAE,IAAA,iBAAS,EAAC,IAAI,CAAC,EAAE,KAAK,CAAC,CAAA;IAChE,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,IAAK,EAA4B,EAAE,IAAI,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAA;QACjE,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAVY,QAAA,iBAAiB,qBAU7B;AAED,MAAM,gBAAgB,GAAG,KAAK,EAC5B,IAAY,EACZ,GAAuB,EACvB,GAAmB,EACnB,KAAK,GAAG,KAAK,EACK,EAAE;IACpB,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IAED,MAAM,OAAO,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,MAAM,IAAA,oCAAc,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACrE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,gEAAgE;QAChE,oDAAoD;QACpD,qBAAqB;QACrB,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC9B,OAAO,IAAI,CAAA;YACb,CAAC;YACD,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;gBAC/B,MAAM,OAAO,CAAA;YACf,CAAC;QACH,CAAC;QACD,oBAAoB;QACpB,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC;YACjD,OAAO,KAAK,CAAA;QACd,CAAC;QACD,YAAY;QACZ,MAAM,IAAA,+BAAY,EAAC,iBAAiB,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAA;QAChD,OAAO,IAAI,CAAA;IACb,CAAC;IAED,MAAM,CAAC,GAAG,KAAK,KAAK,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAA;IACzC,MAAM,UAAU,GAAG,CACjB,MAAM,OAAO,CAAC,GAAG,CACf,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAChB,gBAAgB,CAAC,IAAA,cAAO,EAAC,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,CACvD,CACF,CACF,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAA;IAEhC,IAAI,KAAK,KAAK,KAAK,EAAE,CAAC;QACpB,OAAO,gBAAgB,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,CAAC,CAAA;IACjD,CAAC;SAAM,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC;QAC5B,IAAI,GAAG,CAAC,YAAY,KAAK,KAAK,IAAI,IAAI,KAAK,IAAA,YAAK,EAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;YAC5D,OAAO,KAAK,CAAA;QACd,CAAC;QACD,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,OAAO,KAAK,CAAA;QACd,CAAC;QACD,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC;YACjD,OAAO,KAAK,CAAA;QACd,CAAC;QACD,MAAM,IAAA,+BAAY,EAAC,kCAAkC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAA;IACnE,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,MAAM,oBAAoB,GAAG,CAC3B,IAAY,EACZ,GAAsB,EACtB,GAAmB,EACnB,KAAK,GAAG,KAAK,EACJ,EAAE;IACX,MAAM,OAAO,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,IAAA,wCAAkB,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACnE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,gEAAgE;QAChE,oDAAoD;QACpD,qBAAqB;QACrB,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC9B,OAAO,IAAI,CAAA;YACb,CAAC;YACD,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;gBAC/B,MAAM,OAAO,CAAA;YACf,CAAC;QACH,CAAC;QACD,oBAAoB;QACpB,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzC,OAAO,KAAK,CAAA;QACd,CAAC;QACD,YAAY;QACZ,IAAA,mCAAgB,EAAC,GAAG,EAAE,CAAC,qBAAqB,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAA;QACxD,OAAO,IAAI,CAAA;IACb,CAAC;IAED,IAAI,UAAU,GAAG,IAAI,CAAA;IACrB,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE,CAAC;QAC1B,MAAM,CAAC,GAAG,KAAK,KAAK,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAA;QACzC,MAAM,CAAC,GAAG,IAAA,cAAO,EAAC,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,CAAA;QACjC,UAAU,GAAG,oBAAoB,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,IAAI,UAAU,CAAA;IACjE,CAAC;IAED,IAAI,KAAK,KAAK,KAAK,EAAE,CAAC;QACpB,OAAO,oBAAoB,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,CAAC,CAAA;IACrD,CAAC;SAAM,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC;QAC5B,IAAI,GAAG,CAAC,YAAY,KAAK,KAAK,IAAI,IAAI,KAAK,IAAA,YAAK,EAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;YAC5D,OAAO,KAAK,CAAA;QACd,CAAC;QACD,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,OAAO,KAAK,CAAA;QACd,CAAC;QACD,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzC,OAAO,KAAK,CAAA;QACd,CAAC;QACD,IAAA,mCAAgB,EAAC,GAAG,EAAE;YACpB,sCAAsC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;QACnD,CAAC,CAAC,CAAA;IACJ,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC,CAAA","sourcesContent":["// This is the same as rimrafPosix, with the following changes:\n//\n// 1. EBUSY, ENFILE, EMFILE trigger retries and/or exponential backoff\n// 2. All non-directories are removed first and then all directories are\n// removed in a second sweep.\n// 3. If we hit ENOTEMPTY in the second sweep, fall back to move-remove on\n// the that folder.\n//\n// Note: \"move then remove\" is 2-10 times slower, and just as unreliable.\n\nimport { Dirent, Stats } from 'fs'\nimport { parse, resolve } from 'path'\nimport { RimrafAsyncOptions, RimrafSyncOptions } from './index.js'\nimport { fixEPERM, fixEPERMSync } from './fix-eperm.js'\nimport { lstatSync, promises, rmdirSync, unlinkSync } from './fs.js'\nimport { ignoreENOENT, ignoreENOENTSync } from './ignore-enoent.js'\nimport { readdirOrError, readdirOrErrorSync } from './readdir-or-error.js'\nimport { retryBusy, retryBusySync } from './retry-busy.js'\nimport { rimrafMoveRemove, rimrafMoveRemoveSync } from './rimraf-move-remove.js'\nconst { unlink, rmdir, lstat } = promises\n\nconst rimrafWindowsFile = retryBusy(fixEPERM(unlink))\nconst rimrafWindowsFileSync = retryBusySync(fixEPERMSync(unlinkSync))\nconst rimrafWindowsDirRetry = retryBusy(fixEPERM(rmdir))\nconst rimrafWindowsDirRetrySync = retryBusySync(fixEPERMSync(rmdirSync))\n\nconst rimrafWindowsDirMoveRemoveFallback = async (\n path: string,\n opt: RimrafAsyncOptions,\n): Promise => {\n /* c8 ignore start */\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n /* c8 ignore stop */\n // already filtered, remove from options so we don't call unnecessarily\n const { filter, ...options } = opt\n try {\n return await rimrafWindowsDirRetry(path, options)\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'ENOTEMPTY') {\n return await rimrafMoveRemove(path, options)\n }\n throw er\n }\n}\n\nconst rimrafWindowsDirMoveRemoveFallbackSync = (\n path: string,\n opt: RimrafSyncOptions,\n): boolean => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n // already filtered, remove from options so we don't call unnecessarily\n const { filter, ...options } = opt\n try {\n return rimrafWindowsDirRetrySync(path, options)\n } catch (er) {\n const fer = er as NodeJS.ErrnoException\n if (fer?.code === 'ENOTEMPTY') {\n return rimrafMoveRemoveSync(path, options)\n }\n throw er\n }\n}\n\nconst START = Symbol('start')\nconst CHILD = Symbol('child')\nconst FINISH = Symbol('finish')\n\nexport const rimrafWindows = async (path: string, opt: RimrafAsyncOptions) => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n try {\n return await rimrafWindowsDir(path, opt, await lstat(path), START)\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'ENOENT') return true\n throw er\n }\n}\n\nexport const rimrafWindowsSync = (path: string, opt: RimrafSyncOptions) => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n try {\n return rimrafWindowsDirSync(path, opt, lstatSync(path), START)\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'ENOENT') return true\n throw er\n }\n}\n\nconst rimrafWindowsDir = async (\n path: string,\n opt: RimrafAsyncOptions,\n ent: Dirent | Stats,\n state = START,\n): Promise => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n\n const entries = ent.isDirectory() ? await readdirOrError(path) : null\n if (!Array.isArray(entries)) {\n // this can only happen if lstat/readdir lied, or if the dir was\n // swapped out with a file at just the right moment.\n /* c8 ignore start */\n if (entries) {\n if (entries.code === 'ENOENT') {\n return true\n }\n if (entries.code !== 'ENOTDIR') {\n throw entries\n }\n }\n /* c8 ignore stop */\n if (opt.filter && !(await opt.filter(path, ent))) {\n return false\n }\n // is a file\n await ignoreENOENT(rimrafWindowsFile(path, opt))\n return true\n }\n\n const s = state === START ? CHILD : state\n const removedAll = (\n await Promise.all(\n entries.map(ent =>\n rimrafWindowsDir(resolve(path, ent.name), opt, ent, s),\n ),\n )\n ).reduce((a, b) => a && b, true)\n\n if (state === START) {\n return rimrafWindowsDir(path, opt, ent, FINISH)\n } else if (state === FINISH) {\n if (opt.preserveRoot === false && path === parse(path).root) {\n return false\n }\n if (!removedAll) {\n return false\n }\n if (opt.filter && !(await opt.filter(path, ent))) {\n return false\n }\n await ignoreENOENT(rimrafWindowsDirMoveRemoveFallback(path, opt))\n }\n return true\n}\n\nconst rimrafWindowsDirSync = (\n path: string,\n opt: RimrafSyncOptions,\n ent: Dirent | Stats,\n state = START,\n): boolean => {\n const entries = ent.isDirectory() ? readdirOrErrorSync(path) : null\n if (!Array.isArray(entries)) {\n // this can only happen if lstat/readdir lied, or if the dir was\n // swapped out with a file at just the right moment.\n /* c8 ignore start */\n if (entries) {\n if (entries.code === 'ENOENT') {\n return true\n }\n if (entries.code !== 'ENOTDIR') {\n throw entries\n }\n }\n /* c8 ignore stop */\n if (opt.filter && !opt.filter(path, ent)) {\n return false\n }\n // is a file\n ignoreENOENTSync(() => rimrafWindowsFileSync(path, opt))\n return true\n }\n\n let removedAll = true\n for (const ent of entries) {\n const s = state === START ? CHILD : state\n const p = resolve(path, ent.name)\n removedAll = rimrafWindowsDirSync(p, opt, ent, s) && removedAll\n }\n\n if (state === START) {\n return rimrafWindowsDirSync(path, opt, ent, FINISH)\n } else if (state === FINISH) {\n if (opt.preserveRoot === false && path === parse(path).root) {\n return false\n }\n if (!removedAll) {\n return false\n }\n if (opt.filter && !opt.filter(path, ent)) {\n return false\n }\n ignoreENOENTSync(() => {\n rimrafWindowsDirMoveRemoveFallbackSync(path, opt)\n })\n }\n return true\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/use-native.d.ts b/node_modules/rimraf/dist/commonjs/use-native.d.ts new file mode 100644 index 0000000..e191fd9 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/use-native.d.ts @@ -0,0 +1,4 @@ +import { RimrafAsyncOptions, RimrafOptions } from './index.js'; +export declare const useNative: (opt?: RimrafAsyncOptions) => boolean; +export declare const useNativeSync: (opt?: RimrafOptions) => boolean; +//# sourceMappingURL=use-native.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/use-native.d.ts.map b/node_modules/rimraf/dist/commonjs/use-native.d.ts.map new file mode 100644 index 0000000..b182beb --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/use-native.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"use-native.d.ts","sourceRoot":"","sources":["../../src/use-native.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAa9D,eAAO,MAAM,SAAS,EAAE,CAAC,GAAG,CAAC,EAAE,kBAAkB,KAAK,OAGf,CAAA;AACvC,eAAO,MAAM,aAAa,EAAE,CAAC,GAAG,CAAC,EAAE,aAAa,KAAK,OAGd,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/use-native.js b/node_modules/rimraf/dist/commonjs/use-native.js new file mode 100644 index 0000000..1f66876 --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/use-native.js @@ -0,0 +1,22 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.useNativeSync = exports.useNative = void 0; +const platform_js_1 = __importDefault(require("./platform.js")); +const version = process.env.__TESTING_RIMRAF_NODE_VERSION__ || process.version; +const versArr = version.replace(/^v/, '').split('.'); +/* c8 ignore start */ +const [major = 0, minor = 0] = versArr.map(v => parseInt(v, 10)); +/* c8 ignore stop */ +const hasNative = major > 14 || (major === 14 && minor >= 14); +// we do NOT use native by default on Windows, because Node's native +// rm implementation is less advanced. Change this code if that changes. +exports.useNative = !hasNative || platform_js_1.default === 'win32' ? + () => false + : opt => !opt?.signal && !opt?.filter; +exports.useNativeSync = !hasNative || platform_js_1.default === 'win32' ? + () => false + : opt => !opt?.signal && !opt?.filter; +//# sourceMappingURL=use-native.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/commonjs/use-native.js.map b/node_modules/rimraf/dist/commonjs/use-native.js.map new file mode 100644 index 0000000..a89b8db --- /dev/null +++ b/node_modules/rimraf/dist/commonjs/use-native.js.map @@ -0,0 +1 @@ +{"version":3,"file":"use-native.js","sourceRoot":"","sources":["../../src/use-native.ts"],"names":[],"mappings":";;;;;;AACA,gEAAoC;AAEpC,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,+BAA+B,IAAI,OAAO,CAAC,OAAO,CAAA;AAC9E,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;AAEpD,qBAAqB;AACrB,MAAM,CAAC,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAA;AAChE,oBAAoB;AACpB,MAAM,SAAS,GAAG,KAAK,GAAG,EAAE,IAAI,CAAC,KAAK,KAAK,EAAE,IAAI,KAAK,IAAI,EAAE,CAAC,CAAA;AAE7D,oEAAoE;AACpE,yEAAyE;AAC5D,QAAA,SAAS,GACpB,CAAC,SAAS,IAAI,qBAAQ,KAAK,OAAO,CAAC,CAAC;IAClC,GAAG,EAAE,CAAC,KAAK;IACb,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,MAAM,IAAI,CAAC,GAAG,EAAE,MAAM,CAAA;AAC1B,QAAA,aAAa,GACxB,CAAC,SAAS,IAAI,qBAAQ,KAAK,OAAO,CAAC,CAAC;IAClC,GAAG,EAAE,CAAC,KAAK;IACb,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,MAAM,IAAI,CAAC,GAAG,EAAE,MAAM,CAAA","sourcesContent":["import { RimrafAsyncOptions, RimrafOptions } from './index.js'\nimport platform from './platform.js'\n\nconst version = process.env.__TESTING_RIMRAF_NODE_VERSION__ || process.version\nconst versArr = version.replace(/^v/, '').split('.')\n\n/* c8 ignore start */\nconst [major = 0, minor = 0] = versArr.map(v => parseInt(v, 10))\n/* c8 ignore stop */\nconst hasNative = major > 14 || (major === 14 && minor >= 14)\n\n// we do NOT use native by default on Windows, because Node's native\n// rm implementation is less advanced. Change this code if that changes.\nexport const useNative: (opt?: RimrafAsyncOptions) => boolean =\n !hasNative || platform === 'win32' ?\n () => false\n : opt => !opt?.signal && !opt?.filter\nexport const useNativeSync: (opt?: RimrafOptions) => boolean =\n !hasNative || platform === 'win32' ?\n () => false\n : opt => !opt?.signal && !opt?.filter\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/bin.d.mts b/node_modules/rimraf/dist/esm/bin.d.mts new file mode 100644 index 0000000..5600d7c --- /dev/null +++ b/node_modules/rimraf/dist/esm/bin.d.mts @@ -0,0 +1,8 @@ +#!/usr/bin/env node +export declare const help: string; +declare const main: { + (...args: string[]): Promise<1 | 0>; + help: string; +}; +export default main; +//# sourceMappingURL=bin.d.mts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/bin.d.mts.map b/node_modules/rimraf/dist/esm/bin.d.mts.map new file mode 100644 index 0000000..a5f1ec2 --- /dev/null +++ b/node_modules/rimraf/dist/esm/bin.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"bin.d.mts","sourceRoot":"","sources":["../../src/bin.mts"],"names":[],"mappings":";AAcA,eAAO,MAAM,IAAI,QAkChB,CAAA;AA8ED,QAAA,MAAM,IAAI;cAAmB,MAAM,EAAE;;CAoIpC,CAAA;AAGD,eAAe,IAAI,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/bin.mjs b/node_modules/rimraf/dist/esm/bin.mjs new file mode 100755 index 0000000..4aea35e --- /dev/null +++ b/node_modules/rimraf/dist/esm/bin.mjs @@ -0,0 +1,256 @@ +#!/usr/bin/env node +import { readFile } from 'fs/promises'; +import { rimraf } from './index.js'; +const pj = fileURLToPath(new URL('../package.json', import.meta.url)); +const pjDist = fileURLToPath(new URL('../../package.json', import.meta.url)); +const { version } = JSON.parse(await readFile(pjDist, 'utf8').catch(() => readFile(pj, 'utf8'))); +const runHelpForUsage = () => console.error('run `rimraf --help` for usage information'); +export const help = `rimraf version ${version} + +Usage: rimraf [ ...] +Deletes all files and folders at "path", recursively. + +Options: + -- Treat all subsequent arguments as paths + -h --help Display this usage info + --preserve-root Do not remove '/' recursively (default) + --no-preserve-root Do not treat '/' specially + -G --no-glob Treat arguments as literal paths, not globs (default) + -g --glob Treat arguments as glob patterns + -v --verbose Be verbose when deleting files, showing them as + they are removed. Not compatible with --impl=native + -V --no-verbose Be silent when deleting files, showing nothing as + they are removed (default) + -i --interactive Ask for confirmation before deleting anything + Not compatible with --impl=native + -I --no-interactive Do not ask for confirmation before deleting + + --impl= Specify the implementation to use: + rimraf: choose the best option (default) + native: the built-in implementation in Node.js + manual: the platform-specific JS implementation + posix: the Posix JS implementation + windows: the Windows JS implementation (falls back to + move-remove on ENOTEMPTY) + move-remove: a slow reliable Windows fallback + +Implementation-specific options: + --tmp= Temp file folder for 'move-remove' implementation + --max-retries= maxRetries for 'native' and 'windows' implementations + --retry-delay= retryDelay for 'native' implementation, default 100 + --backoff= Exponential backoff factor for retries (default: 1.2) +`; +import { parse, relative, resolve } from 'path'; +const cwd = process.cwd(); +import { createInterface } from 'readline'; +import { fileURLToPath } from 'url'; +const prompt = async (rl, q) => new Promise(res => rl.question(q, res)); +const interactiveRimraf = async (impl, paths, opt) => { + const existingFilter = opt.filter || (() => true); + let allRemaining = false; + let noneRemaining = false; + const queue = []; + let processing = false; + const processQueue = async () => { + if (processing) + return; + processing = true; + let next; + while ((next = queue.shift())) { + await next(); + } + processing = false; + }; + const oneAtATime = (fn) => async (s, e) => { + const p = new Promise(res => { + queue.push(async () => { + const result = await fn(s, e); + res(result); + return result; + }); + }); + processQueue(); + return p; + }; + const rl = createInterface({ + input: process.stdin, + output: process.stdout, + }); + opt.filter = oneAtATime(async (path, ent) => { + if (noneRemaining) { + return false; + } + while (!allRemaining) { + const a = (await prompt(rl, `rm? ${relative(cwd, path)}\n[(Yes)/No/All/Quit] > `)).trim(); + if (/^n/i.test(a)) { + return false; + } + else if (/^a/i.test(a)) { + allRemaining = true; + break; + } + else if (/^q/i.test(a)) { + noneRemaining = true; + return false; + } + else if (a === '' || /^y/i.test(a)) { + break; + } + else { + continue; + } + } + return existingFilter(path, ent); + }); + await impl(paths, opt); + rl.close(); +}; +const main = async (...args) => { + const verboseFilter = (s) => { + console.log(relative(cwd, s)); + return true; + }; + if (process.env.__RIMRAF_TESTING_BIN_FAIL__ === '1') { + throw new Error('simulated rimraf failure'); + } + const opt = {}; + const paths = []; + let dashdash = false; + let impl = rimraf; + let interactive = false; + for (const arg of args) { + if (dashdash) { + paths.push(arg); + continue; + } + if (arg === '--') { + dashdash = true; + continue; + } + else if (arg === '-rf' || arg === '-fr') { + // this never did anything, but people put it there I guess + continue; + } + else if (arg === '-h' || arg === '--help') { + console.log(help); + return 0; + } + else if (arg === '--interactive' || arg === '-i') { + interactive = true; + continue; + } + else if (arg === '--no-interactive' || arg === '-I') { + interactive = false; + continue; + } + else if (arg === '--verbose' || arg === '-v') { + opt.filter = verboseFilter; + continue; + } + else if (arg === '--no-verbose' || arg === '-V') { + opt.filter = undefined; + continue; + } + else if (arg === '-g' || arg === '--glob') { + opt.glob = true; + continue; + } + else if (arg === '-G' || arg === '--no-glob') { + opt.glob = false; + continue; + } + else if (arg === '--preserve-root') { + opt.preserveRoot = true; + continue; + } + else if (arg === '--no-preserve-root') { + opt.preserveRoot = false; + continue; + } + else if (/^--tmp=/.test(arg)) { + const val = arg.substring('--tmp='.length); + opt.tmp = val; + continue; + } + else if (/^--max-retries=/.test(arg)) { + const val = +arg.substring('--max-retries='.length); + opt.maxRetries = val; + continue; + } + else if (/^--retry-delay=/.test(arg)) { + const val = +arg.substring('--retry-delay='.length); + opt.retryDelay = val; + continue; + } + else if (/^--backoff=/.test(arg)) { + const val = +arg.substring('--backoff='.length); + opt.backoff = val; + continue; + } + else if (/^--impl=/.test(arg)) { + const val = arg.substring('--impl='.length); + switch (val) { + case 'rimraf': + impl = rimraf; + continue; + case 'native': + case 'manual': + case 'posix': + case 'windows': + impl = rimraf[val]; + continue; + case 'move-remove': + impl = rimraf.moveRemove; + continue; + default: + console.error(`unknown implementation: ${val}`); + runHelpForUsage(); + return 1; + } + } + else if (/^-/.test(arg)) { + console.error(`unknown option: ${arg}`); + runHelpForUsage(); + return 1; + } + else { + paths.push(arg); + } + } + if (opt.preserveRoot !== false) { + for (const path of paths.map(p => resolve(p))) { + if (path === parse(path).root) { + console.error(`rimraf: it is dangerous to operate recursively on '/'`); + console.error('use --no-preserve-root to override this failsafe'); + return 1; + } + } + } + if (!paths.length) { + console.error('rimraf: must provide a path to remove'); + runHelpForUsage(); + return 1; + } + if (impl === rimraf.native && (interactive || opt.filter)) { + console.error('native implementation does not support -v or -i'); + runHelpForUsage(); + return 1; + } + if (interactive) { + await interactiveRimraf(impl, paths, opt); + } + else { + await impl(paths, opt); + } + return 0; +}; +main.help = help; +export default main; +if (process.env.__TESTING_RIMRAF_BIN__ !== '1') { + const args = process.argv.slice(2); + main(...args).then(code => process.exit(code), er => { + console.error(er); + process.exit(1); + }); +} +//# sourceMappingURL=bin.mjs.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/bin.mjs.map b/node_modules/rimraf/dist/esm/bin.mjs.map new file mode 100644 index 0000000..163fc96 --- /dev/null +++ b/node_modules/rimraf/dist/esm/bin.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"bin.mjs","sourceRoot":"","sources":["../../src/bin.mts"],"names":[],"mappings":";AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAEtC,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAA;AAEnC,MAAM,EAAE,GAAG,aAAa,CAAC,IAAI,GAAG,CAAC,iBAAiB,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAA;AACrE,MAAM,MAAM,GAAG,aAAa,CAAC,IAAI,GAAG,CAAC,oBAAoB,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAA;AAC5E,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC,KAAK,CAC5B,MAAM,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC,CAC1C,CAAA;AAExB,MAAM,eAAe,GAAG,GAAG,EAAE,CAC3B,OAAO,CAAC,KAAK,CAAC,2CAA2C,CAAC,CAAA;AAE5D,MAAM,CAAC,MAAM,IAAI,GAAG,kBAAkB,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkC5C,CAAA;AAED,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAC/C,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,CAAA;AAGzB,OAAO,EAAE,eAAe,EAAa,MAAM,UAAU,CAAA;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAA;AAEnC,MAAM,MAAM,GAAG,KAAK,EAAE,EAAa,EAAE,CAAS,EAAE,EAAE,CAChD,IAAI,OAAO,CAAS,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAA;AAEjD,MAAM,iBAAiB,GAAG,KAAK,EAC7B,IAA6E,EAC7E,KAAe,EACf,GAAuB,EACvB,EAAE;IACF,MAAM,cAAc,GAAG,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAA;IACjD,IAAI,YAAY,GAAG,KAAK,CAAA;IACxB,IAAI,aAAa,GAAG,KAAK,CAAA;IACzB,MAAM,KAAK,GAA+B,EAAE,CAAA;IAC5C,IAAI,UAAU,GAAG,KAAK,CAAA;IACtB,MAAM,YAAY,GAAG,KAAK,IAAI,EAAE;QAC9B,IAAI,UAAU;YAAE,OAAM;QACtB,UAAU,GAAG,IAAI,CAAA;QACjB,IAAI,IAA0C,CAAA;QAC9C,OAAO,CAAC,IAAI,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC;YAC9B,MAAM,IAAI,EAAE,CAAA;QACd,CAAC;QACD,UAAU,GAAG,KAAK,CAAA;IACpB,CAAC,CAAA;IACD,MAAM,UAAU,GACd,CAAC,EAAsD,EAAE,EAAE,CAC3D,KAAK,EAAE,CAAS,EAAE,CAAiB,EAAoB,EAAE;QACvD,MAAM,CAAC,GAAG,IAAI,OAAO,CAAU,GAAG,CAAC,EAAE;YACnC,KAAK,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE;gBACpB,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;gBAC7B,GAAG,CAAC,MAAM,CAAC,CAAA;gBACX,OAAO,MAAM,CAAA;YACf,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QACF,YAAY,EAAE,CAAA;QACd,OAAO,CAAC,CAAA;IACV,CAAC,CAAA;IACH,MAAM,EAAE,GAAG,eAAe,CAAC;QACzB,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,MAAM,EAAE,OAAO,CAAC,MAAM;KACvB,CAAC,CAAA;IACF,GAAG,CAAC,MAAM,GAAG,UAAU,CACrB,KAAK,EAAE,IAAY,EAAE,GAAmB,EAAoB,EAAE;QAC5D,IAAI,aAAa,EAAE,CAAC;YAClB,OAAO,KAAK,CAAA;QACd,CAAC;QACD,OAAO,CAAC,YAAY,EAAE,CAAC;YACrB,MAAM,CAAC,GAAG,CACR,MAAM,MAAM,CAAC,EAAE,EAAE,OAAO,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,0BAA0B,CAAC,CACvE,CAAC,IAAI,EAAE,CAAA;YACR,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;gBAClB,OAAO,KAAK,CAAA;YACd,CAAC;iBAAM,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;gBACzB,YAAY,GAAG,IAAI,CAAA;gBACnB,MAAK;YACP,CAAC;iBAAM,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;gBACzB,aAAa,GAAG,IAAI,CAAA;gBACpB,OAAO,KAAK,CAAA;YACd,CAAC;iBAAM,IAAI,CAAC,KAAK,EAAE,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;gBACrC,MAAK;YACP,CAAC;iBAAM,CAAC;gBACN,SAAQ;YACV,CAAC;QACH,CAAC;QACD,OAAO,cAAc,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;IAClC,CAAC,CACF,CAAA;IACD,MAAM,IAAI,CAAC,KAAK,EAAE,GAAG,CAAC,CAAA;IACtB,EAAE,CAAC,KAAK,EAAE,CAAA;AACZ,CAAC,CAAA;AAED,MAAM,IAAI,GAAG,KAAK,EAAE,GAAG,IAAc,EAAE,EAAE;IACvC,MAAM,aAAa,GAAG,CAAC,CAAS,EAAE,EAAE;QAClC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAA;QAC7B,OAAO,IAAI,CAAA;IACb,CAAC,CAAA;IAED,IAAI,OAAO,CAAC,GAAG,CAAC,2BAA2B,KAAK,GAAG,EAAE,CAAC;QACpD,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAA;IAC7C,CAAC;IAED,MAAM,GAAG,GAAuB,EAAE,CAAA;IAClC,MAAM,KAAK,GAAa,EAAE,CAAA;IAC1B,IAAI,QAAQ,GAAG,KAAK,CAAA;IACpB,IAAI,IAAI,GAGgB,MAAM,CAAA;IAE9B,IAAI,WAAW,GAAG,KAAK,CAAA;IAEvB,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,IAAI,QAAQ,EAAE,CAAC;YACb,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;YACf,SAAQ;QACV,CAAC;QACD,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC;YACjB,QAAQ,GAAG,IAAI,CAAA;YACf,SAAQ;QACV,CAAC;aAAM,IAAI,GAAG,KAAK,KAAK,IAAI,GAAG,KAAK,KAAK,EAAE,CAAC;YAC1C,2DAA2D;YAC3D,SAAQ;QACV,CAAC;aAAM,IAAI,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,QAAQ,EAAE,CAAC;YAC5C,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;YACjB,OAAO,CAAC,CAAA;QACV,CAAC;aAAM,IAAI,GAAG,KAAK,eAAe,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC;YACnD,WAAW,GAAG,IAAI,CAAA;YAClB,SAAQ;QACV,CAAC;aAAM,IAAI,GAAG,KAAK,kBAAkB,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC;YACtD,WAAW,GAAG,KAAK,CAAA;YACnB,SAAQ;QACV,CAAC;aAAM,IAAI,GAAG,KAAK,WAAW,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC;YAC/C,GAAG,CAAC,MAAM,GAAG,aAAa,CAAA;YAC1B,SAAQ;QACV,CAAC;aAAM,IAAI,GAAG,KAAK,cAAc,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC;YAClD,GAAG,CAAC,MAAM,GAAG,SAAS,CAAA;YACtB,SAAQ;QACV,CAAC;aAAM,IAAI,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,QAAQ,EAAE,CAAC;YAC5C,GAAG,CAAC,IAAI,GAAG,IAAI,CAAA;YACf,SAAQ;QACV,CAAC;aAAM,IAAI,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,WAAW,EAAE,CAAC;YAC/C,GAAG,CAAC,IAAI,GAAG,KAAK,CAAA;YAChB,SAAQ;QACV,CAAC;aAAM,IAAI,GAAG,KAAK,iBAAiB,EAAE,CAAC;YACrC,GAAG,CAAC,YAAY,GAAG,IAAI,CAAA;YACvB,SAAQ;QACV,CAAC;aAAM,IAAI,GAAG,KAAK,oBAAoB,EAAE,CAAC;YACxC,GAAG,CAAC,YAAY,GAAG,KAAK,CAAA;YACxB,SAAQ;QACV,CAAC;aAAM,IAAI,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YAC/B,MAAM,GAAG,GAAG,GAAG,CAAC,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAA;YAC1C,GAAG,CAAC,GAAG,GAAG,GAAG,CAAA;YACb,SAAQ;QACV,CAAC;aAAM,IAAI,iBAAiB,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YACvC,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAA;YACnD,GAAG,CAAC,UAAU,GAAG,GAAG,CAAA;YACpB,SAAQ;QACV,CAAC;aAAM,IAAI,iBAAiB,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YACvC,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAA;YACnD,GAAG,CAAC,UAAU,GAAG,GAAG,CAAA;YACpB,SAAQ;QACV,CAAC;aAAM,IAAI,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YACnC,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,YAAY,CAAC,MAAM,CAAC,CAAA;YAC/C,GAAG,CAAC,OAAO,GAAG,GAAG,CAAA;YACjB,SAAQ;QACV,CAAC;aAAM,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YAChC,MAAM,GAAG,GAAG,GAAG,CAAC,SAAS,CAAC,SAAS,CAAC,MAAM,CAAC,CAAA;YAC3C,QAAQ,GAAG,EAAE,CAAC;gBACZ,KAAK,QAAQ;oBACX,IAAI,GAAG,MAAM,CAAA;oBACb,SAAQ;gBACV,KAAK,QAAQ,CAAC;gBACd,KAAK,QAAQ,CAAC;gBACd,KAAK,OAAO,CAAC;gBACb,KAAK,SAAS;oBACZ,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,CAAA;oBAClB,SAAQ;gBACV,KAAK,aAAa;oBAChB,IAAI,GAAG,MAAM,CAAC,UAAU,CAAA;oBACxB,SAAQ;gBACV;oBACE,OAAO,CAAC,KAAK,CAAC,2BAA2B,GAAG,EAAE,CAAC,CAAA;oBAC/C,eAAe,EAAE,CAAA;oBACjB,OAAO,CAAC,CAAA;YACZ,CAAC;QACH,CAAC;aAAM,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YAC1B,OAAO,CAAC,KAAK,CAAC,mBAAmB,GAAG,EAAE,CAAC,CAAA;YACvC,eAAe,EAAE,CAAA;YACjB,OAAO,CAAC,CAAA;QACV,CAAC;aAAM,CAAC;YACN,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;QACjB,CAAC;IACH,CAAC;IAED,IAAI,GAAG,CAAC,YAAY,KAAK,KAAK,EAAE,CAAC;QAC/B,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;YAC9C,IAAI,IAAI,KAAK,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;gBAC9B,OAAO,CAAC,KAAK,CAAC,uDAAuD,CAAC,CAAA;gBACtE,OAAO,CAAC,KAAK,CAAC,kDAAkD,CAAC,CAAA;gBACjE,OAAO,CAAC,CAAA;YACV,CAAC;QACH,CAAC;IACH,CAAC;IAED,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC;QAClB,OAAO,CAAC,KAAK,CAAC,uCAAuC,CAAC,CAAA;QACtD,eAAe,EAAE,CAAA;QACjB,OAAO,CAAC,CAAA;IACV,CAAC;IAED,IAAI,IAAI,KAAK,MAAM,CAAC,MAAM,IAAI,CAAC,WAAW,IAAI,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;QAC1D,OAAO,CAAC,KAAK,CAAC,iDAAiD,CAAC,CAAA;QAChE,eAAe,EAAE,CAAA;QACjB,OAAO,CAAC,CAAA;IACV,CAAC;IAED,IAAI,WAAW,EAAE,CAAC;QAChB,MAAM,iBAAiB,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,CAAA;IAC3C,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,CAAC,KAAK,EAAE,GAAG,CAAC,CAAA;IACxB,CAAC;IAED,OAAO,CAAC,CAAA;AACV,CAAC,CAAA;AACD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;AAEhB,eAAe,IAAI,CAAA;AAEnB,IAAI,OAAO,CAAC,GAAG,CAAC,sBAAsB,KAAK,GAAG,EAAE,CAAC;IAC/C,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IAClC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,IAAI,CAChB,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAC1B,EAAE,CAAC,EAAE;QACH,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;IACjB,CAAC,CACF,CAAA;AACH,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { readFile } from 'fs/promises'\nimport type { RimrafAsyncOptions } from './index.js'\nimport { rimraf } from './index.js'\n\nconst pj = fileURLToPath(new URL('../package.json', import.meta.url))\nconst pjDist = fileURLToPath(new URL('../../package.json', import.meta.url))\nconst { version } = JSON.parse(\n await readFile(pjDist, 'utf8').catch(() => readFile(pj, 'utf8')),\n) as { version: string }\n\nconst runHelpForUsage = () =>\n console.error('run `rimraf --help` for usage information')\n\nexport const help = `rimraf version ${version}\n\nUsage: rimraf [ ...]\nDeletes all files and folders at \"path\", recursively.\n\nOptions:\n -- Treat all subsequent arguments as paths\n -h --help Display this usage info\n --preserve-root Do not remove '/' recursively (default)\n --no-preserve-root Do not treat '/' specially\n -G --no-glob Treat arguments as literal paths, not globs (default)\n -g --glob Treat arguments as glob patterns\n -v --verbose Be verbose when deleting files, showing them as\n they are removed. Not compatible with --impl=native\n -V --no-verbose Be silent when deleting files, showing nothing as\n they are removed (default)\n -i --interactive Ask for confirmation before deleting anything\n Not compatible with --impl=native\n -I --no-interactive Do not ask for confirmation before deleting\n\n --impl= Specify the implementation to use:\n rimraf: choose the best option (default)\n native: the built-in implementation in Node.js\n manual: the platform-specific JS implementation\n posix: the Posix JS implementation\n windows: the Windows JS implementation (falls back to\n move-remove on ENOTEMPTY)\n move-remove: a slow reliable Windows fallback\n\nImplementation-specific options:\n --tmp= Temp file folder for 'move-remove' implementation\n --max-retries= maxRetries for 'native' and 'windows' implementations\n --retry-delay= retryDelay for 'native' implementation, default 100\n --backoff= Exponential backoff factor for retries (default: 1.2)\n`\n\nimport { parse, relative, resolve } from 'path'\nconst cwd = process.cwd()\n\nimport { Dirent, Stats } from 'fs'\nimport { createInterface, Interface } from 'readline'\nimport { fileURLToPath } from 'url'\n\nconst prompt = async (rl: Interface, q: string) =>\n new Promise(res => rl.question(q, res))\n\nconst interactiveRimraf = async (\n impl: (path: string | string[], opt?: RimrafAsyncOptions) => Promise,\n paths: string[],\n opt: RimrafAsyncOptions,\n) => {\n const existingFilter = opt.filter || (() => true)\n let allRemaining = false\n let noneRemaining = false\n const queue: (() => Promise)[] = []\n let processing = false\n const processQueue = async () => {\n if (processing) return\n processing = true\n let next: (() => Promise) | undefined\n while ((next = queue.shift())) {\n await next()\n }\n processing = false\n }\n const oneAtATime =\n (fn: (s: string, e: Dirent | Stats) => Promise) =>\n async (s: string, e: Dirent | Stats): Promise => {\n const p = new Promise(res => {\n queue.push(async () => {\n const result = await fn(s, e)\n res(result)\n return result\n })\n })\n processQueue()\n return p\n }\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n })\n opt.filter = oneAtATime(\n async (path: string, ent: Dirent | Stats): Promise => {\n if (noneRemaining) {\n return false\n }\n while (!allRemaining) {\n const a = (\n await prompt(rl, `rm? ${relative(cwd, path)}\\n[(Yes)/No/All/Quit] > `)\n ).trim()\n if (/^n/i.test(a)) {\n return false\n } else if (/^a/i.test(a)) {\n allRemaining = true\n break\n } else if (/^q/i.test(a)) {\n noneRemaining = true\n return false\n } else if (a === '' || /^y/i.test(a)) {\n break\n } else {\n continue\n }\n }\n return existingFilter(path, ent)\n },\n )\n await impl(paths, opt)\n rl.close()\n}\n\nconst main = async (...args: string[]) => {\n const verboseFilter = (s: string) => {\n console.log(relative(cwd, s))\n return true\n }\n\n if (process.env.__RIMRAF_TESTING_BIN_FAIL__ === '1') {\n throw new Error('simulated rimraf failure')\n }\n\n const opt: RimrafAsyncOptions = {}\n const paths: string[] = []\n let dashdash = false\n let impl: (\n path: string | string[],\n opt?: RimrafAsyncOptions,\n ) => Promise = rimraf\n\n let interactive = false\n\n for (const arg of args) {\n if (dashdash) {\n paths.push(arg)\n continue\n }\n if (arg === '--') {\n dashdash = true\n continue\n } else if (arg === '-rf' || arg === '-fr') {\n // this never did anything, but people put it there I guess\n continue\n } else if (arg === '-h' || arg === '--help') {\n console.log(help)\n return 0\n } else if (arg === '--interactive' || arg === '-i') {\n interactive = true\n continue\n } else if (arg === '--no-interactive' || arg === '-I') {\n interactive = false\n continue\n } else if (arg === '--verbose' || arg === '-v') {\n opt.filter = verboseFilter\n continue\n } else if (arg === '--no-verbose' || arg === '-V') {\n opt.filter = undefined\n continue\n } else if (arg === '-g' || arg === '--glob') {\n opt.glob = true\n continue\n } else if (arg === '-G' || arg === '--no-glob') {\n opt.glob = false\n continue\n } else if (arg === '--preserve-root') {\n opt.preserveRoot = true\n continue\n } else if (arg === '--no-preserve-root') {\n opt.preserveRoot = false\n continue\n } else if (/^--tmp=/.test(arg)) {\n const val = arg.substring('--tmp='.length)\n opt.tmp = val\n continue\n } else if (/^--max-retries=/.test(arg)) {\n const val = +arg.substring('--max-retries='.length)\n opt.maxRetries = val\n continue\n } else if (/^--retry-delay=/.test(arg)) {\n const val = +arg.substring('--retry-delay='.length)\n opt.retryDelay = val\n continue\n } else if (/^--backoff=/.test(arg)) {\n const val = +arg.substring('--backoff='.length)\n opt.backoff = val\n continue\n } else if (/^--impl=/.test(arg)) {\n const val = arg.substring('--impl='.length)\n switch (val) {\n case 'rimraf':\n impl = rimraf\n continue\n case 'native':\n case 'manual':\n case 'posix':\n case 'windows':\n impl = rimraf[val]\n continue\n case 'move-remove':\n impl = rimraf.moveRemove\n continue\n default:\n console.error(`unknown implementation: ${val}`)\n runHelpForUsage()\n return 1\n }\n } else if (/^-/.test(arg)) {\n console.error(`unknown option: ${arg}`)\n runHelpForUsage()\n return 1\n } else {\n paths.push(arg)\n }\n }\n\n if (opt.preserveRoot !== false) {\n for (const path of paths.map(p => resolve(p))) {\n if (path === parse(path).root) {\n console.error(`rimraf: it is dangerous to operate recursively on '/'`)\n console.error('use --no-preserve-root to override this failsafe')\n return 1\n }\n }\n }\n\n if (!paths.length) {\n console.error('rimraf: must provide a path to remove')\n runHelpForUsage()\n return 1\n }\n\n if (impl === rimraf.native && (interactive || opt.filter)) {\n console.error('native implementation does not support -v or -i')\n runHelpForUsage()\n return 1\n }\n\n if (interactive) {\n await interactiveRimraf(impl, paths, opt)\n } else {\n await impl(paths, opt)\n }\n\n return 0\n}\nmain.help = help\n\nexport default main\n\nif (process.env.__TESTING_RIMRAF_BIN__ !== '1') {\n const args = process.argv.slice(2)\n main(...args).then(\n code => process.exit(code),\n er => {\n console.error(er)\n process.exit(1)\n },\n )\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/default-tmp.d.ts b/node_modules/rimraf/dist/esm/default-tmp.d.ts new file mode 100644 index 0000000..a68e925 --- /dev/null +++ b/node_modules/rimraf/dist/esm/default-tmp.d.ts @@ -0,0 +1,3 @@ +export declare const defaultTmp: (path: string) => Promise; +export declare const defaultTmpSync: (path: string) => string; +//# sourceMappingURL=default-tmp.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/default-tmp.d.ts.map b/node_modules/rimraf/dist/esm/default-tmp.d.ts.map new file mode 100644 index 0000000..d0b35f2 --- /dev/null +++ b/node_modules/rimraf/dist/esm/default-tmp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"default-tmp.d.ts","sourceRoot":"","sources":["../../src/default-tmp.ts"],"names":[],"mappings":"AAiEA,eAAO,MAAM,UAAU,SAnCc,MAAM,oBAoCe,CAAA;AAC1D,eAAO,MAAM,cAAc,SArBQ,MAAM,WAsByB,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/default-tmp.js b/node_modules/rimraf/dist/esm/default-tmp.js new file mode 100644 index 0000000..fb0846a --- /dev/null +++ b/node_modules/rimraf/dist/esm/default-tmp.js @@ -0,0 +1,55 @@ +// The default temporary folder location for use in the windows algorithm. +// It's TEMPting to use dirname(path), since that's guaranteed to be on the +// same device. However, this means that: +// rimraf(path).then(() => rimraf(dirname(path))) +// will often fail with EBUSY, because the parent dir contains +// marked-for-deletion directory entries (which do not show up in readdir). +// The approach here is to use os.tmpdir() if it's on the same drive letter, +// or resolve(path, '\\temp') if it exists, or the root of the drive if not. +// On Posix (not that you'd be likely to use the windows algorithm there), +// it uses os.tmpdir() always. +import { tmpdir } from 'os'; +import { parse, resolve } from 'path'; +import { promises, statSync } from './fs.js'; +import platform from './platform.js'; +const { stat } = promises; +const isDirSync = (path) => { + try { + return statSync(path).isDirectory(); + } + catch (er) { + return false; + } +}; +const isDir = (path) => stat(path).then(st => st.isDirectory(), () => false); +const win32DefaultTmp = async (path) => { + const { root } = parse(path); + const tmp = tmpdir(); + const { root: tmpRoot } = parse(tmp); + if (root.toLowerCase() === tmpRoot.toLowerCase()) { + return tmp; + } + const driveTmp = resolve(root, '/temp'); + if (await isDir(driveTmp)) { + return driveTmp; + } + return root; +}; +const win32DefaultTmpSync = (path) => { + const { root } = parse(path); + const tmp = tmpdir(); + const { root: tmpRoot } = parse(tmp); + if (root.toLowerCase() === tmpRoot.toLowerCase()) { + return tmp; + } + const driveTmp = resolve(root, '/temp'); + if (isDirSync(driveTmp)) { + return driveTmp; + } + return root; +}; +const posixDefaultTmp = async () => tmpdir(); +const posixDefaultTmpSync = () => tmpdir(); +export const defaultTmp = platform === 'win32' ? win32DefaultTmp : posixDefaultTmp; +export const defaultTmpSync = platform === 'win32' ? win32DefaultTmpSync : posixDefaultTmpSync; +//# sourceMappingURL=default-tmp.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/default-tmp.js.map b/node_modules/rimraf/dist/esm/default-tmp.js.map new file mode 100644 index 0000000..ea6af37 --- /dev/null +++ b/node_modules/rimraf/dist/esm/default-tmp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"default-tmp.js","sourceRoot":"","sources":["../../src/default-tmp.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,2EAA2E;AAC3E,0CAA0C;AAC1C,iDAAiD;AACjD,8DAA8D;AAC9D,2EAA2E;AAC3E,4EAA4E;AAC5E,4EAA4E;AAC5E,0EAA0E;AAC1E,8BAA8B;AAC9B,OAAO,EAAE,MAAM,EAAE,MAAM,IAAI,CAAA;AAC3B,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AACrC,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAC5C,OAAO,QAAQ,MAAM,eAAe,CAAA;AACpC,MAAM,EAAE,IAAI,EAAE,GAAG,QAAQ,CAAA;AAEzB,MAAM,SAAS,GAAG,CAAC,IAAY,EAAE,EAAE;IACjC,IAAI,CAAC;QACH,OAAO,QAAQ,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE,CAAA;IACrC,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,OAAO,KAAK,CAAA;IACd,CAAC;AACH,CAAC,CAAA;AAED,MAAM,KAAK,GAAG,CAAC,IAAY,EAAE,EAAE,CAC7B,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CACb,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,WAAW,EAAE,EACtB,GAAG,EAAE,CAAC,KAAK,CACZ,CAAA;AAEH,MAAM,eAAe,GAAG,KAAK,EAAE,IAAY,EAAE,EAAE;IAC7C,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC,IAAI,CAAC,CAAA;IAC5B,MAAM,GAAG,GAAG,MAAM,EAAE,CAAA;IACpB,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC,GAAG,CAAC,CAAA;IACpC,IAAI,IAAI,CAAC,WAAW,EAAE,KAAK,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC;QACjD,OAAO,GAAG,CAAA;IACZ,CAAC;IAED,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IACvC,IAAI,MAAM,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC1B,OAAO,QAAQ,CAAA;IACjB,CAAC;IAED,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,MAAM,mBAAmB,GAAG,CAAC,IAAY,EAAE,EAAE;IAC3C,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC,IAAI,CAAC,CAAA;IAC5B,MAAM,GAAG,GAAG,MAAM,EAAE,CAAA;IACpB,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC,GAAG,CAAC,CAAA;IACpC,IAAI,IAAI,CAAC,WAAW,EAAE,KAAK,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC;QACjD,OAAO,GAAG,CAAA;IACZ,CAAC;IAED,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IACvC,IAAI,SAAS,CAAC,QAAQ,CAAC,EAAE,CAAC;QACxB,OAAO,QAAQ,CAAA;IACjB,CAAC;IAED,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,MAAM,eAAe,GAAG,KAAK,IAAI,EAAE,CAAC,MAAM,EAAE,CAAA;AAC5C,MAAM,mBAAmB,GAAG,GAAG,EAAE,CAAC,MAAM,EAAE,CAAA;AAE1C,MAAM,CAAC,MAAM,UAAU,GACrB,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,eAAe,CAAA;AAC1D,MAAM,CAAC,MAAM,cAAc,GACzB,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,mBAAmB,CAAA","sourcesContent":["// The default temporary folder location for use in the windows algorithm.\n// It's TEMPting to use dirname(path), since that's guaranteed to be on the\n// same device. However, this means that:\n// rimraf(path).then(() => rimraf(dirname(path)))\n// will often fail with EBUSY, because the parent dir contains\n// marked-for-deletion directory entries (which do not show up in readdir).\n// The approach here is to use os.tmpdir() if it's on the same drive letter,\n// or resolve(path, '\\\\temp') if it exists, or the root of the drive if not.\n// On Posix (not that you'd be likely to use the windows algorithm there),\n// it uses os.tmpdir() always.\nimport { tmpdir } from 'os'\nimport { parse, resolve } from 'path'\nimport { promises, statSync } from './fs.js'\nimport platform from './platform.js'\nconst { stat } = promises\n\nconst isDirSync = (path: string) => {\n try {\n return statSync(path).isDirectory()\n } catch (er) {\n return false\n }\n}\n\nconst isDir = (path: string) =>\n stat(path).then(\n st => st.isDirectory(),\n () => false,\n )\n\nconst win32DefaultTmp = async (path: string) => {\n const { root } = parse(path)\n const tmp = tmpdir()\n const { root: tmpRoot } = parse(tmp)\n if (root.toLowerCase() === tmpRoot.toLowerCase()) {\n return tmp\n }\n\n const driveTmp = resolve(root, '/temp')\n if (await isDir(driveTmp)) {\n return driveTmp\n }\n\n return root\n}\n\nconst win32DefaultTmpSync = (path: string) => {\n const { root } = parse(path)\n const tmp = tmpdir()\n const { root: tmpRoot } = parse(tmp)\n if (root.toLowerCase() === tmpRoot.toLowerCase()) {\n return tmp\n }\n\n const driveTmp = resolve(root, '/temp')\n if (isDirSync(driveTmp)) {\n return driveTmp\n }\n\n return root\n}\n\nconst posixDefaultTmp = async () => tmpdir()\nconst posixDefaultTmpSync = () => tmpdir()\n\nexport const defaultTmp =\n platform === 'win32' ? win32DefaultTmp : posixDefaultTmp\nexport const defaultTmpSync =\n platform === 'win32' ? win32DefaultTmpSync : posixDefaultTmpSync\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/fix-eperm.d.ts b/node_modules/rimraf/dist/esm/fix-eperm.d.ts new file mode 100644 index 0000000..20e76a8 --- /dev/null +++ b/node_modules/rimraf/dist/esm/fix-eperm.d.ts @@ -0,0 +1,3 @@ +export declare const fixEPERM: (fn: (path: string) => Promise) => (path: string) => Promise; +export declare const fixEPERMSync: (fn: (path: string) => any) => (path: string) => any; +//# sourceMappingURL=fix-eperm.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/fix-eperm.d.ts.map b/node_modules/rimraf/dist/esm/fix-eperm.d.ts.map new file mode 100644 index 0000000..ac17d6f --- /dev/null +++ b/node_modules/rimraf/dist/esm/fix-eperm.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fix-eperm.d.ts","sourceRoot":"","sources":["../../src/fix-eperm.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,QAAQ,OACd,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,GAAG,CAAC,YAAkB,MAAM,iBAsB1D,CAAA;AAEH,eAAO,MAAM,YAAY,OAAQ,CAAC,IAAI,EAAE,MAAM,KAAK,GAAG,YAAY,MAAM,QAsBvE,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/fix-eperm.js b/node_modules/rimraf/dist/esm/fix-eperm.js new file mode 100644 index 0000000..633c0e1 --- /dev/null +++ b/node_modules/rimraf/dist/esm/fix-eperm.js @@ -0,0 +1,53 @@ +import { chmodSync, promises } from './fs.js'; +const { chmod } = promises; +export const fixEPERM = (fn) => async (path) => { + try { + return await fn(path); + } + catch (er) { + const fer = er; + if (fer?.code === 'ENOENT') { + return; + } + if (fer?.code === 'EPERM') { + try { + await chmod(path, 0o666); + } + catch (er2) { + const fer2 = er2; + if (fer2?.code === 'ENOENT') { + return; + } + throw er; + } + return await fn(path); + } + throw er; + } +}; +export const fixEPERMSync = (fn) => (path) => { + try { + return fn(path); + } + catch (er) { + const fer = er; + if (fer?.code === 'ENOENT') { + return; + } + if (fer?.code === 'EPERM') { + try { + chmodSync(path, 0o666); + } + catch (er2) { + const fer2 = er2; + if (fer2?.code === 'ENOENT') { + return; + } + throw er; + } + return fn(path); + } + throw er; + } +}; +//# sourceMappingURL=fix-eperm.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/fix-eperm.js.map b/node_modules/rimraf/dist/esm/fix-eperm.js.map new file mode 100644 index 0000000..a6aa032 --- /dev/null +++ b/node_modules/rimraf/dist/esm/fix-eperm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fix-eperm.js","sourceRoot":"","sources":["../../src/fix-eperm.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAC7C,MAAM,EAAE,KAAK,EAAE,GAAG,QAAQ,CAAA;AAE1B,MAAM,CAAC,MAAM,QAAQ,GACnB,CAAC,EAAkC,EAAE,EAAE,CAAC,KAAK,EAAE,IAAY,EAAE,EAAE;IAC7D,IAAI,CAAC;QACH,OAAO,MAAM,EAAE,CAAC,IAAI,CAAC,CAAA;IACvB,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC3B,OAAM;QACR,CAAC;QACD,IAAI,GAAG,EAAE,IAAI,KAAK,OAAO,EAAE,CAAC;YAC1B,IAAI,CAAC;gBACH,MAAM,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;YAC1B,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,MAAM,IAAI,GAAG,GAA4B,CAAA;gBACzC,IAAI,IAAI,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;oBAC5B,OAAM;gBACR,CAAC;gBACD,MAAM,EAAE,CAAA;YACV,CAAC;YACD,OAAO,MAAM,EAAE,CAAC,IAAI,CAAC,CAAA;QACvB,CAAC;QACD,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAEH,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,EAAyB,EAAE,EAAE,CAAC,CAAC,IAAY,EAAE,EAAE;IAC1E,IAAI,CAAC;QACH,OAAO,EAAE,CAAC,IAAI,CAAC,CAAA;IACjB,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC3B,OAAM;QACR,CAAC;QACD,IAAI,GAAG,EAAE,IAAI,KAAK,OAAO,EAAE,CAAC;YAC1B,IAAI,CAAC;gBACH,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;YACxB,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,MAAM,IAAI,GAAG,GAA4B,CAAA;gBACzC,IAAI,IAAI,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;oBAC5B,OAAM;gBACR,CAAC;gBACD,MAAM,EAAE,CAAA;YACV,CAAC;YACD,OAAO,EAAE,CAAC,IAAI,CAAC,CAAA;QACjB,CAAC;QACD,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA","sourcesContent":["import { chmodSync, promises } from './fs.js'\nconst { chmod } = promises\n\nexport const fixEPERM =\n (fn: (path: string) => Promise) => async (path: string) => {\n try {\n return await fn(path)\n } catch (er) {\n const fer = er as NodeJS.ErrnoException\n if (fer?.code === 'ENOENT') {\n return\n }\n if (fer?.code === 'EPERM') {\n try {\n await chmod(path, 0o666)\n } catch (er2) {\n const fer2 = er2 as NodeJS.ErrnoException\n if (fer2?.code === 'ENOENT') {\n return\n }\n throw er\n }\n return await fn(path)\n }\n throw er\n }\n }\n\nexport const fixEPERMSync = (fn: (path: string) => any) => (path: string) => {\n try {\n return fn(path)\n } catch (er) {\n const fer = er as NodeJS.ErrnoException\n if (fer?.code === 'ENOENT') {\n return\n }\n if (fer?.code === 'EPERM') {\n try {\n chmodSync(path, 0o666)\n } catch (er2) {\n const fer2 = er2 as NodeJS.ErrnoException\n if (fer2?.code === 'ENOENT') {\n return\n }\n throw er\n }\n return fn(path)\n }\n throw er\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/fs.d.ts b/node_modules/rimraf/dist/esm/fs.d.ts new file mode 100644 index 0000000..9e4e95b --- /dev/null +++ b/node_modules/rimraf/dist/esm/fs.d.ts @@ -0,0 +1,17 @@ +import fs, { Dirent } from 'fs'; +export { chmodSync, mkdirSync, renameSync, rmdirSync, rmSync, statSync, lstatSync, unlinkSync, } from 'fs'; +export declare const readdirSync: (path: fs.PathLike) => Dirent[]; +export declare const promises: { + chmod: (path: fs.PathLike, mode: fs.Mode) => Promise; + mkdir: (path: fs.PathLike, options?: fs.Mode | (fs.MakeDirectoryOptions & { + recursive?: boolean | null; + }) | undefined | null) => Promise; + readdir: (path: fs.PathLike) => Promise; + rename: (oldPath: fs.PathLike, newPath: fs.PathLike) => Promise; + rm: (path: fs.PathLike, options: fs.RmOptions) => Promise; + rmdir: (path: fs.PathLike) => Promise; + stat: (path: fs.PathLike) => Promise; + lstat: (path: fs.PathLike) => Promise; + unlink: (path: fs.PathLike) => Promise; +}; +//# sourceMappingURL=fs.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/fs.d.ts.map b/node_modules/rimraf/dist/esm/fs.d.ts.map new file mode 100644 index 0000000..8c8b103 --- /dev/null +++ b/node_modules/rimraf/dist/esm/fs.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fs.d.ts","sourceRoot":"","sources":["../../src/fs.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,IAAI,CAAA;AAG/B,OAAO,EACL,SAAS,EACT,SAAS,EACT,UAAU,EACV,SAAS,EACT,MAAM,EACN,QAAQ,EACR,SAAS,EACT,UAAU,GACX,MAAM,IAAI,CAAA;AAGX,eAAO,MAAM,WAAW,SAAU,EAAE,CAAC,QAAQ,KAAG,MAAM,EACf,CAAA;AA+DvC,eAAO,MAAM,QAAQ;kBAxDA,EAAE,CAAC,QAAQ,QAAQ,EAAE,CAAC,IAAI,KAAG,OAAO,CAAC,IAAI,CAAC;kBAMvD,EAAE,CAAC,QAAQ,YAEb,EAAE,CAAC,IAAI,GACP,CAAC,EAAE,CAAC,oBAAoB,GAAG;QAAE,SAAS,CAAC,EAAE,OAAO,GAAG,IAAI,CAAA;KAAE,CAAC,GAC1D,SAAS,GACT,IAAI,KACP,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;oBAKP,EAAE,CAAC,QAAQ,KAAG,OAAO,CAAC,MAAM,EAAE,CAAC;sBAO7B,EAAE,CAAC,QAAQ,WAAW,EAAE,CAAC,QAAQ,KAAG,OAAO,CAAC,IAAI,CAAC;eAOxD,EAAE,CAAC,QAAQ,WAAW,EAAE,CAAC,SAAS,KAAG,OAAO,CAAC,IAAI,CAAC;kBAK/C,EAAE,CAAC,QAAQ,KAAG,OAAO,CAAC,IAAI,CAAC;iBAK5B,EAAE,CAAC,QAAQ,KAAG,OAAO,CAAC,EAAE,CAAC,KAAK,CAAC;kBAK9B,EAAE,CAAC,QAAQ,KAAG,OAAO,CAAC,EAAE,CAAC,KAAK,CAAC;mBAK9B,EAAE,CAAC,QAAQ,KAAG,OAAO,CAAC,IAAI,CAAC;CAehD,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/fs.js b/node_modules/rimraf/dist/esm/fs.js new file mode 100644 index 0000000..f9422ce --- /dev/null +++ b/node_modules/rimraf/dist/esm/fs.js @@ -0,0 +1,31 @@ +// promisify ourselves, because older nodes don't have fs.promises +import fs from 'fs'; +// sync ones just take the sync version from node +export { chmodSync, mkdirSync, renameSync, rmdirSync, rmSync, statSync, lstatSync, unlinkSync, } from 'fs'; +import { readdirSync as rdSync } from 'fs'; +export const readdirSync = (path) => rdSync(path, { withFileTypes: true }); +// unrolled for better inlining, this seems to get better performance +// than something like: +// const makeCb = (res, rej) => (er, ...d) => er ? rej(er) : res(...d) +// which would be a bit cleaner. +const chmod = (path, mode) => new Promise((res, rej) => fs.chmod(path, mode, (er, ...d) => (er ? rej(er) : res(...d)))); +const mkdir = (path, options) => new Promise((res, rej) => fs.mkdir(path, options, (er, made) => (er ? rej(er) : res(made)))); +const readdir = (path) => new Promise((res, rej) => fs.readdir(path, { withFileTypes: true }, (er, data) => er ? rej(er) : res(data))); +const rename = (oldPath, newPath) => new Promise((res, rej) => fs.rename(oldPath, newPath, (er, ...d) => er ? rej(er) : res(...d))); +const rm = (path, options) => new Promise((res, rej) => fs.rm(path, options, (er, ...d) => (er ? rej(er) : res(...d)))); +const rmdir = (path) => new Promise((res, rej) => fs.rmdir(path, (er, ...d) => (er ? rej(er) : res(...d)))); +const stat = (path) => new Promise((res, rej) => fs.stat(path, (er, data) => (er ? rej(er) : res(data)))); +const lstat = (path) => new Promise((res, rej) => fs.lstat(path, (er, data) => (er ? rej(er) : res(data)))); +const unlink = (path) => new Promise((res, rej) => fs.unlink(path, (er, ...d) => (er ? rej(er) : res(...d)))); +export const promises = { + chmod, + mkdir, + readdir, + rename, + rm, + rmdir, + stat, + lstat, + unlink, +}; +//# sourceMappingURL=fs.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/fs.js.map b/node_modules/rimraf/dist/esm/fs.js.map new file mode 100644 index 0000000..c4c5d0f --- /dev/null +++ b/node_modules/rimraf/dist/esm/fs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fs.js","sourceRoot":"","sources":["../../src/fs.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAElE,OAAO,EAAc,MAAM,IAAI,CAAA;AAE/B,iDAAiD;AACjD,OAAO,EACL,SAAS,EACT,SAAS,EACT,UAAU,EACV,SAAS,EACT,MAAM,EACN,QAAQ,EACR,SAAS,EACT,UAAU,GACX,MAAM,IAAI,CAAA;AAEX,OAAO,EAAE,WAAW,IAAI,MAAM,EAAE,MAAM,IAAI,CAAA;AAC1C,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,IAAiB,EAAY,EAAE,CACzD,MAAM,CAAC,IAAI,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,CAAA;AAEvC,qEAAqE;AACrE,uBAAuB;AACvB,sEAAsE;AACtE,gCAAgC;AAEhC,MAAM,KAAK,GAAG,CAAC,IAAiB,EAAE,IAAa,EAAiB,EAAE,CAChE,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE,GAAG,CAAQ,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CACtE,CAAA;AAEH,MAAM,KAAK,GAAG,CACZ,IAAiB,EACjB,OAIQ,EACqB,EAAE,CAC/B,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAClE,CAAA;AAEH,MAAM,OAAO,GAAG,CAAC,IAAiB,EAAqB,EAAE,CACvD,IAAI,OAAO,CAAW,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACjC,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,CACrD,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CACzB,CACF,CAAA;AAEH,MAAM,MAAM,GAAG,CAAC,OAAoB,EAAE,OAAoB,EAAiB,EAAE,CAC3E,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,EAAE,CAAC,MAAM,CAAC,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,GAAG,CAAQ,EAAE,EAAE,CAC9C,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CACzB,CACF,CAAA;AAEH,MAAM,EAAE,GAAG,CAAC,IAAiB,EAAE,OAAqB,EAAiB,EAAE,CACrE,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,EAAE,CAAC,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,GAAG,CAAQ,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CACtE,CAAA;AAEH,MAAM,KAAK,GAAG,CAAC,IAAiB,EAAiB,EAAE,CACjD,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,GAAG,CAAQ,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAChE,CAAA;AAEH,MAAM,IAAI,GAAG,CAAC,IAAiB,EAAqB,EAAE,CACpD,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CACxD,CAAA;AAEH,MAAM,KAAK,GAAG,CAAC,IAAiB,EAAqB,EAAE,CACrD,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CACzD,CAAA;AAEH,MAAM,MAAM,GAAG,CAAC,IAAiB,EAAiB,EAAE,CAClD,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CACvB,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,GAAG,CAAQ,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CACjE,CAAA;AAEH,MAAM,CAAC,MAAM,QAAQ,GAAG;IACtB,KAAK;IACL,KAAK;IACL,OAAO;IACP,MAAM;IACN,EAAE;IACF,KAAK;IACL,IAAI;IACJ,KAAK;IACL,MAAM;CACP,CAAA","sourcesContent":["// promisify ourselves, because older nodes don't have fs.promises\n\nimport fs, { Dirent } from 'fs'\n\n// sync ones just take the sync version from node\nexport {\n chmodSync,\n mkdirSync,\n renameSync,\n rmdirSync,\n rmSync,\n statSync,\n lstatSync,\n unlinkSync,\n} from 'fs'\n\nimport { readdirSync as rdSync } from 'fs'\nexport const readdirSync = (path: fs.PathLike): Dirent[] =>\n rdSync(path, { withFileTypes: true })\n\n// unrolled for better inlining, this seems to get better performance\n// than something like:\n// const makeCb = (res, rej) => (er, ...d) => er ? rej(er) : res(...d)\n// which would be a bit cleaner.\n\nconst chmod = (path: fs.PathLike, mode: fs.Mode): Promise =>\n new Promise((res, rej) =>\n fs.chmod(path, mode, (er, ...d: any[]) => (er ? rej(er) : res(...d))),\n )\n\nconst mkdir = (\n path: fs.PathLike,\n options?:\n | fs.Mode\n | (fs.MakeDirectoryOptions & { recursive?: boolean | null })\n | undefined\n | null,\n): Promise =>\n new Promise((res, rej) =>\n fs.mkdir(path, options, (er, made) => (er ? rej(er) : res(made))),\n )\n\nconst readdir = (path: fs.PathLike): Promise =>\n new Promise((res, rej) =>\n fs.readdir(path, { withFileTypes: true }, (er, data) =>\n er ? rej(er) : res(data),\n ),\n )\n\nconst rename = (oldPath: fs.PathLike, newPath: fs.PathLike): Promise =>\n new Promise((res, rej) =>\n fs.rename(oldPath, newPath, (er, ...d: any[]) =>\n er ? rej(er) : res(...d),\n ),\n )\n\nconst rm = (path: fs.PathLike, options: fs.RmOptions): Promise =>\n new Promise((res, rej) =>\n fs.rm(path, options, (er, ...d: any[]) => (er ? rej(er) : res(...d))),\n )\n\nconst rmdir = (path: fs.PathLike): Promise =>\n new Promise((res, rej) =>\n fs.rmdir(path, (er, ...d: any[]) => (er ? rej(er) : res(...d))),\n )\n\nconst stat = (path: fs.PathLike): Promise =>\n new Promise((res, rej) =>\n fs.stat(path, (er, data) => (er ? rej(er) : res(data))),\n )\n\nconst lstat = (path: fs.PathLike): Promise =>\n new Promise((res, rej) =>\n fs.lstat(path, (er, data) => (er ? rej(er) : res(data))),\n )\n\nconst unlink = (path: fs.PathLike): Promise =>\n new Promise((res, rej) =>\n fs.unlink(path, (er, ...d: any[]) => (er ? rej(er) : res(...d))),\n )\n\nexport const promises = {\n chmod,\n mkdir,\n readdir,\n rename,\n rm,\n rmdir,\n stat,\n lstat,\n unlink,\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/ignore-enoent.d.ts b/node_modules/rimraf/dist/esm/ignore-enoent.d.ts new file mode 100644 index 0000000..f158cc2 --- /dev/null +++ b/node_modules/rimraf/dist/esm/ignore-enoent.d.ts @@ -0,0 +1,3 @@ +export declare const ignoreENOENT: (p: Promise) => Promise; +export declare const ignoreENOENTSync: (fn: () => any) => any; +//# sourceMappingURL=ignore-enoent.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/ignore-enoent.d.ts.map b/node_modules/rimraf/dist/esm/ignore-enoent.d.ts.map new file mode 100644 index 0000000..2cfb3bb --- /dev/null +++ b/node_modules/rimraf/dist/esm/ignore-enoent.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ignore-enoent.d.ts","sourceRoot":"","sources":["../../src/ignore-enoent.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,YAAY,MAAa,OAAO,CAAC,GAAG,CAAC,iBAK9C,CAAA;AAEJ,eAAO,MAAM,gBAAgB,OAAQ,MAAM,GAAG,QAQ7C,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/ignore-enoent.js b/node_modules/rimraf/dist/esm/ignore-enoent.js new file mode 100644 index 0000000..753f481 --- /dev/null +++ b/node_modules/rimraf/dist/esm/ignore-enoent.js @@ -0,0 +1,16 @@ +export const ignoreENOENT = async (p) => p.catch(er => { + if (er.code !== 'ENOENT') { + throw er; + } +}); +export const ignoreENOENTSync = (fn) => { + try { + return fn(); + } + catch (er) { + if (er?.code !== 'ENOENT') { + throw er; + } + } +}; +//# sourceMappingURL=ignore-enoent.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/ignore-enoent.js.map b/node_modules/rimraf/dist/esm/ignore-enoent.js.map new file mode 100644 index 0000000..acffb14 --- /dev/null +++ b/node_modules/rimraf/dist/esm/ignore-enoent.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ignore-enoent.js","sourceRoot":"","sources":["../../src/ignore-enoent.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,YAAY,GAAG,KAAK,EAAE,CAAe,EAAE,EAAE,CACpD,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE;IACX,IAAI,EAAE,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QACzB,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAC,CAAA;AAEJ,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,EAAa,EAAE,EAAE;IAChD,IAAI,CAAC;QACH,OAAO,EAAE,EAAE,CAAA;IACb,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,IAAK,EAA4B,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;YACrD,MAAM,EAAE,CAAA;QACV,CAAC;IACH,CAAC;AACH,CAAC,CAAA","sourcesContent":["export const ignoreENOENT = async (p: Promise) =>\n p.catch(er => {\n if (er.code !== 'ENOENT') {\n throw er\n }\n })\n\nexport const ignoreENOENTSync = (fn: () => any) => {\n try {\n return fn()\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code !== 'ENOENT') {\n throw er\n }\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/index.d.ts b/node_modules/rimraf/dist/esm/index.d.ts new file mode 100644 index 0000000..9ec4a12 --- /dev/null +++ b/node_modules/rimraf/dist/esm/index.d.ts @@ -0,0 +1,50 @@ +import { RimrafAsyncOptions, RimrafSyncOptions } from './opt-arg.js'; +export { assertRimrafOptions, isRimrafOptions, type RimrafAsyncOptions, type RimrafOptions, type RimrafSyncOptions, } from './opt-arg.js'; +export declare const nativeSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +export declare const native: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +}; +export declare const manualSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +export declare const manual: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +}; +export declare const windowsSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +export declare const windows: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +}; +export declare const posixSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +export declare const posix: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +}; +export declare const moveRemoveSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +export declare const moveRemove: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +}; +export declare const rimrafSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +export declare const sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +export declare const rimraf: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + rimraf: (path: string | string[], opt?: RimrafAsyncOptions) => Promise; + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + rimrafSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + manual: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + }; + manualSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + native: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + }; + nativeSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + posix: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + }; + posixSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + windows: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + }; + windowsSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + moveRemove: ((path: string | string[], opt?: RimrafAsyncOptions) => Promise) & { + sync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; + }; + moveRemoveSync: (path: string | string[], opt?: RimrafSyncOptions) => boolean; +}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/index.d.ts.map b/node_modules/rimraf/dist/esm/index.d.ts.map new file mode 100644 index 0000000..0dc659c --- /dev/null +++ b/node_modules/rimraf/dist/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,kBAAkB,EAClB,iBAAiB,EAClB,MAAM,cAAc,CAAA;AASrB,OAAO,EACL,mBAAmB,EACnB,eAAe,EACf,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,KAAK,iBAAiB,GACvB,MAAM,cAAc,CAAA;AAqCrB,eAAO,MAAM,UAAU,SAdd,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAcF,CAAA;AACpD,eAAO,MAAM,MAAM,UAjCT,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;iBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;CAegB,CAAA;AAE7E,eAAO,MAAM,UAAU,SAjBd,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAiBF,CAAA;AACpD,eAAO,MAAM,MAAM,UApCT,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;iBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;CAkBgB,CAAA;AAE7E,eAAO,MAAM,WAAW,SApBf,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAoBA,CAAA;AACtD,eAAO,MAAM,OAAO,UAvCV,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;iBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;CAqBmB,CAAA;AAEhF,eAAO,MAAM,SAAS,SAvBb,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAuBJ,CAAA;AAClD,eAAO,MAAM,KAAK,UA1CR,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;iBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;CAwBa,CAAA;AAE1E,eAAO,MAAM,cAAc,SA1BlB,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OA0BM,CAAA;AAC5D,eAAO,MAAM,UAAU,UA7Cb,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;iBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;CA6B3D,CAAA;AAEF,eAAO,MAAM,UAAU,SA/Bd,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAmCrD,CAAA;AACD,eAAO,MAAM,IAAI,SApCR,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAoCxB,CAAA;AAK9B,eAAO,MAAM,MAAM,UA3DT,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;mBAFX,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;iBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;uBAApD,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;oBAlBnD,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;qBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;;uBAApD,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;oBAlBnD,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;qBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;;uBAApD,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;mBAlBnD,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;qBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;;sBAApD,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;qBAlBnD,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;qBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;;wBAApD,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;wBAlBnD,MAAM,GAAG,MAAM,EAAE,QACjB,kBAAkB,KACvB,OAAO,CAAC,OAAO,CAAC;qBAgBZ,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;;2BAApD,MAAM,GAAG,MAAM,EAAE,QAAQ,iBAAiB,KAAG,OAAO;CAuD3D,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/index.js b/node_modules/rimraf/dist/esm/index.js new file mode 100644 index 0000000..d94d6f8 --- /dev/null +++ b/node_modules/rimraf/dist/esm/index.js @@ -0,0 +1,70 @@ +import { glob, globSync } from 'glob'; +import { optArg, optArgSync, } from './opt-arg.js'; +import pathArg from './path-arg.js'; +import { rimrafManual, rimrafManualSync } from './rimraf-manual.js'; +import { rimrafMoveRemove, rimrafMoveRemoveSync } from './rimraf-move-remove.js'; +import { rimrafNative, rimrafNativeSync } from './rimraf-native.js'; +import { rimrafPosix, rimrafPosixSync } from './rimraf-posix.js'; +import { rimrafWindows, rimrafWindowsSync } from './rimraf-windows.js'; +import { useNative, useNativeSync } from './use-native.js'; +export { assertRimrafOptions, isRimrafOptions, } from './opt-arg.js'; +const wrap = (fn) => async (path, opt) => { + const options = optArg(opt); + if (options.glob) { + path = await glob(path, options.glob); + } + if (Array.isArray(path)) { + return !!(await Promise.all(path.map(p => fn(pathArg(p, options), options)))).reduce((a, b) => a && b, true); + } + else { + return !!(await fn(pathArg(path, options), options)); + } +}; +const wrapSync = (fn) => (path, opt) => { + const options = optArgSync(opt); + if (options.glob) { + path = globSync(path, options.glob); + } + if (Array.isArray(path)) { + return !!path + .map(p => fn(pathArg(p, options), options)) + .reduce((a, b) => a && b, true); + } + else { + return !!fn(pathArg(path, options), options); + } +}; +export const nativeSync = wrapSync(rimrafNativeSync); +export const native = Object.assign(wrap(rimrafNative), { sync: nativeSync }); +export const manualSync = wrapSync(rimrafManualSync); +export const manual = Object.assign(wrap(rimrafManual), { sync: manualSync }); +export const windowsSync = wrapSync(rimrafWindowsSync); +export const windows = Object.assign(wrap(rimrafWindows), { sync: windowsSync }); +export const posixSync = wrapSync(rimrafPosixSync); +export const posix = Object.assign(wrap(rimrafPosix), { sync: posixSync }); +export const moveRemoveSync = wrapSync(rimrafMoveRemoveSync); +export const moveRemove = Object.assign(wrap(rimrafMoveRemove), { + sync: moveRemoveSync, +}); +export const rimrafSync = wrapSync((path, opt) => useNativeSync(opt) ? + rimrafNativeSync(path, opt) + : rimrafManualSync(path, opt)); +export const sync = rimrafSync; +const rimraf_ = wrap((path, opt) => useNative(opt) ? rimrafNative(path, opt) : rimrafManual(path, opt)); +export const rimraf = Object.assign(rimraf_, { + rimraf: rimraf_, + sync: rimrafSync, + rimrafSync: rimrafSync, + manual, + manualSync, + native, + nativeSync, + posix, + posixSync, + windows, + windowsSync, + moveRemove, + moveRemoveSync, +}); +rimraf.rimraf = rimraf; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/index.js.map b/node_modules/rimraf/dist/esm/index.js.map new file mode 100644 index 0000000..0c8ca64 --- /dev/null +++ b/node_modules/rimraf/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,MAAM,CAAA;AACrC,OAAO,EACL,MAAM,EACN,UAAU,GAGX,MAAM,cAAc,CAAA;AACrB,OAAO,OAAO,MAAM,eAAe,CAAA;AACnC,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAA;AAChF,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAChE,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAA;AACtE,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAE1D,OAAO,EACL,mBAAmB,EACnB,eAAe,GAIhB,MAAM,cAAc,CAAA;AAErB,MAAM,IAAI,GACR,CAAC,EAA0D,EAAE,EAAE,CAC/D,KAAK,EACH,IAAuB,EACvB,GAAwB,EACN,EAAE;IACpB,MAAM,OAAO,GAAG,MAAM,CAAC,GAAG,CAAC,CAAA;IAC3B,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,IAAI,GAAG,MAAM,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,CAAA;IACvC,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;QACxB,OAAO,CAAC,CAAC,CACP,MAAM,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CACnE,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAA;IAClC,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,CAAA;IACtD,CAAC;AACH,CAAC,CAAA;AAEH,MAAM,QAAQ,GACZ,CAAC,EAAgD,EAAE,EAAE,CACrD,CAAC,IAAuB,EAAE,GAAuB,EAAW,EAAE;IAC5D,MAAM,OAAO,GAAG,UAAU,CAAC,GAAG,CAAC,CAAA;IAC/B,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,IAAI,GAAG,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,CAAA;IACrC,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;QACxB,OAAO,CAAC,CAAC,IAAI;aACV,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC;aAC1C,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAA;IACnC,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAA;IAC9C,CAAC;AACH,CAAC,CAAA;AAEH,MAAM,CAAC,MAAM,UAAU,GAAG,QAAQ,CAAC,gBAAgB,CAAC,CAAA;AACpD,MAAM,CAAC,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAA;AAE7E,MAAM,CAAC,MAAM,UAAU,GAAG,QAAQ,CAAC,gBAAgB,CAAC,CAAA;AACpD,MAAM,CAAC,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAA;AAE7E,MAAM,CAAC,MAAM,WAAW,GAAG,QAAQ,CAAC,iBAAiB,CAAC,CAAA;AACtD,MAAM,CAAC,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC,CAAA;AAEhF,MAAM,CAAC,MAAM,SAAS,GAAG,QAAQ,CAAC,eAAe,CAAC,CAAA;AAClD,MAAM,CAAC,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,CAAA;AAE1E,MAAM,CAAC,MAAM,cAAc,GAAG,QAAQ,CAAC,oBAAoB,CAAC,CAAA;AAC5D,MAAM,CAAC,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,gBAAgB,CAAC,EAAE;IAC9D,IAAI,EAAE,cAAc;CACrB,CAAC,CAAA;AAEF,MAAM,CAAC,MAAM,UAAU,GAAG,QAAQ,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,CAC/C,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC;IAClB,gBAAgB,CAAC,IAAI,EAAE,GAAG,CAAC;IAC7B,CAAC,CAAC,gBAAgB,CAAC,IAAI,EAAE,GAAG,CAAC,CAC9B,CAAA;AACD,MAAM,CAAC,MAAM,IAAI,GAAG,UAAU,CAAA;AAE9B,MAAM,OAAO,GAAG,IAAI,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,CACjC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,EAAE,GAAG,CAAC,CACnE,CAAA;AACD,MAAM,CAAC,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE;IAC3C,MAAM,EAAE,OAAO;IACf,IAAI,EAAE,UAAU;IAChB,UAAU,EAAE,UAAU;IACtB,MAAM;IACN,UAAU;IACV,MAAM;IACN,UAAU;IACV,KAAK;IACL,SAAS;IACT,OAAO;IACP,WAAW;IACX,UAAU;IACV,cAAc;CACf,CAAC,CAAA;AACF,MAAM,CAAC,MAAM,GAAG,MAAM,CAAA","sourcesContent":["import { glob, globSync } from 'glob'\nimport {\n optArg,\n optArgSync,\n RimrafAsyncOptions,\n RimrafSyncOptions,\n} from './opt-arg.js'\nimport pathArg from './path-arg.js'\nimport { rimrafManual, rimrafManualSync } from './rimraf-manual.js'\nimport { rimrafMoveRemove, rimrafMoveRemoveSync } from './rimraf-move-remove.js'\nimport { rimrafNative, rimrafNativeSync } from './rimraf-native.js'\nimport { rimrafPosix, rimrafPosixSync } from './rimraf-posix.js'\nimport { rimrafWindows, rimrafWindowsSync } from './rimraf-windows.js'\nimport { useNative, useNativeSync } from './use-native.js'\n\nexport {\n assertRimrafOptions,\n isRimrafOptions,\n type RimrafAsyncOptions,\n type RimrafOptions,\n type RimrafSyncOptions,\n} from './opt-arg.js'\n\nconst wrap =\n (fn: (p: string, o: RimrafAsyncOptions) => Promise) =>\n async (\n path: string | string[],\n opt?: RimrafAsyncOptions,\n ): Promise => {\n const options = optArg(opt)\n if (options.glob) {\n path = await glob(path, options.glob)\n }\n if (Array.isArray(path)) {\n return !!(\n await Promise.all(path.map(p => fn(pathArg(p, options), options)))\n ).reduce((a, b) => a && b, true)\n } else {\n return !!(await fn(pathArg(path, options), options))\n }\n }\n\nconst wrapSync =\n (fn: (p: string, o: RimrafSyncOptions) => boolean) =>\n (path: string | string[], opt?: RimrafSyncOptions): boolean => {\n const options = optArgSync(opt)\n if (options.glob) {\n path = globSync(path, options.glob)\n }\n if (Array.isArray(path)) {\n return !!path\n .map(p => fn(pathArg(p, options), options))\n .reduce((a, b) => a && b, true)\n } else {\n return !!fn(pathArg(path, options), options)\n }\n }\n\nexport const nativeSync = wrapSync(rimrafNativeSync)\nexport const native = Object.assign(wrap(rimrafNative), { sync: nativeSync })\n\nexport const manualSync = wrapSync(rimrafManualSync)\nexport const manual = Object.assign(wrap(rimrafManual), { sync: manualSync })\n\nexport const windowsSync = wrapSync(rimrafWindowsSync)\nexport const windows = Object.assign(wrap(rimrafWindows), { sync: windowsSync })\n\nexport const posixSync = wrapSync(rimrafPosixSync)\nexport const posix = Object.assign(wrap(rimrafPosix), { sync: posixSync })\n\nexport const moveRemoveSync = wrapSync(rimrafMoveRemoveSync)\nexport const moveRemove = Object.assign(wrap(rimrafMoveRemove), {\n sync: moveRemoveSync,\n})\n\nexport const rimrafSync = wrapSync((path, opt) =>\n useNativeSync(opt) ?\n rimrafNativeSync(path, opt)\n : rimrafManualSync(path, opt),\n)\nexport const sync = rimrafSync\n\nconst rimraf_ = wrap((path, opt) =>\n useNative(opt) ? rimrafNative(path, opt) : rimrafManual(path, opt),\n)\nexport const rimraf = Object.assign(rimraf_, {\n rimraf: rimraf_,\n sync: rimrafSync,\n rimrafSync: rimrafSync,\n manual,\n manualSync,\n native,\n nativeSync,\n posix,\n posixSync,\n windows,\n windowsSync,\n moveRemove,\n moveRemoveSync,\n})\nrimraf.rimraf = rimraf\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/opt-arg.d.ts b/node_modules/rimraf/dist/esm/opt-arg.d.ts new file mode 100644 index 0000000..c869d4a --- /dev/null +++ b/node_modules/rimraf/dist/esm/opt-arg.d.ts @@ -0,0 +1,34 @@ +import { Dirent, Stats } from 'fs'; +import { GlobOptions } from 'glob'; +export declare const isRimrafOptions: (o: any) => o is RimrafOptions; +export declare const assertRimrafOptions: (o: any) => void; +export interface RimrafAsyncOptions { + preserveRoot?: boolean; + tmp?: string; + maxRetries?: number; + retryDelay?: number; + backoff?: number; + maxBackoff?: number; + signal?: AbortSignal; + glob?: boolean | GlobOptions; + filter?: ((path: string, ent: Dirent | Stats) => boolean) | ((path: string, ent: Dirent | Stats) => Promise); +} +export interface RimrafSyncOptions extends RimrafAsyncOptions { + filter?: (path: string, ent: Dirent | Stats) => boolean; +} +export type RimrafOptions = RimrafSyncOptions | RimrafAsyncOptions; +export declare const optArg: (opt?: RimrafAsyncOptions) => (RimrafAsyncOptions & { + glob: GlobOptions & { + withFileTypes: false; + }; +}) | (RimrafAsyncOptions & { + glob: undefined; +}); +export declare const optArgSync: (opt?: RimrafSyncOptions) => (RimrafSyncOptions & { + glob: GlobOptions & { + withFileTypes: false; + }; +}) | (RimrafSyncOptions & { + glob: undefined; +}); +//# sourceMappingURL=opt-arg.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/opt-arg.d.ts.map b/node_modules/rimraf/dist/esm/opt-arg.d.ts.map new file mode 100644 index 0000000..89e83b2 --- /dev/null +++ b/node_modules/rimraf/dist/esm/opt-arg.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"opt-arg.d.ts","sourceRoot":"","sources":["../../src/opt-arg.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,IAAI,CAAA;AAClC,OAAO,EAAE,WAAW,EAAE,MAAM,MAAM,CAAA;AAKlC,eAAO,MAAM,eAAe,MAAO,GAAG,KAAG,CAAC,IAAI,aAUX,CAAA;AAEnC,eAAO,MAAM,mBAAmB,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,IAM7C,CAAA;AAED,MAAM,WAAW,kBAAkB;IACjC,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,IAAI,CAAC,EAAE,OAAO,GAAG,WAAW,CAAA;IAC5B,MAAM,CAAC,EACH,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,KAAK,KAAK,OAAO,CAAC,GAChD,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,KAAK,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC,CAAA;CAC9D;AAED,MAAM,WAAW,iBAAkB,SAAQ,kBAAkB;IAC3D,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,KAAK,KAAK,OAAO,CAAA;CACxD;AAED,MAAM,MAAM,aAAa,GAAG,iBAAiB,GAAG,kBAAkB,CAAA;AAqClE,eAAO,MAAM,MAAM,SAAS,kBAAkB;UA/BlC,WAAW,GAAG;QAAE,aAAa,EAAE,KAAK,CAAA;KAAE;;UAEjC,SAAS;EA6B0C,CAAA;AACpE,eAAO,MAAM,UAAU,SAAS,iBAAiB;UAhCrC,WAAW,GAAG;QAAE,aAAa,EAAE,KAAK,CAAA;KAAE;;UAEjC,SAAS;EA8B6C,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/opt-arg.js b/node_modules/rimraf/dist/esm/opt-arg.js new file mode 100644 index 0000000..eacfe6c --- /dev/null +++ b/node_modules/rimraf/dist/esm/opt-arg.js @@ -0,0 +1,46 @@ +const typeOrUndef = (val, t) => typeof val === 'undefined' || typeof val === t; +export const isRimrafOptions = (o) => !!o && + typeof o === 'object' && + typeOrUndef(o.preserveRoot, 'boolean') && + typeOrUndef(o.tmp, 'string') && + typeOrUndef(o.maxRetries, 'number') && + typeOrUndef(o.retryDelay, 'number') && + typeOrUndef(o.backoff, 'number') && + typeOrUndef(o.maxBackoff, 'number') && + (typeOrUndef(o.glob, 'boolean') || (o.glob && typeof o.glob === 'object')) && + typeOrUndef(o.filter, 'function'); +export const assertRimrafOptions = (o) => { + if (!isRimrafOptions(o)) { + throw new Error('invalid rimraf options'); + } +}; +const optArgT = (opt) => { + assertRimrafOptions(opt); + const { glob, ...options } = opt; + if (!glob) { + return options; + } + const globOpt = glob === true ? + opt.signal ? + { signal: opt.signal } + : {} + : opt.signal ? + { + signal: opt.signal, + ...glob, + } + : glob; + return { + ...options, + glob: { + ...globOpt, + // always get absolute paths from glob, to ensure + // that we are referencing the correct thing. + absolute: true, + withFileTypes: false, + }, + }; +}; +export const optArg = (opt = {}) => optArgT(opt); +export const optArgSync = (opt = {}) => optArgT(opt); +//# sourceMappingURL=opt-arg.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/opt-arg.js.map b/node_modules/rimraf/dist/esm/opt-arg.js.map new file mode 100644 index 0000000..82ff94f --- /dev/null +++ b/node_modules/rimraf/dist/esm/opt-arg.js.map @@ -0,0 +1 @@ +{"version":3,"file":"opt-arg.js","sourceRoot":"","sources":["../../src/opt-arg.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,GAAG,CAAC,GAAQ,EAAE,CAAS,EAAE,EAAE,CAC1C,OAAO,GAAG,KAAK,WAAW,IAAI,OAAO,GAAG,KAAK,CAAC,CAAA;AAEhD,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,CAAM,EAAsB,EAAE,CAC5D,CAAC,CAAC,CAAC;IACH,OAAO,CAAC,KAAK,QAAQ;IACrB,WAAW,CAAC,CAAC,CAAC,YAAY,EAAE,SAAS,CAAC;IACtC,WAAW,CAAC,CAAC,CAAC,GAAG,EAAE,QAAQ,CAAC;IAC5B,WAAW,CAAC,CAAC,CAAC,UAAU,EAAE,QAAQ,CAAC;IACnC,WAAW,CAAC,CAAC,CAAC,UAAU,EAAE,QAAQ,CAAC;IACnC,WAAW,CAAC,CAAC,CAAC,OAAO,EAAE,QAAQ,CAAC;IAChC,WAAW,CAAC,CAAC,CAAC,UAAU,EAAE,QAAQ,CAAC;IACnC,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,EAAE,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,OAAO,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC;IAC1E,WAAW,CAAC,CAAC,CAAC,MAAM,EAAE,UAAU,CAAC,CAAA;AAEnC,MAAM,CAAC,MAAM,mBAAmB,GAAqB,CACnD,CAAM,EACsB,EAAE;IAC9B,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAA;IAC3C,CAAC;AACH,CAAC,CAAA;AAsBD,MAAM,OAAO,GAAG,CACd,GAAM,EAKsB,EAAE;IAC9B,mBAAmB,CAAC,GAAG,CAAC,CAAA;IACxB,MAAM,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,GAAG,GAAG,CAAA;IAChC,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,OAAO,OAAkC,CAAA;IAC3C,CAAC;IACD,MAAM,OAAO,GACX,IAAI,KAAK,IAAI,CAAC,CAAC;QACb,GAAG,CAAC,MAAM,CAAC,CAAC;YACV,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE;YACxB,CAAC,CAAC,EAAE;QACN,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YACZ;gBACE,MAAM,EAAE,GAAG,CAAC,MAAM;gBAClB,GAAG,IAAI;aACR;YACH,CAAC,CAAC,IAAI,CAAA;IACR,OAAO;QACL,GAAG,OAAO;QACV,IAAI,EAAE;YACJ,GAAG,OAAO;YACV,iDAAiD;YACjD,6CAA6C;YAC7C,QAAQ,EAAE,IAAI;YACd,aAAa,EAAE,KAAK;SACrB;KACsD,CAAA;AAC3D,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,MAA0B,EAAE,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;AACpE,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,MAAyB,EAAE,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA","sourcesContent":["import { Dirent, Stats } from 'fs'\nimport { GlobOptions } from 'glob'\n\nconst typeOrUndef = (val: any, t: string) =>\n typeof val === 'undefined' || typeof val === t\n\nexport const isRimrafOptions = (o: any): o is RimrafOptions =>\n !!o &&\n typeof o === 'object' &&\n typeOrUndef(o.preserveRoot, 'boolean') &&\n typeOrUndef(o.tmp, 'string') &&\n typeOrUndef(o.maxRetries, 'number') &&\n typeOrUndef(o.retryDelay, 'number') &&\n typeOrUndef(o.backoff, 'number') &&\n typeOrUndef(o.maxBackoff, 'number') &&\n (typeOrUndef(o.glob, 'boolean') || (o.glob && typeof o.glob === 'object')) &&\n typeOrUndef(o.filter, 'function')\n\nexport const assertRimrafOptions: (o: any) => void = (\n o: any,\n): asserts o is RimrafOptions => {\n if (!isRimrafOptions(o)) {\n throw new Error('invalid rimraf options')\n }\n}\n\nexport interface RimrafAsyncOptions {\n preserveRoot?: boolean\n tmp?: string\n maxRetries?: number\n retryDelay?: number\n backoff?: number\n maxBackoff?: number\n signal?: AbortSignal\n glob?: boolean | GlobOptions\n filter?:\n | ((path: string, ent: Dirent | Stats) => boolean)\n | ((path: string, ent: Dirent | Stats) => Promise)\n}\n\nexport interface RimrafSyncOptions extends RimrafAsyncOptions {\n filter?: (path: string, ent: Dirent | Stats) => boolean\n}\n\nexport type RimrafOptions = RimrafSyncOptions | RimrafAsyncOptions\n\nconst optArgT = (\n opt: T,\n):\n | (T & {\n glob: GlobOptions & { withFileTypes: false }\n })\n | (T & { glob: undefined }) => {\n assertRimrafOptions(opt)\n const { glob, ...options } = opt\n if (!glob) {\n return options as T & { glob: undefined }\n }\n const globOpt =\n glob === true ?\n opt.signal ?\n { signal: opt.signal }\n : {}\n : opt.signal ?\n {\n signal: opt.signal,\n ...glob,\n }\n : glob\n return {\n ...options,\n glob: {\n ...globOpt,\n // always get absolute paths from glob, to ensure\n // that we are referencing the correct thing.\n absolute: true,\n withFileTypes: false,\n },\n } as T & { glob: GlobOptions & { withFileTypes: false } }\n}\n\nexport const optArg = (opt: RimrafAsyncOptions = {}) => optArgT(opt)\nexport const optArgSync = (opt: RimrafSyncOptions = {}) => optArgT(opt)\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/package.json b/node_modules/rimraf/dist/esm/package.json new file mode 100644 index 0000000..3dbc1ca --- /dev/null +++ b/node_modules/rimraf/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/rimraf/dist/esm/path-arg.d.ts b/node_modules/rimraf/dist/esm/path-arg.d.ts new file mode 100644 index 0000000..c0b7e7c --- /dev/null +++ b/node_modules/rimraf/dist/esm/path-arg.d.ts @@ -0,0 +1,4 @@ +import { RimrafAsyncOptions } from './index.js'; +declare const pathArg: (path: string, opt?: RimrafAsyncOptions) => string; +export default pathArg; +//# sourceMappingURL=path-arg.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/path-arg.d.ts.map b/node_modules/rimraf/dist/esm/path-arg.d.ts.map new file mode 100644 index 0000000..4fe93c3 --- /dev/null +++ b/node_modules/rimraf/dist/esm/path-arg.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"path-arg.d.ts","sourceRoot":"","sources":["../../src/path-arg.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAG/C,QAAA,MAAM,OAAO,SAAU,MAAM,QAAO,kBAAkB,WAgDrD,CAAA;AAED,eAAe,OAAO,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/path-arg.js b/node_modules/rimraf/dist/esm/path-arg.js new file mode 100644 index 0000000..f32cb10 --- /dev/null +++ b/node_modules/rimraf/dist/esm/path-arg.js @@ -0,0 +1,47 @@ +import { parse, resolve } from 'path'; +import { inspect } from 'util'; +import platform from './platform.js'; +const pathArg = (path, opt = {}) => { + const type = typeof path; + if (type !== 'string') { + const ctor = path && type === 'object' && path.constructor; + const received = ctor && ctor.name ? `an instance of ${ctor.name}` + : type === 'object' ? inspect(path) + : `type ${type} ${path}`; + const msg = 'The "path" argument must be of type string. ' + `Received ${received}`; + throw Object.assign(new TypeError(msg), { + path, + code: 'ERR_INVALID_ARG_TYPE', + }); + } + if (/\0/.test(path)) { + // simulate same failure that node raises + const msg = 'path must be a string without null bytes'; + throw Object.assign(new TypeError(msg), { + path, + code: 'ERR_INVALID_ARG_VALUE', + }); + } + path = resolve(path); + const { root } = parse(path); + if (path === root && opt.preserveRoot !== false) { + const msg = 'refusing to remove root directory without preserveRoot:false'; + throw Object.assign(new Error(msg), { + path, + code: 'ERR_PRESERVE_ROOT', + }); + } + if (platform === 'win32') { + const badWinChars = /[*|"<>?:]/; + const { root } = parse(path); + if (badWinChars.test(path.substring(root.length))) { + throw Object.assign(new Error('Illegal characters in path.'), { + path, + code: 'EINVAL', + }); + } + } + return path; +}; +export default pathArg; +//# sourceMappingURL=path-arg.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/path-arg.js.map b/node_modules/rimraf/dist/esm/path-arg.js.map new file mode 100644 index 0000000..2f73f5f --- /dev/null +++ b/node_modules/rimraf/dist/esm/path-arg.js.map @@ -0,0 +1 @@ +{"version":3,"file":"path-arg.js","sourceRoot":"","sources":["../../src/path-arg.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AACrC,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAE9B,OAAO,QAAQ,MAAM,eAAe,CAAA;AAEpC,MAAM,OAAO,GAAG,CAAC,IAAY,EAAE,MAA0B,EAAE,EAAE,EAAE;IAC7D,MAAM,IAAI,GAAG,OAAO,IAAI,CAAA;IACxB,IAAI,IAAI,KAAK,QAAQ,EAAE,CAAC;QACtB,MAAM,IAAI,GAAG,IAAI,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,WAAW,CAAA;QAC1D,MAAM,QAAQ,GACZ,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,kBAAkB,IAAI,CAAC,IAAI,EAAE;YACjD,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC;gBACnC,CAAC,CAAC,QAAQ,IAAI,IAAI,IAAI,EAAE,CAAA;QAC1B,MAAM,GAAG,GACP,8CAA8C,GAAG,YAAY,QAAQ,EAAE,CAAA;QACzE,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,SAAS,CAAC,GAAG,CAAC,EAAE;YACtC,IAAI;YACJ,IAAI,EAAE,sBAAsB;SAC7B,CAAC,CAAA;IACJ,CAAC;IAED,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACpB,yCAAyC;QACzC,MAAM,GAAG,GAAG,0CAA0C,CAAA;QACtD,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,SAAS,CAAC,GAAG,CAAC,EAAE;YACtC,IAAI;YACJ,IAAI,EAAE,uBAAuB;SAC9B,CAAC,CAAA;IACJ,CAAC;IAED,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACpB,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC,IAAI,CAAC,CAAA;IAE5B,IAAI,IAAI,KAAK,IAAI,IAAI,GAAG,CAAC,YAAY,KAAK,KAAK,EAAE,CAAC;QAChD,MAAM,GAAG,GAAG,8DAA8D,CAAA;QAC1E,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,GAAG,CAAC,EAAE;YAClC,IAAI;YACJ,IAAI,EAAE,mBAAmB;SAC1B,CAAC,CAAA;IACJ,CAAC;IAED,IAAI,QAAQ,KAAK,OAAO,EAAE,CAAC;QACzB,MAAM,WAAW,GAAG,WAAW,CAAA;QAC/B,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC,IAAI,CAAC,CAAA;QAC5B,IAAI,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC;YAClD,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,6BAA6B,CAAC,EAAE;gBAC5D,IAAI;gBACJ,IAAI,EAAE,QAAQ;aACf,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;IAED,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,eAAe,OAAO,CAAA","sourcesContent":["import { parse, resolve } from 'path'\nimport { inspect } from 'util'\nimport { RimrafAsyncOptions } from './index.js'\nimport platform from './platform.js'\n\nconst pathArg = (path: string, opt: RimrafAsyncOptions = {}) => {\n const type = typeof path\n if (type !== 'string') {\n const ctor = path && type === 'object' && path.constructor\n const received =\n ctor && ctor.name ? `an instance of ${ctor.name}`\n : type === 'object' ? inspect(path)\n : `type ${type} ${path}`\n const msg =\n 'The \"path\" argument must be of type string. ' + `Received ${received}`\n throw Object.assign(new TypeError(msg), {\n path,\n code: 'ERR_INVALID_ARG_TYPE',\n })\n }\n\n if (/\\0/.test(path)) {\n // simulate same failure that node raises\n const msg = 'path must be a string without null bytes'\n throw Object.assign(new TypeError(msg), {\n path,\n code: 'ERR_INVALID_ARG_VALUE',\n })\n }\n\n path = resolve(path)\n const { root } = parse(path)\n\n if (path === root && opt.preserveRoot !== false) {\n const msg = 'refusing to remove root directory without preserveRoot:false'\n throw Object.assign(new Error(msg), {\n path,\n code: 'ERR_PRESERVE_ROOT',\n })\n }\n\n if (platform === 'win32') {\n const badWinChars = /[*|\"<>?:]/\n const { root } = parse(path)\n if (badWinChars.test(path.substring(root.length))) {\n throw Object.assign(new Error('Illegal characters in path.'), {\n path,\n code: 'EINVAL',\n })\n }\n }\n\n return path\n}\n\nexport default pathArg\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/platform.d.ts b/node_modules/rimraf/dist/esm/platform.d.ts new file mode 100644 index 0000000..e127a8e --- /dev/null +++ b/node_modules/rimraf/dist/esm/platform.d.ts @@ -0,0 +1,3 @@ +declare const _default: string; +export default _default; +//# sourceMappingURL=platform.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/platform.d.ts.map b/node_modules/rimraf/dist/esm/platform.d.ts.map new file mode 100644 index 0000000..ef2e673 --- /dev/null +++ b/node_modules/rimraf/dist/esm/platform.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"platform.d.ts","sourceRoot":"","sources":["../../src/platform.ts"],"names":[],"mappings":";AAAA,wBAA0E"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/platform.js b/node_modules/rimraf/dist/esm/platform.js new file mode 100644 index 0000000..a264172 --- /dev/null +++ b/node_modules/rimraf/dist/esm/platform.js @@ -0,0 +1,2 @@ +export default process.env.__TESTING_RIMRAF_PLATFORM__ || process.platform; +//# sourceMappingURL=platform.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/platform.js.map b/node_modules/rimraf/dist/esm/platform.js.map new file mode 100644 index 0000000..c5fdaf9 --- /dev/null +++ b/node_modules/rimraf/dist/esm/platform.js.map @@ -0,0 +1 @@ +{"version":3,"file":"platform.js","sourceRoot":"","sources":["../../src/platform.ts"],"names":[],"mappings":"AAAA,eAAe,OAAO,CAAC,GAAG,CAAC,2BAA2B,IAAI,OAAO,CAAC,QAAQ,CAAA","sourcesContent":["export default process.env.__TESTING_RIMRAF_PLATFORM__ || process.platform\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/readdir-or-error.d.ts b/node_modules/rimraf/dist/esm/readdir-or-error.d.ts new file mode 100644 index 0000000..cce7309 --- /dev/null +++ b/node_modules/rimraf/dist/esm/readdir-or-error.d.ts @@ -0,0 +1,3 @@ +export declare const readdirOrError: (path: string) => Promise; +export declare const readdirOrErrorSync: (path: string) => import("fs").Dirent[] | NodeJS.ErrnoException; +//# sourceMappingURL=readdir-or-error.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/readdir-or-error.d.ts.map b/node_modules/rimraf/dist/esm/readdir-or-error.d.ts.map new file mode 100644 index 0000000..8a19f6b --- /dev/null +++ b/node_modules/rimraf/dist/esm/readdir-or-error.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"readdir-or-error.d.ts","sourceRoot":"","sources":["../../src/readdir-or-error.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,cAAc,SAAU,MAAM,2DACa,CAAA;AACxD,eAAO,MAAM,kBAAkB,SAAU,MAAM,kDAM9C,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/readdir-or-error.js b/node_modules/rimraf/dist/esm/readdir-or-error.js new file mode 100644 index 0000000..7123513 --- /dev/null +++ b/node_modules/rimraf/dist/esm/readdir-or-error.js @@ -0,0 +1,14 @@ +// returns an array of entries if readdir() works, +// or the error that readdir() raised if not. +import { promises, readdirSync } from './fs.js'; +const { readdir } = promises; +export const readdirOrError = (path) => readdir(path).catch(er => er); +export const readdirOrErrorSync = (path) => { + try { + return readdirSync(path); + } + catch (er) { + return er; + } +}; +//# sourceMappingURL=readdir-or-error.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/readdir-or-error.js.map b/node_modules/rimraf/dist/esm/readdir-or-error.js.map new file mode 100644 index 0000000..1d0c00e --- /dev/null +++ b/node_modules/rimraf/dist/esm/readdir-or-error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"readdir-or-error.js","sourceRoot":"","sources":["../../src/readdir-or-error.ts"],"names":[],"mappings":"AAAA,kDAAkD;AAClD,6CAA6C;AAC7C,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAC/C,MAAM,EAAE,OAAO,EAAE,GAAG,QAAQ,CAAA;AAC5B,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,IAAY,EAAE,EAAE,CAC7C,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,CAAC,EAA2B,CAAC,CAAA;AACxD,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,IAAY,EAAE,EAAE;IACjD,IAAI,CAAC;QACH,OAAO,WAAW,CAAC,IAAI,CAAC,CAAA;IAC1B,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,OAAO,EAA2B,CAAA;IACpC,CAAC;AACH,CAAC,CAAA","sourcesContent":["// returns an array of entries if readdir() works,\n// or the error that readdir() raised if not.\nimport { promises, readdirSync } from './fs.js'\nconst { readdir } = promises\nexport const readdirOrError = (path: string) =>\n readdir(path).catch(er => er as NodeJS.ErrnoException)\nexport const readdirOrErrorSync = (path: string) => {\n try {\n return readdirSync(path)\n } catch (er) {\n return er as NodeJS.ErrnoException\n }\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/retry-busy.d.ts b/node_modules/rimraf/dist/esm/retry-busy.d.ts new file mode 100644 index 0000000..c0af0dd --- /dev/null +++ b/node_modules/rimraf/dist/esm/retry-busy.d.ts @@ -0,0 +1,8 @@ +import { RimrafAsyncOptions, RimrafOptions } from './index.js'; +export declare const MAXBACKOFF = 200; +export declare const RATE = 1.2; +export declare const MAXRETRIES = 10; +export declare const codes: Set; +export declare const retryBusy: (fn: (path: string) => Promise) => (path: string, opt: RimrafAsyncOptions, backoff?: number, total?: number) => Promise; +export declare const retryBusySync: (fn: (path: string) => any) => (path: string, opt: RimrafOptions) => any; +//# sourceMappingURL=retry-busy.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/retry-busy.d.ts.map b/node_modules/rimraf/dist/esm/retry-busy.d.ts.map new file mode 100644 index 0000000..21960c5 --- /dev/null +++ b/node_modules/rimraf/dist/esm/retry-busy.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"retry-busy.d.ts","sourceRoot":"","sources":["../../src/retry-busy.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAE9D,eAAO,MAAM,UAAU,MAAM,CAAA;AAC7B,eAAO,MAAM,IAAI,MAAM,CAAA;AACvB,eAAO,MAAM,UAAU,KAAK,CAAA;AAC5B,eAAO,MAAM,KAAK,aAAyC,CAAA;AAE3D,eAAO,MAAM,SAAS,OAAQ,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,GAAG,CAAC,YAElD,MAAM,OACP,kBAAkB,mDAkC1B,CAAA;AAGD,eAAO,MAAM,aAAa,OAAQ,CAAC,IAAI,EAAE,MAAM,KAAK,GAAG,YAC/B,MAAM,OAAO,aAAa,QAsBjD,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/retry-busy.js b/node_modules/rimraf/dist/esm/retry-busy.js new file mode 100644 index 0000000..17e336a --- /dev/null +++ b/node_modules/rimraf/dist/esm/retry-busy.js @@ -0,0 +1,63 @@ +// note: max backoff is the maximum that any *single* backoff will do +export const MAXBACKOFF = 200; +export const RATE = 1.2; +export const MAXRETRIES = 10; +export const codes = new Set(['EMFILE', 'ENFILE', 'EBUSY']); +export const retryBusy = (fn) => { + const method = async (path, opt, backoff = 1, total = 0) => { + const mbo = opt.maxBackoff || MAXBACKOFF; + const rate = opt.backoff || RATE; + const max = opt.maxRetries || MAXRETRIES; + let retries = 0; + while (true) { + try { + return await fn(path); + } + catch (er) { + const fer = er; + if (fer?.path === path && fer?.code && codes.has(fer.code)) { + backoff = Math.ceil(backoff * rate); + total = backoff + total; + if (total < mbo) { + return new Promise((res, rej) => { + setTimeout(() => { + method(path, opt, backoff, total).then(res, rej); + }, backoff); + }); + } + if (retries < max) { + retries++; + continue; + } + } + throw er; + } + } + }; + return method; +}; +// just retries, no async so no backoff +export const retryBusySync = (fn) => { + const method = (path, opt) => { + const max = opt.maxRetries || MAXRETRIES; + let retries = 0; + while (true) { + try { + return fn(path); + } + catch (er) { + const fer = er; + if (fer?.path === path && + fer?.code && + codes.has(fer.code) && + retries < max) { + retries++; + continue; + } + throw er; + } + } + }; + return method; +}; +//# sourceMappingURL=retry-busy.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/retry-busy.js.map b/node_modules/rimraf/dist/esm/retry-busy.js.map new file mode 100644 index 0000000..f4239eb --- /dev/null +++ b/node_modules/rimraf/dist/esm/retry-busy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"retry-busy.js","sourceRoot":"","sources":["../../src/retry-busy.ts"],"names":[],"mappings":"AAAA,qEAAqE;AAIrE,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,CAAA;AAC7B,MAAM,CAAC,MAAM,IAAI,GAAG,GAAG,CAAA;AACvB,MAAM,CAAC,MAAM,UAAU,GAAG,EAAE,CAAA;AAC5B,MAAM,CAAC,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAA;AAE3D,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,EAAkC,EAAE,EAAE;IAC9D,MAAM,MAAM,GAAG,KAAK,EAClB,IAAY,EACZ,GAAuB,EACvB,OAAO,GAAG,CAAC,EACX,KAAK,GAAG,CAAC,EACT,EAAE;QACF,MAAM,GAAG,GAAG,GAAG,CAAC,UAAU,IAAI,UAAU,CAAA;QACxC,MAAM,IAAI,GAAG,GAAG,CAAC,OAAO,IAAI,IAAI,CAAA;QAChC,MAAM,GAAG,GAAG,GAAG,CAAC,UAAU,IAAI,UAAU,CAAA;QACxC,IAAI,OAAO,GAAG,CAAC,CAAA;QACf,OAAO,IAAI,EAAE,CAAC;YACZ,IAAI,CAAC;gBACH,OAAO,MAAM,EAAE,CAAC,IAAI,CAAC,CAAA;YACvB,CAAC;YAAC,OAAO,EAAE,EAAE,CAAC;gBACZ,MAAM,GAAG,GAAG,EAA2B,CAAA;gBACvC,IAAI,GAAG,EAAE,IAAI,KAAK,IAAI,IAAI,GAAG,EAAE,IAAI,IAAI,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;oBAC3D,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,CAAA;oBACnC,KAAK,GAAG,OAAO,GAAG,KAAK,CAAA;oBACvB,IAAI,KAAK,GAAG,GAAG,EAAE,CAAC;wBAChB,OAAO,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;4BAC9B,UAAU,CAAC,GAAG,EAAE;gCACd,MAAM,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;4BAClD,CAAC,EAAE,OAAO,CAAC,CAAA;wBACb,CAAC,CAAC,CAAA;oBACJ,CAAC;oBACD,IAAI,OAAO,GAAG,GAAG,EAAE,CAAC;wBAClB,OAAO,EAAE,CAAA;wBACT,SAAQ;oBACV,CAAC;gBACH,CAAC;gBACD,MAAM,EAAE,CAAA;YACV,CAAC;QACH,CAAC;IACH,CAAC,CAAA;IAED,OAAO,MAAM,CAAA;AACf,CAAC,CAAA;AAED,uCAAuC;AACvC,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,EAAyB,EAAE,EAAE;IACzD,MAAM,MAAM,GAAG,CAAC,IAAY,EAAE,GAAkB,EAAE,EAAE;QAClD,MAAM,GAAG,GAAG,GAAG,CAAC,UAAU,IAAI,UAAU,CAAA;QACxC,IAAI,OAAO,GAAG,CAAC,CAAA;QACf,OAAO,IAAI,EAAE,CAAC;YACZ,IAAI,CAAC;gBACH,OAAO,EAAE,CAAC,IAAI,CAAC,CAAA;YACjB,CAAC;YAAC,OAAO,EAAE,EAAE,CAAC;gBACZ,MAAM,GAAG,GAAG,EAA2B,CAAA;gBACvC,IACE,GAAG,EAAE,IAAI,KAAK,IAAI;oBAClB,GAAG,EAAE,IAAI;oBACT,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC;oBACnB,OAAO,GAAG,GAAG,EACb,CAAC;oBACD,OAAO,EAAE,CAAA;oBACT,SAAQ;gBACV,CAAC;gBACD,MAAM,EAAE,CAAA;YACV,CAAC;QACH,CAAC;IACH,CAAC,CAAA;IACD,OAAO,MAAM,CAAA;AACf,CAAC,CAAA","sourcesContent":["// note: max backoff is the maximum that any *single* backoff will do\n\nimport { RimrafAsyncOptions, RimrafOptions } from './index.js'\n\nexport const MAXBACKOFF = 200\nexport const RATE = 1.2\nexport const MAXRETRIES = 10\nexport const codes = new Set(['EMFILE', 'ENFILE', 'EBUSY'])\n\nexport const retryBusy = (fn: (path: string) => Promise) => {\n const method = async (\n path: string,\n opt: RimrafAsyncOptions,\n backoff = 1,\n total = 0,\n ) => {\n const mbo = opt.maxBackoff || MAXBACKOFF\n const rate = opt.backoff || RATE\n const max = opt.maxRetries || MAXRETRIES\n let retries = 0\n while (true) {\n try {\n return await fn(path)\n } catch (er) {\n const fer = er as NodeJS.ErrnoException\n if (fer?.path === path && fer?.code && codes.has(fer.code)) {\n backoff = Math.ceil(backoff * rate)\n total = backoff + total\n if (total < mbo) {\n return new Promise((res, rej) => {\n setTimeout(() => {\n method(path, opt, backoff, total).then(res, rej)\n }, backoff)\n })\n }\n if (retries < max) {\n retries++\n continue\n }\n }\n throw er\n }\n }\n }\n\n return method\n}\n\n// just retries, no async so no backoff\nexport const retryBusySync = (fn: (path: string) => any) => {\n const method = (path: string, opt: RimrafOptions) => {\n const max = opt.maxRetries || MAXRETRIES\n let retries = 0\n while (true) {\n try {\n return fn(path)\n } catch (er) {\n const fer = er as NodeJS.ErrnoException\n if (\n fer?.path === path &&\n fer?.code &&\n codes.has(fer.code) &&\n retries < max\n ) {\n retries++\n continue\n }\n throw er\n }\n }\n }\n return method\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-manual.d.ts b/node_modules/rimraf/dist/esm/rimraf-manual.d.ts new file mode 100644 index 0000000..35c5c86 --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-manual.d.ts @@ -0,0 +1,3 @@ +export declare const rimrafManual: (path: string, opt: import("./opt-arg.js").RimrafAsyncOptions) => Promise; +export declare const rimrafManualSync: (path: string, opt: import("./opt-arg.js").RimrafSyncOptions) => boolean; +//# sourceMappingURL=rimraf-manual.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-manual.d.ts.map b/node_modules/rimraf/dist/esm/rimraf-manual.d.ts.map new file mode 100644 index 0000000..19bd251 --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-manual.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-manual.d.ts","sourceRoot":"","sources":["../../src/rimraf-manual.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,YAAY,oFAAqD,CAAA;AAC9E,eAAO,MAAM,gBAAgB,0EAC+B,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-manual.js b/node_modules/rimraf/dist/esm/rimraf-manual.js new file mode 100644 index 0000000..132708f --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-manual.js @@ -0,0 +1,6 @@ +import platform from './platform.js'; +import { rimrafPosix, rimrafPosixSync } from './rimraf-posix.js'; +import { rimrafWindows, rimrafWindowsSync } from './rimraf-windows.js'; +export const rimrafManual = platform === 'win32' ? rimrafWindows : rimrafPosix; +export const rimrafManualSync = platform === 'win32' ? rimrafWindowsSync : rimrafPosixSync; +//# sourceMappingURL=rimraf-manual.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-manual.js.map b/node_modules/rimraf/dist/esm/rimraf-manual.js.map new file mode 100644 index 0000000..212c815 --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-manual.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-manual.js","sourceRoot":"","sources":["../../src/rimraf-manual.ts"],"names":[],"mappings":"AAAA,OAAO,QAAQ,MAAM,eAAe,CAAA;AAEpC,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAChE,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAA;AAEtE,MAAM,CAAC,MAAM,YAAY,GAAG,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,WAAW,CAAA;AAC9E,MAAM,CAAC,MAAM,gBAAgB,GAC3B,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,eAAe,CAAA","sourcesContent":["import platform from './platform.js'\n\nimport { rimrafPosix, rimrafPosixSync } from './rimraf-posix.js'\nimport { rimrafWindows, rimrafWindowsSync } from './rimraf-windows.js'\n\nexport const rimrafManual = platform === 'win32' ? rimrafWindows : rimrafPosix\nexport const rimrafManualSync =\n platform === 'win32' ? rimrafWindowsSync : rimrafPosixSync\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-move-remove.d.ts b/node_modules/rimraf/dist/esm/rimraf-move-remove.d.ts new file mode 100644 index 0000000..5d41d40 --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-move-remove.d.ts @@ -0,0 +1,4 @@ +import { RimrafAsyncOptions, RimrafSyncOptions } from './index.js'; +export declare const rimrafMoveRemove: (path: string, opt: RimrafAsyncOptions) => Promise; +export declare const rimrafMoveRemoveSync: (path: string, opt: RimrafSyncOptions) => boolean; +//# sourceMappingURL=rimraf-move-remove.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-move-remove.d.ts.map b/node_modules/rimraf/dist/esm/rimraf-move-remove.d.ts.map new file mode 100644 index 0000000..4062eae --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-move-remove.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-move-remove.d.ts","sourceRoot":"","sources":["../../src/rimraf-move-remove.ts"],"names":[],"mappings":"AA6BA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AA4ClE,eAAO,MAAM,gBAAgB,SACrB,MAAM,OACP,kBAAkB,qBAWxB,CAAA;AA4ED,eAAO,MAAM,oBAAoB,SAAU,MAAM,OAAO,iBAAiB,YAUxE,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-move-remove.js b/node_modules/rimraf/dist/esm/rimraf-move-remove.js new file mode 100644 index 0000000..093e40f --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-move-remove.js @@ -0,0 +1,187 @@ +// https://youtu.be/uhRWMGBjlO8?t=537 +// +// 1. readdir +// 2. for each entry +// a. if a non-empty directory, recurse +// b. if an empty directory, move to random hidden file name in $TEMP +// c. unlink/rmdir $TEMP +// +// This works around the fact that unlink/rmdir is non-atomic and takes +// a non-deterministic amount of time to complete. +// +// However, it is HELLA SLOW, like 2-10x slower than a naive recursive rm. +import { basename, parse, resolve } from 'path'; +import { defaultTmp, defaultTmpSync } from './default-tmp.js'; +import { ignoreENOENT, ignoreENOENTSync } from './ignore-enoent.js'; +import { chmodSync, lstatSync, promises as fsPromises, renameSync, rmdirSync, unlinkSync, } from './fs.js'; +const { lstat, rename, unlink, rmdir, chmod } = fsPromises; +import { readdirOrError, readdirOrErrorSync } from './readdir-or-error.js'; +// crypto.randomBytes is much slower, and Math.random() is enough here +const uniqueFilename = (path) => `.${basename(path)}.${Math.random()}`; +const unlinkFixEPERM = async (path) => unlink(path).catch((er) => { + if (er.code === 'EPERM') { + return chmod(path, 0o666).then(() => unlink(path), er2 => { + if (er2.code === 'ENOENT') { + return; + } + throw er; + }); + } + else if (er.code === 'ENOENT') { + return; + } + throw er; +}); +const unlinkFixEPERMSync = (path) => { + try { + unlinkSync(path); + } + catch (er) { + if (er?.code === 'EPERM') { + try { + return chmodSync(path, 0o666); + } + catch (er2) { + if (er2?.code === 'ENOENT') { + return; + } + throw er; + } + } + else if (er?.code === 'ENOENT') { + return; + } + throw er; + } +}; +export const rimrafMoveRemove = async (path, opt) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + try { + return await rimrafMoveRemoveDir(path, opt, await lstat(path)); + } + catch (er) { + if (er?.code === 'ENOENT') + return true; + throw er; + } +}; +const rimrafMoveRemoveDir = async (path, opt, ent) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + if (!opt.tmp) { + return rimrafMoveRemoveDir(path, { ...opt, tmp: await defaultTmp(path) }, ent); + } + if (path === opt.tmp && parse(path).root !== path) { + throw new Error('cannot delete temp directory used for deletion'); + } + const entries = ent.isDirectory() ? await readdirOrError(path) : null; + if (!Array.isArray(entries)) { + // this can only happen if lstat/readdir lied, or if the dir was + // swapped out with a file at just the right moment. + /* c8 ignore start */ + if (entries) { + if (entries.code === 'ENOENT') { + return true; + } + if (entries.code !== 'ENOTDIR') { + throw entries; + } + } + /* c8 ignore stop */ + if (opt.filter && !(await opt.filter(path, ent))) { + return false; + } + await ignoreENOENT(tmpUnlink(path, opt.tmp, unlinkFixEPERM)); + return true; + } + const removedAll = (await Promise.all(entries.map(ent => rimrafMoveRemoveDir(resolve(path, ent.name), opt, ent)))).reduce((a, b) => a && b, true); + if (!removedAll) { + return false; + } + // we don't ever ACTUALLY try to unlink /, because that can never work + // but when preserveRoot is false, we could be operating on it. + // No need to check if preserveRoot is not false. + if (opt.preserveRoot === false && path === parse(path).root) { + return false; + } + if (opt.filter && !(await opt.filter(path, ent))) { + return false; + } + await ignoreENOENT(tmpUnlink(path, opt.tmp, rmdir)); + return true; +}; +const tmpUnlink = async (path, tmp, rm) => { + const tmpFile = resolve(tmp, uniqueFilename(path)); + await rename(path, tmpFile); + return await rm(tmpFile); +}; +export const rimrafMoveRemoveSync = (path, opt) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + try { + return rimrafMoveRemoveDirSync(path, opt, lstatSync(path)); + } + catch (er) { + if (er?.code === 'ENOENT') + return true; + throw er; + } +}; +const rimrafMoveRemoveDirSync = (path, opt, ent) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + if (!opt.tmp) { + return rimrafMoveRemoveDirSync(path, { ...opt, tmp: defaultTmpSync(path) }, ent); + } + const tmp = opt.tmp; + if (path === opt.tmp && parse(path).root !== path) { + throw new Error('cannot delete temp directory used for deletion'); + } + const entries = ent.isDirectory() ? readdirOrErrorSync(path) : null; + if (!Array.isArray(entries)) { + // this can only happen if lstat/readdir lied, or if the dir was + // swapped out with a file at just the right moment. + /* c8 ignore start */ + if (entries) { + if (entries.code === 'ENOENT') { + return true; + } + if (entries.code !== 'ENOTDIR') { + throw entries; + } + } + /* c8 ignore stop */ + if (opt.filter && !opt.filter(path, ent)) { + return false; + } + ignoreENOENTSync(() => tmpUnlinkSync(path, tmp, unlinkFixEPERMSync)); + return true; + } + let removedAll = true; + for (const ent of entries) { + const p = resolve(path, ent.name); + removedAll = rimrafMoveRemoveDirSync(p, opt, ent) && removedAll; + } + if (!removedAll) { + return false; + } + if (opt.preserveRoot === false && path === parse(path).root) { + return false; + } + if (opt.filter && !opt.filter(path, ent)) { + return false; + } + ignoreENOENTSync(() => tmpUnlinkSync(path, tmp, rmdirSync)); + return true; +}; +const tmpUnlinkSync = (path, tmp, rmSync) => { + const tmpFile = resolve(tmp, uniqueFilename(path)); + renameSync(path, tmpFile); + return rmSync(tmpFile); +}; +//# sourceMappingURL=rimraf-move-remove.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-move-remove.js.map b/node_modules/rimraf/dist/esm/rimraf-move-remove.js.map new file mode 100644 index 0000000..b9a1fd5 --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-move-remove.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-move-remove.js","sourceRoot":"","sources":["../../src/rimraf-move-remove.ts"],"names":[],"mappings":"AAAA,qCAAqC;AACrC,EAAE;AACF,aAAa;AACb,oBAAoB;AACpB,yCAAyC;AACzC,uEAAuE;AACvE,0BAA0B;AAC1B,EAAE;AACF,uEAAuE;AACvE,kDAAkD;AAClD,EAAE;AACF,0EAA0E;AAE1E,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAC/C,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAA;AAE7D,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AAEnE,OAAO,EACL,SAAS,EACT,SAAS,EACT,QAAQ,IAAI,UAAU,EACtB,UAAU,EACV,SAAS,EACT,UAAU,GACX,MAAM,SAAS,CAAA;AAChB,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,UAAU,CAAA;AAI1D,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAA;AAE1E,sEAAsE;AACtE,MAAM,cAAc,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,MAAM,EAAE,EAAE,CAAA;AAE9E,MAAM,cAAc,GAAG,KAAK,EAAE,IAAY,EAAE,EAAE,CAC5C,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,EAA6B,EAAE,EAAE;IACnD,IAAI,EAAE,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;QACxB,OAAO,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,IAAI,CAC5B,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,EAClB,GAAG,CAAC,EAAE;YACJ,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC1B,OAAM;YACR,CAAC;YACD,MAAM,EAAE,CAAA;QACV,CAAC,CACF,CAAA;IACH,CAAC;SAAM,IAAI,EAAE,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QAChC,OAAM;IACR,CAAC;IACD,MAAM,EAAE,CAAA;AACV,CAAC,CAAC,CAAA;AAEJ,MAAM,kBAAkB,GAAG,CAAC,IAAY,EAAE,EAAE;IAC1C,IAAI,CAAC;QACH,UAAU,CAAC,IAAI,CAAC,CAAA;IAClB,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,IAAK,EAA4B,EAAE,IAAI,KAAK,OAAO,EAAE,CAAC;YACpD,IAAI,CAAC;gBACH,OAAO,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;YAC/B,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,IAAK,GAA6B,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;oBACtD,OAAM;gBACR,CAAC;gBACD,MAAM,EAAE,CAAA;YACV,CAAC;QACH,CAAC;aAAM,IAAK,EAA4B,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC5D,OAAM;QACR,CAAC;QACD,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,EACnC,IAAY,EACZ,GAAuB,EACvB,EAAE;IACF,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,IAAI,CAAC;QACH,OAAO,MAAM,mBAAmB,CAAC,IAAI,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC,IAAI,CAAC,CAAC,CAAA;IAChE,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,IAAK,EAA4B,EAAE,IAAI,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAA;QACjE,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAED,MAAM,mBAAmB,GAAG,KAAK,EAC/B,IAAY,EACZ,GAAuB,EACvB,GAAmB,EACD,EAAE;IACpB,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;QACb,OAAO,mBAAmB,CACxB,IAAI,EACJ,EAAE,GAAG,GAAG,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC,IAAI,CAAC,EAAE,EACvC,GAAG,CACJ,CAAA;IACH,CAAC;IACD,IAAI,IAAI,KAAK,GAAG,CAAC,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,KAAK,IAAI,EAAE,CAAC;QAClD,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAA;IACnE,CAAC;IAED,MAAM,OAAO,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,MAAM,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACrE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,gEAAgE;QAChE,oDAAoD;QACpD,qBAAqB;QACrB,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC9B,OAAO,IAAI,CAAA;YACb,CAAC;YACD,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;gBAC/B,MAAM,OAAO,CAAA;YACf,CAAC;QACH,CAAC;QACD,oBAAoB;QACpB,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC;YACjD,OAAO,KAAK,CAAA;QACd,CAAC;QACD,MAAM,YAAY,CAAC,SAAS,CAAC,IAAI,EAAE,GAAG,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC,CAAA;QAC5D,OAAO,IAAI,CAAA;IACb,CAAC;IAED,MAAM,UAAU,GAAG,CACjB,MAAM,OAAO,CAAC,GAAG,CACf,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAChB,mBAAmB,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,CACvD,CACF,CACF,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAA;IAChC,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,KAAK,CAAA;IACd,CAAC;IAED,sEAAsE;IACtE,+DAA+D;IAC/D,iDAAiD;IACjD,IAAI,GAAG,CAAC,YAAY,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;QAC5D,OAAO,KAAK,CAAA;IACd,CAAC;IACD,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC;QACjD,OAAO,KAAK,CAAA;IACd,CAAC;IACD,MAAM,YAAY,CAAC,SAAS,CAAC,IAAI,EAAE,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAA;IACnD,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,MAAM,SAAS,GAAG,KAAK,EACrB,IAAY,EACZ,GAAW,EACX,EAA+B,EAC/B,EAAE;IACF,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC,CAAA;IAClD,MAAM,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IAC3B,OAAO,MAAM,EAAE,CAAC,OAAO,CAAC,CAAA;AAC1B,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,IAAY,EAAE,GAAsB,EAAE,EAAE;IAC3E,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,IAAI,CAAC;QACH,OAAO,uBAAuB,CAAC,IAAI,EAAE,GAAG,EAAE,SAAS,CAAC,IAAI,CAAC,CAAC,CAAA;IAC5D,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,IAAK,EAA4B,EAAE,IAAI,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAA;QACjE,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAED,MAAM,uBAAuB,GAAG,CAC9B,IAAY,EACZ,GAAsB,EACtB,GAAmB,EACV,EAAE;IACX,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;QACb,OAAO,uBAAuB,CAC5B,IAAI,EACJ,EAAE,GAAG,GAAG,EAAE,GAAG,EAAE,cAAc,CAAC,IAAI,CAAC,EAAE,EACrC,GAAG,CACJ,CAAA;IACH,CAAC;IACD,MAAM,GAAG,GAAW,GAAG,CAAC,GAAG,CAAA;IAE3B,IAAI,IAAI,KAAK,GAAG,CAAC,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,KAAK,IAAI,EAAE,CAAC;QAClD,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAA;IACnE,CAAC;IAED,MAAM,OAAO,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACnE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,gEAAgE;QAChE,oDAAoD;QACpD,qBAAqB;QACrB,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC9B,OAAO,IAAI,CAAA;YACb,CAAC;YACD,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;gBAC/B,MAAM,OAAO,CAAA;YACf,CAAC;QACH,CAAC;QACD,oBAAoB;QACpB,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzC,OAAO,KAAK,CAAA;QACd,CAAC;QACD,gBAAgB,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,IAAI,EAAE,GAAG,EAAE,kBAAkB,CAAC,CAAC,CAAA;QACpE,OAAO,IAAI,CAAA;IACb,CAAC;IAED,IAAI,UAAU,GAAG,IAAI,CAAA;IACrB,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE,CAAC;QAC1B,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,CAAA;QACjC,UAAU,GAAG,uBAAuB,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,IAAI,UAAU,CAAA;IACjE,CAAC;IACD,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,KAAK,CAAA;IACd,CAAC;IACD,IAAI,GAAG,CAAC,YAAY,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;QAC5D,OAAO,KAAK,CAAA;IACd,CAAC;IACD,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;QACzC,OAAO,KAAK,CAAA;IACd,CAAC;IACD,gBAAgB,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,IAAI,EAAE,GAAG,EAAE,SAAS,CAAC,CAAC,CAAA;IAC3D,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,MAAM,aAAa,GAAG,CACpB,IAAY,EACZ,GAAW,EACX,MAA2B,EAC3B,EAAE;IACF,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC,CAAA;IAClD,UAAU,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IACzB,OAAO,MAAM,CAAC,OAAO,CAAC,CAAA;AACxB,CAAC,CAAA","sourcesContent":["// https://youtu.be/uhRWMGBjlO8?t=537\n//\n// 1. readdir\n// 2. for each entry\n// a. if a non-empty directory, recurse\n// b. if an empty directory, move to random hidden file name in $TEMP\n// c. unlink/rmdir $TEMP\n//\n// This works around the fact that unlink/rmdir is non-atomic and takes\n// a non-deterministic amount of time to complete.\n//\n// However, it is HELLA SLOW, like 2-10x slower than a naive recursive rm.\n\nimport { basename, parse, resolve } from 'path'\nimport { defaultTmp, defaultTmpSync } from './default-tmp.js'\n\nimport { ignoreENOENT, ignoreENOENTSync } from './ignore-enoent.js'\n\nimport {\n chmodSync,\n lstatSync,\n promises as fsPromises,\n renameSync,\n rmdirSync,\n unlinkSync,\n} from './fs.js'\nconst { lstat, rename, unlink, rmdir, chmod } = fsPromises\n\nimport { Dirent, Stats } from 'fs'\nimport { RimrafAsyncOptions, RimrafSyncOptions } from './index.js'\nimport { readdirOrError, readdirOrErrorSync } from './readdir-or-error.js'\n\n// crypto.randomBytes is much slower, and Math.random() is enough here\nconst uniqueFilename = (path: string) => `.${basename(path)}.${Math.random()}`\n\nconst unlinkFixEPERM = async (path: string) =>\n unlink(path).catch((er: Error & { code?: string }) => {\n if (er.code === 'EPERM') {\n return chmod(path, 0o666).then(\n () => unlink(path),\n er2 => {\n if (er2.code === 'ENOENT') {\n return\n }\n throw er\n },\n )\n } else if (er.code === 'ENOENT') {\n return\n }\n throw er\n })\n\nconst unlinkFixEPERMSync = (path: string) => {\n try {\n unlinkSync(path)\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'EPERM') {\n try {\n return chmodSync(path, 0o666)\n } catch (er2) {\n if ((er2 as NodeJS.ErrnoException)?.code === 'ENOENT') {\n return\n }\n throw er\n }\n } else if ((er as NodeJS.ErrnoException)?.code === 'ENOENT') {\n return\n }\n throw er\n }\n}\n\nexport const rimrafMoveRemove = async (\n path: string,\n opt: RimrafAsyncOptions,\n) => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n try {\n return await rimrafMoveRemoveDir(path, opt, await lstat(path))\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'ENOENT') return true\n throw er\n }\n}\n\nconst rimrafMoveRemoveDir = async (\n path: string,\n opt: RimrafAsyncOptions,\n ent: Dirent | Stats,\n): Promise => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n if (!opt.tmp) {\n return rimrafMoveRemoveDir(\n path,\n { ...opt, tmp: await defaultTmp(path) },\n ent,\n )\n }\n if (path === opt.tmp && parse(path).root !== path) {\n throw new Error('cannot delete temp directory used for deletion')\n }\n\n const entries = ent.isDirectory() ? await readdirOrError(path) : null\n if (!Array.isArray(entries)) {\n // this can only happen if lstat/readdir lied, or if the dir was\n // swapped out with a file at just the right moment.\n /* c8 ignore start */\n if (entries) {\n if (entries.code === 'ENOENT') {\n return true\n }\n if (entries.code !== 'ENOTDIR') {\n throw entries\n }\n }\n /* c8 ignore stop */\n if (opt.filter && !(await opt.filter(path, ent))) {\n return false\n }\n await ignoreENOENT(tmpUnlink(path, opt.tmp, unlinkFixEPERM))\n return true\n }\n\n const removedAll = (\n await Promise.all(\n entries.map(ent =>\n rimrafMoveRemoveDir(resolve(path, ent.name), opt, ent),\n ),\n )\n ).reduce((a, b) => a && b, true)\n if (!removedAll) {\n return false\n }\n\n // we don't ever ACTUALLY try to unlink /, because that can never work\n // but when preserveRoot is false, we could be operating on it.\n // No need to check if preserveRoot is not false.\n if (opt.preserveRoot === false && path === parse(path).root) {\n return false\n }\n if (opt.filter && !(await opt.filter(path, ent))) {\n return false\n }\n await ignoreENOENT(tmpUnlink(path, opt.tmp, rmdir))\n return true\n}\n\nconst tmpUnlink = async (\n path: string,\n tmp: string,\n rm: (p: string) => Promise,\n) => {\n const tmpFile = resolve(tmp, uniqueFilename(path))\n await rename(path, tmpFile)\n return await rm(tmpFile)\n}\n\nexport const rimrafMoveRemoveSync = (path: string, opt: RimrafSyncOptions) => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n try {\n return rimrafMoveRemoveDirSync(path, opt, lstatSync(path))\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'ENOENT') return true\n throw er\n }\n}\n\nconst rimrafMoveRemoveDirSync = (\n path: string,\n opt: RimrafSyncOptions,\n ent: Dirent | Stats,\n): boolean => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n if (!opt.tmp) {\n return rimrafMoveRemoveDirSync(\n path,\n { ...opt, tmp: defaultTmpSync(path) },\n ent,\n )\n }\n const tmp: string = opt.tmp\n\n if (path === opt.tmp && parse(path).root !== path) {\n throw new Error('cannot delete temp directory used for deletion')\n }\n\n const entries = ent.isDirectory() ? readdirOrErrorSync(path) : null\n if (!Array.isArray(entries)) {\n // this can only happen if lstat/readdir lied, or if the dir was\n // swapped out with a file at just the right moment.\n /* c8 ignore start */\n if (entries) {\n if (entries.code === 'ENOENT') {\n return true\n }\n if (entries.code !== 'ENOTDIR') {\n throw entries\n }\n }\n /* c8 ignore stop */\n if (opt.filter && !opt.filter(path, ent)) {\n return false\n }\n ignoreENOENTSync(() => tmpUnlinkSync(path, tmp, unlinkFixEPERMSync))\n return true\n }\n\n let removedAll = true\n for (const ent of entries) {\n const p = resolve(path, ent.name)\n removedAll = rimrafMoveRemoveDirSync(p, opt, ent) && removedAll\n }\n if (!removedAll) {\n return false\n }\n if (opt.preserveRoot === false && path === parse(path).root) {\n return false\n }\n if (opt.filter && !opt.filter(path, ent)) {\n return false\n }\n ignoreENOENTSync(() => tmpUnlinkSync(path, tmp, rmdirSync))\n return true\n}\n\nconst tmpUnlinkSync = (\n path: string,\n tmp: string,\n rmSync: (p: string) => void,\n) => {\n const tmpFile = resolve(tmp, uniqueFilename(path))\n renameSync(path, tmpFile)\n return rmSync(tmpFile)\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-native.d.ts b/node_modules/rimraf/dist/esm/rimraf-native.d.ts new file mode 100644 index 0000000..cc84bf7 --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-native.d.ts @@ -0,0 +1,4 @@ +import { RimrafAsyncOptions, RimrafSyncOptions } from './index.js'; +export declare const rimrafNative: (path: string, opt: RimrafAsyncOptions) => Promise; +export declare const rimrafNativeSync: (path: string, opt: RimrafSyncOptions) => boolean; +//# sourceMappingURL=rimraf-native.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-native.d.ts.map b/node_modules/rimraf/dist/esm/rimraf-native.d.ts.map new file mode 100644 index 0000000..bea6b79 --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-native.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-native.d.ts","sourceRoot":"","sources":["../../src/rimraf-native.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAIlE,eAAO,MAAM,YAAY,SACjB,MAAM,OACP,kBAAkB,KACtB,OAAO,CAAC,OAAO,CAOjB,CAAA;AAED,eAAO,MAAM,gBAAgB,SACrB,MAAM,OACP,iBAAiB,KACrB,OAOF,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-native.js b/node_modules/rimraf/dist/esm/rimraf-native.js new file mode 100644 index 0000000..719161f --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-native.js @@ -0,0 +1,19 @@ +import { promises, rmSync } from './fs.js'; +const { rm } = promises; +export const rimrafNative = async (path, opt) => { + await rm(path, { + ...opt, + force: true, + recursive: true, + }); + return true; +}; +export const rimrafNativeSync = (path, opt) => { + rmSync(path, { + ...opt, + force: true, + recursive: true, + }); + return true; +}; +//# sourceMappingURL=rimraf-native.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-native.js.map b/node_modules/rimraf/dist/esm/rimraf-native.js.map new file mode 100644 index 0000000..fde373b --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-native.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-native.js","sourceRoot":"","sources":["../../src/rimraf-native.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAC1C,MAAM,EAAE,EAAE,EAAE,GAAG,QAAQ,CAAA;AAEvB,MAAM,CAAC,MAAM,YAAY,GAAG,KAAK,EAC/B,IAAY,EACZ,GAAuB,EACL,EAAE;IACpB,MAAM,EAAE,CAAC,IAAI,EAAE;QACb,GAAG,GAAG;QACN,KAAK,EAAE,IAAI;QACX,SAAS,EAAE,IAAI;KAChB,CAAC,CAAA;IACF,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAC9B,IAAY,EACZ,GAAsB,EACb,EAAE;IACX,MAAM,CAAC,IAAI,EAAE;QACX,GAAG,GAAG;QACN,KAAK,EAAE,IAAI;QACX,SAAS,EAAE,IAAI;KAChB,CAAC,CAAA;IACF,OAAO,IAAI,CAAA;AACb,CAAC,CAAA","sourcesContent":["import { RimrafAsyncOptions, RimrafSyncOptions } from './index.js'\nimport { promises, rmSync } from './fs.js'\nconst { rm } = promises\n\nexport const rimrafNative = async (\n path: string,\n opt: RimrafAsyncOptions,\n): Promise => {\n await rm(path, {\n ...opt,\n force: true,\n recursive: true,\n })\n return true\n}\n\nexport const rimrafNativeSync = (\n path: string,\n opt: RimrafSyncOptions,\n): boolean => {\n rmSync(path, {\n ...opt,\n force: true,\n recursive: true,\n })\n return true\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-posix.d.ts b/node_modules/rimraf/dist/esm/rimraf-posix.d.ts new file mode 100644 index 0000000..8e532ef --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-posix.d.ts @@ -0,0 +1,4 @@ +import { RimrafAsyncOptions, RimrafSyncOptions } from './index.js'; +export declare const rimrafPosix: (path: string, opt: RimrafAsyncOptions) => Promise; +export declare const rimrafPosixSync: (path: string, opt: RimrafSyncOptions) => boolean; +//# sourceMappingURL=rimraf-posix.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-posix.d.ts.map b/node_modules/rimraf/dist/esm/rimraf-posix.d.ts.map new file mode 100644 index 0000000..3f9b808 --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-posix.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-posix.d.ts","sourceRoot":"","sources":["../../src/rimraf-posix.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAGlE,eAAO,MAAM,WAAW,SAAgB,MAAM,OAAO,kBAAkB,qBAUtE,CAAA;AAED,eAAO,MAAM,eAAe,SAAU,MAAM,OAAO,iBAAiB,YAUnE,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-posix.js b/node_modules/rimraf/dist/esm/rimraf-posix.js new file mode 100644 index 0000000..356a477 --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-posix.js @@ -0,0 +1,118 @@ +// the simple recursive removal, where unlink and rmdir are atomic +// Note that this approach does NOT work on Windows! +// We stat first and only unlink if the Dirent isn't a directory, +// because sunos will let root unlink a directory, and some +// SUPER weird breakage happens as a result. +import { lstatSync, promises, rmdirSync, unlinkSync } from './fs.js'; +const { lstat, rmdir, unlink } = promises; +import { parse, resolve } from 'path'; +import { readdirOrError, readdirOrErrorSync } from './readdir-or-error.js'; +import { ignoreENOENT, ignoreENOENTSync } from './ignore-enoent.js'; +export const rimrafPosix = async (path, opt) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + try { + return await rimrafPosixDir(path, opt, await lstat(path)); + } + catch (er) { + if (er?.code === 'ENOENT') + return true; + throw er; + } +}; +export const rimrafPosixSync = (path, opt) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + try { + return rimrafPosixDirSync(path, opt, lstatSync(path)); + } + catch (er) { + if (er?.code === 'ENOENT') + return true; + throw er; + } +}; +const rimrafPosixDir = async (path, opt, ent) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + const entries = ent.isDirectory() ? await readdirOrError(path) : null; + if (!Array.isArray(entries)) { + // this can only happen if lstat/readdir lied, or if the dir was + // swapped out with a file at just the right moment. + /* c8 ignore start */ + if (entries) { + if (entries.code === 'ENOENT') { + return true; + } + if (entries.code !== 'ENOTDIR') { + throw entries; + } + } + /* c8 ignore stop */ + if (opt.filter && !(await opt.filter(path, ent))) { + return false; + } + await ignoreENOENT(unlink(path)); + return true; + } + const removedAll = (await Promise.all(entries.map(ent => rimrafPosixDir(resolve(path, ent.name), opt, ent)))).reduce((a, b) => a && b, true); + if (!removedAll) { + return false; + } + // we don't ever ACTUALLY try to unlink /, because that can never work + // but when preserveRoot is false, we could be operating on it. + // No need to check if preserveRoot is not false. + if (opt.preserveRoot === false && path === parse(path).root) { + return false; + } + if (opt.filter && !(await opt.filter(path, ent))) { + return false; + } + await ignoreENOENT(rmdir(path)); + return true; +}; +const rimrafPosixDirSync = (path, opt, ent) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + const entries = ent.isDirectory() ? readdirOrErrorSync(path) : null; + if (!Array.isArray(entries)) { + // this can only happen if lstat/readdir lied, or if the dir was + // swapped out with a file at just the right moment. + /* c8 ignore start */ + if (entries) { + if (entries.code === 'ENOENT') { + return true; + } + if (entries.code !== 'ENOTDIR') { + throw entries; + } + } + /* c8 ignore stop */ + if (opt.filter && !opt.filter(path, ent)) { + return false; + } + ignoreENOENTSync(() => unlinkSync(path)); + return true; + } + let removedAll = true; + for (const ent of entries) { + const p = resolve(path, ent.name); + removedAll = rimrafPosixDirSync(p, opt, ent) && removedAll; + } + if (opt.preserveRoot === false && path === parse(path).root) { + return false; + } + if (!removedAll) { + return false; + } + if (opt.filter && !opt.filter(path, ent)) { + return false; + } + ignoreENOENTSync(() => rmdirSync(path)); + return true; +}; +//# sourceMappingURL=rimraf-posix.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-posix.js.map b/node_modules/rimraf/dist/esm/rimraf-posix.js.map new file mode 100644 index 0000000..e301324 --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-posix.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-posix.js","sourceRoot":"","sources":["../../src/rimraf-posix.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,oDAAoD;AACpD,iEAAiE;AACjE,2DAA2D;AAC3D,4CAA4C;AAE5C,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AACpE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,QAAQ,CAAA;AAEzC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAErC,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAA;AAI1E,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AAEnE,MAAM,CAAC,MAAM,WAAW,GAAG,KAAK,EAAE,IAAY,EAAE,GAAuB,EAAE,EAAE;IACzE,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,IAAI,CAAC;QACH,OAAO,MAAM,cAAc,CAAC,IAAI,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC,IAAI,CAAC,CAAC,CAAA;IAC3D,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,IAAK,EAA4B,EAAE,IAAI,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAA;QACjE,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,IAAY,EAAE,GAAsB,EAAE,EAAE;IACtE,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,IAAI,CAAC;QACH,OAAO,kBAAkB,CAAC,IAAI,EAAE,GAAG,EAAE,SAAS,CAAC,IAAI,CAAC,CAAC,CAAA;IACvD,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,IAAK,EAA4B,EAAE,IAAI,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAA;QACjE,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAED,MAAM,cAAc,GAAG,KAAK,EAC1B,IAAY,EACZ,GAAuB,EACvB,GAAmB,EACD,EAAE;IACpB,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,MAAM,OAAO,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,MAAM,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACrE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,gEAAgE;QAChE,oDAAoD;QACpD,qBAAqB;QACrB,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC9B,OAAO,IAAI,CAAA;YACb,CAAC;YACD,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;gBAC/B,MAAM,OAAO,CAAA;YACf,CAAC;QACH,CAAC;QACD,oBAAoB;QACpB,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC;YACjD,OAAO,KAAK,CAAA;QACd,CAAC;QACD,MAAM,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAA;QAChC,OAAO,IAAI,CAAA;IACb,CAAC;IAED,MAAM,UAAU,GAAG,CACjB,MAAM,OAAO,CAAC,GAAG,CACf,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,cAAc,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CACtE,CACF,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAA;IAEhC,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,KAAK,CAAA;IACd,CAAC;IAED,sEAAsE;IACtE,+DAA+D;IAC/D,iDAAiD;IACjD,IAAI,GAAG,CAAC,YAAY,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;QAC5D,OAAO,KAAK,CAAA;IACd,CAAC;IAED,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC;QACjD,OAAO,KAAK,CAAA;IACd,CAAC;IAED,MAAM,YAAY,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAA;IAC/B,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,MAAM,kBAAkB,GAAG,CACzB,IAAY,EACZ,GAAsB,EACtB,GAAmB,EACV,EAAE;IACX,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,MAAM,OAAO,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACnE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,gEAAgE;QAChE,oDAAoD;QACpD,qBAAqB;QACrB,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC9B,OAAO,IAAI,CAAA;YACb,CAAC;YACD,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;gBAC/B,MAAM,OAAO,CAAA;YACf,CAAC;QACH,CAAC;QACD,oBAAoB;QACpB,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzC,OAAO,KAAK,CAAA;QACd,CAAC;QACD,gBAAgB,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAA;QACxC,OAAO,IAAI,CAAA;IACb,CAAC;IACD,IAAI,UAAU,GAAY,IAAI,CAAA;IAC9B,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE,CAAC;QAC1B,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,CAAA;QACjC,UAAU,GAAG,kBAAkB,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,IAAI,UAAU,CAAA;IAC5D,CAAC;IACD,IAAI,GAAG,CAAC,YAAY,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;QAC5D,OAAO,KAAK,CAAA;IACd,CAAC;IAED,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,KAAK,CAAA;IACd,CAAC;IAED,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;QACzC,OAAO,KAAK,CAAA;IACd,CAAC;IAED,gBAAgB,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAA;IACvC,OAAO,IAAI,CAAA;AACb,CAAC,CAAA","sourcesContent":["// the simple recursive removal, where unlink and rmdir are atomic\n// Note that this approach does NOT work on Windows!\n// We stat first and only unlink if the Dirent isn't a directory,\n// because sunos will let root unlink a directory, and some\n// SUPER weird breakage happens as a result.\n\nimport { lstatSync, promises, rmdirSync, unlinkSync } from './fs.js'\nconst { lstat, rmdir, unlink } = promises\n\nimport { parse, resolve } from 'path'\n\nimport { readdirOrError, readdirOrErrorSync } from './readdir-or-error.js'\n\nimport { Dirent, Stats } from 'fs'\nimport { RimrafAsyncOptions, RimrafSyncOptions } from './index.js'\nimport { ignoreENOENT, ignoreENOENTSync } from './ignore-enoent.js'\n\nexport const rimrafPosix = async (path: string, opt: RimrafAsyncOptions) => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n try {\n return await rimrafPosixDir(path, opt, await lstat(path))\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'ENOENT') return true\n throw er\n }\n}\n\nexport const rimrafPosixSync = (path: string, opt: RimrafSyncOptions) => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n try {\n return rimrafPosixDirSync(path, opt, lstatSync(path))\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'ENOENT') return true\n throw er\n }\n}\n\nconst rimrafPosixDir = async (\n path: string,\n opt: RimrafAsyncOptions,\n ent: Dirent | Stats,\n): Promise => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n const entries = ent.isDirectory() ? await readdirOrError(path) : null\n if (!Array.isArray(entries)) {\n // this can only happen if lstat/readdir lied, or if the dir was\n // swapped out with a file at just the right moment.\n /* c8 ignore start */\n if (entries) {\n if (entries.code === 'ENOENT') {\n return true\n }\n if (entries.code !== 'ENOTDIR') {\n throw entries\n }\n }\n /* c8 ignore stop */\n if (opt.filter && !(await opt.filter(path, ent))) {\n return false\n }\n await ignoreENOENT(unlink(path))\n return true\n }\n\n const removedAll = (\n await Promise.all(\n entries.map(ent => rimrafPosixDir(resolve(path, ent.name), opt, ent)),\n )\n ).reduce((a, b) => a && b, true)\n\n if (!removedAll) {\n return false\n }\n\n // we don't ever ACTUALLY try to unlink /, because that can never work\n // but when preserveRoot is false, we could be operating on it.\n // No need to check if preserveRoot is not false.\n if (opt.preserveRoot === false && path === parse(path).root) {\n return false\n }\n\n if (opt.filter && !(await opt.filter(path, ent))) {\n return false\n }\n\n await ignoreENOENT(rmdir(path))\n return true\n}\n\nconst rimrafPosixDirSync = (\n path: string,\n opt: RimrafSyncOptions,\n ent: Dirent | Stats,\n): boolean => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n const entries = ent.isDirectory() ? readdirOrErrorSync(path) : null\n if (!Array.isArray(entries)) {\n // this can only happen if lstat/readdir lied, or if the dir was\n // swapped out with a file at just the right moment.\n /* c8 ignore start */\n if (entries) {\n if (entries.code === 'ENOENT') {\n return true\n }\n if (entries.code !== 'ENOTDIR') {\n throw entries\n }\n }\n /* c8 ignore stop */\n if (opt.filter && !opt.filter(path, ent)) {\n return false\n }\n ignoreENOENTSync(() => unlinkSync(path))\n return true\n }\n let removedAll: boolean = true\n for (const ent of entries) {\n const p = resolve(path, ent.name)\n removedAll = rimrafPosixDirSync(p, opt, ent) && removedAll\n }\n if (opt.preserveRoot === false && path === parse(path).root) {\n return false\n }\n\n if (!removedAll) {\n return false\n }\n\n if (opt.filter && !opt.filter(path, ent)) {\n return false\n }\n\n ignoreENOENTSync(() => rmdirSync(path))\n return true\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-windows.d.ts b/node_modules/rimraf/dist/esm/rimraf-windows.d.ts new file mode 100644 index 0000000..5556890 --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-windows.d.ts @@ -0,0 +1,4 @@ +import { RimrafAsyncOptions, RimrafSyncOptions } from './index.js'; +export declare const rimrafWindows: (path: string, opt: RimrafAsyncOptions) => Promise; +export declare const rimrafWindowsSync: (path: string, opt: RimrafSyncOptions) => boolean; +//# sourceMappingURL=rimraf-windows.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-windows.d.ts.map b/node_modules/rimraf/dist/esm/rimraf-windows.d.ts.map new file mode 100644 index 0000000..56f00d9 --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-windows.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-windows.d.ts","sourceRoot":"","sources":["../../src/rimraf-windows.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AA2DlE,eAAO,MAAM,aAAa,SAAgB,MAAM,OAAO,kBAAkB,qBAUxE,CAAA;AAED,eAAO,MAAM,iBAAiB,SAAU,MAAM,OAAO,iBAAiB,YAUrE,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-windows.js b/node_modules/rimraf/dist/esm/rimraf-windows.js new file mode 100644 index 0000000..bd2fa80 --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-windows.js @@ -0,0 +1,177 @@ +// This is the same as rimrafPosix, with the following changes: +// +// 1. EBUSY, ENFILE, EMFILE trigger retries and/or exponential backoff +// 2. All non-directories are removed first and then all directories are +// removed in a second sweep. +// 3. If we hit ENOTEMPTY in the second sweep, fall back to move-remove on +// the that folder. +// +// Note: "move then remove" is 2-10 times slower, and just as unreliable. +import { parse, resolve } from 'path'; +import { fixEPERM, fixEPERMSync } from './fix-eperm.js'; +import { lstatSync, promises, rmdirSync, unlinkSync } from './fs.js'; +import { ignoreENOENT, ignoreENOENTSync } from './ignore-enoent.js'; +import { readdirOrError, readdirOrErrorSync } from './readdir-or-error.js'; +import { retryBusy, retryBusySync } from './retry-busy.js'; +import { rimrafMoveRemove, rimrafMoveRemoveSync } from './rimraf-move-remove.js'; +const { unlink, rmdir, lstat } = promises; +const rimrafWindowsFile = retryBusy(fixEPERM(unlink)); +const rimrafWindowsFileSync = retryBusySync(fixEPERMSync(unlinkSync)); +const rimrafWindowsDirRetry = retryBusy(fixEPERM(rmdir)); +const rimrafWindowsDirRetrySync = retryBusySync(fixEPERMSync(rmdirSync)); +const rimrafWindowsDirMoveRemoveFallback = async (path, opt) => { + /* c8 ignore start */ + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + /* c8 ignore stop */ + // already filtered, remove from options so we don't call unnecessarily + const { filter, ...options } = opt; + try { + return await rimrafWindowsDirRetry(path, options); + } + catch (er) { + if (er?.code === 'ENOTEMPTY') { + return await rimrafMoveRemove(path, options); + } + throw er; + } +}; +const rimrafWindowsDirMoveRemoveFallbackSync = (path, opt) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + // already filtered, remove from options so we don't call unnecessarily + const { filter, ...options } = opt; + try { + return rimrafWindowsDirRetrySync(path, options); + } + catch (er) { + const fer = er; + if (fer?.code === 'ENOTEMPTY') { + return rimrafMoveRemoveSync(path, options); + } + throw er; + } +}; +const START = Symbol('start'); +const CHILD = Symbol('child'); +const FINISH = Symbol('finish'); +export const rimrafWindows = async (path, opt) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + try { + return await rimrafWindowsDir(path, opt, await lstat(path), START); + } + catch (er) { + if (er?.code === 'ENOENT') + return true; + throw er; + } +}; +export const rimrafWindowsSync = (path, opt) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + try { + return rimrafWindowsDirSync(path, opt, lstatSync(path), START); + } + catch (er) { + if (er?.code === 'ENOENT') + return true; + throw er; + } +}; +const rimrafWindowsDir = async (path, opt, ent, state = START) => { + if (opt?.signal?.aborted) { + throw opt.signal.reason; + } + const entries = ent.isDirectory() ? await readdirOrError(path) : null; + if (!Array.isArray(entries)) { + // this can only happen if lstat/readdir lied, or if the dir was + // swapped out with a file at just the right moment. + /* c8 ignore start */ + if (entries) { + if (entries.code === 'ENOENT') { + return true; + } + if (entries.code !== 'ENOTDIR') { + throw entries; + } + } + /* c8 ignore stop */ + if (opt.filter && !(await opt.filter(path, ent))) { + return false; + } + // is a file + await ignoreENOENT(rimrafWindowsFile(path, opt)); + return true; + } + const s = state === START ? CHILD : state; + const removedAll = (await Promise.all(entries.map(ent => rimrafWindowsDir(resolve(path, ent.name), opt, ent, s)))).reduce((a, b) => a && b, true); + if (state === START) { + return rimrafWindowsDir(path, opt, ent, FINISH); + } + else if (state === FINISH) { + if (opt.preserveRoot === false && path === parse(path).root) { + return false; + } + if (!removedAll) { + return false; + } + if (opt.filter && !(await opt.filter(path, ent))) { + return false; + } + await ignoreENOENT(rimrafWindowsDirMoveRemoveFallback(path, opt)); + } + return true; +}; +const rimrafWindowsDirSync = (path, opt, ent, state = START) => { + const entries = ent.isDirectory() ? readdirOrErrorSync(path) : null; + if (!Array.isArray(entries)) { + // this can only happen if lstat/readdir lied, or if the dir was + // swapped out with a file at just the right moment. + /* c8 ignore start */ + if (entries) { + if (entries.code === 'ENOENT') { + return true; + } + if (entries.code !== 'ENOTDIR') { + throw entries; + } + } + /* c8 ignore stop */ + if (opt.filter && !opt.filter(path, ent)) { + return false; + } + // is a file + ignoreENOENTSync(() => rimrafWindowsFileSync(path, opt)); + return true; + } + let removedAll = true; + for (const ent of entries) { + const s = state === START ? CHILD : state; + const p = resolve(path, ent.name); + removedAll = rimrafWindowsDirSync(p, opt, ent, s) && removedAll; + } + if (state === START) { + return rimrafWindowsDirSync(path, opt, ent, FINISH); + } + else if (state === FINISH) { + if (opt.preserveRoot === false && path === parse(path).root) { + return false; + } + if (!removedAll) { + return false; + } + if (opt.filter && !opt.filter(path, ent)) { + return false; + } + ignoreENOENTSync(() => { + rimrafWindowsDirMoveRemoveFallbackSync(path, opt); + }); + } + return true; +}; +//# sourceMappingURL=rimraf-windows.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/rimraf-windows.js.map b/node_modules/rimraf/dist/esm/rimraf-windows.js.map new file mode 100644 index 0000000..4b136c1 --- /dev/null +++ b/node_modules/rimraf/dist/esm/rimraf-windows.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rimraf-windows.js","sourceRoot":"","sources":["../../src/rimraf-windows.ts"],"names":[],"mappings":"AAAA,+DAA+D;AAC/D,EAAE;AACF,sEAAsE;AACtE,wEAAwE;AACxE,gCAAgC;AAChC,0EAA0E;AAC1E,sBAAsB;AACtB,EAAE;AACF,yEAAyE;AAGzE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAErC,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AACvD,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AACpE,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AACnE,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAA;AAC1E,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAC1D,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAA;AAChF,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,QAAQ,CAAA;AAEzC,MAAM,iBAAiB,GAAG,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAA;AACrD,MAAM,qBAAqB,GAAG,aAAa,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC,CAAA;AACrE,MAAM,qBAAqB,GAAG,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAA;AACxD,MAAM,yBAAyB,GAAG,aAAa,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC,CAAA;AAExE,MAAM,kCAAkC,GAAG,KAAK,EAC9C,IAAY,EACZ,GAAuB,EACL,EAAE;IACpB,qBAAqB;IACrB,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,oBAAoB;IACpB,uEAAuE;IACvE,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,EAAE,GAAG,GAAG,CAAA;IAClC,IAAI,CAAC;QACH,OAAO,MAAM,qBAAqB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IACnD,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,IAAK,EAA4B,EAAE,IAAI,KAAK,WAAW,EAAE,CAAC;YACxD,OAAO,MAAM,gBAAgB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;QAC9C,CAAC;QACD,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAED,MAAM,sCAAsC,GAAG,CAC7C,IAAY,EACZ,GAAsB,EACb,EAAE;IACX,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,uEAAuE;IACvE,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,EAAE,GAAG,GAAG,CAAA;IAClC,IAAI,CAAC;QACH,OAAO,yBAAyB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IACjD,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,MAAM,GAAG,GAAG,EAA2B,CAAA;QACvC,IAAI,GAAG,EAAE,IAAI,KAAK,WAAW,EAAE,CAAC;YAC9B,OAAO,oBAAoB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;QAC5C,CAAC;QACD,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAED,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,CAAA;AAC7B,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,CAAA;AAC7B,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAA;AAE/B,MAAM,CAAC,MAAM,aAAa,GAAG,KAAK,EAAE,IAAY,EAAE,GAAuB,EAAE,EAAE;IAC3E,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,IAAI,CAAC;QACH,OAAO,MAAM,gBAAgB,CAAC,IAAI,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,CAAA;IACpE,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,IAAK,EAA4B,EAAE,IAAI,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAA;QACjE,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,IAAY,EAAE,GAAsB,EAAE,EAAE;IACxE,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IACD,IAAI,CAAC;QACH,OAAO,oBAAoB,CAAC,IAAI,EAAE,GAAG,EAAE,SAAS,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,CAAA;IAChE,CAAC;IAAC,OAAO,EAAE,EAAE,CAAC;QACZ,IAAK,EAA4B,EAAE,IAAI,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAA;QACjE,MAAM,EAAE,CAAA;IACV,CAAC;AACH,CAAC,CAAA;AAED,MAAM,gBAAgB,GAAG,KAAK,EAC5B,IAAY,EACZ,GAAuB,EACvB,GAAmB,EACnB,KAAK,GAAG,KAAK,EACK,EAAE;IACpB,IAAI,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;QACzB,MAAM,GAAG,CAAC,MAAM,CAAC,MAAM,CAAA;IACzB,CAAC;IAED,MAAM,OAAO,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,MAAM,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACrE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,gEAAgE;QAChE,oDAAoD;QACpD,qBAAqB;QACrB,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC9B,OAAO,IAAI,CAAA;YACb,CAAC;YACD,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;gBAC/B,MAAM,OAAO,CAAA;YACf,CAAC;QACH,CAAC;QACD,oBAAoB;QACpB,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC;YACjD,OAAO,KAAK,CAAA;QACd,CAAC;QACD,YAAY;QACZ,MAAM,YAAY,CAAC,iBAAiB,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAA;QAChD,OAAO,IAAI,CAAA;IACb,CAAC;IAED,MAAM,CAAC,GAAG,KAAK,KAAK,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAA;IACzC,MAAM,UAAU,GAAG,CACjB,MAAM,OAAO,CAAC,GAAG,CACf,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAChB,gBAAgB,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,CACvD,CACF,CACF,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAA;IAEhC,IAAI,KAAK,KAAK,KAAK,EAAE,CAAC;QACpB,OAAO,gBAAgB,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,CAAC,CAAA;IACjD,CAAC;SAAM,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC;QAC5B,IAAI,GAAG,CAAC,YAAY,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;YAC5D,OAAO,KAAK,CAAA;QACd,CAAC;QACD,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,OAAO,KAAK,CAAA;QACd,CAAC;QACD,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC;YACjD,OAAO,KAAK,CAAA;QACd,CAAC;QACD,MAAM,YAAY,CAAC,kCAAkC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAA;IACnE,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC,CAAA;AAED,MAAM,oBAAoB,GAAG,CAC3B,IAAY,EACZ,GAAsB,EACtB,GAAmB,EACnB,KAAK,GAAG,KAAK,EACJ,EAAE;IACX,MAAM,OAAO,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACnE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,gEAAgE;QAChE,oDAAoD;QACpD,qBAAqB;QACrB,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC9B,OAAO,IAAI,CAAA;YACb,CAAC;YACD,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;gBAC/B,MAAM,OAAO,CAAA;YACf,CAAC;QACH,CAAC;QACD,oBAAoB;QACpB,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzC,OAAO,KAAK,CAAA;QACd,CAAC;QACD,YAAY;QACZ,gBAAgB,CAAC,GAAG,EAAE,CAAC,qBAAqB,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAA;QACxD,OAAO,IAAI,CAAA;IACb,CAAC;IAED,IAAI,UAAU,GAAG,IAAI,CAAA;IACrB,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE,CAAC;QAC1B,MAAM,CAAC,GAAG,KAAK,KAAK,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAA;QACzC,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,CAAA;QACjC,UAAU,GAAG,oBAAoB,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,IAAI,UAAU,CAAA;IACjE,CAAC;IAED,IAAI,KAAK,KAAK,KAAK,EAAE,CAAC;QACpB,OAAO,oBAAoB,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,CAAC,CAAA;IACrD,CAAC;SAAM,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC;QAC5B,IAAI,GAAG,CAAC,YAAY,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;YAC5D,OAAO,KAAK,CAAA;QACd,CAAC;QACD,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,OAAO,KAAK,CAAA;QACd,CAAC;QACD,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzC,OAAO,KAAK,CAAA;QACd,CAAC;QACD,gBAAgB,CAAC,GAAG,EAAE;YACpB,sCAAsC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;QACnD,CAAC,CAAC,CAAA;IACJ,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC,CAAA","sourcesContent":["// This is the same as rimrafPosix, with the following changes:\n//\n// 1. EBUSY, ENFILE, EMFILE trigger retries and/or exponential backoff\n// 2. All non-directories are removed first and then all directories are\n// removed in a second sweep.\n// 3. If we hit ENOTEMPTY in the second sweep, fall back to move-remove on\n// the that folder.\n//\n// Note: \"move then remove\" is 2-10 times slower, and just as unreliable.\n\nimport { Dirent, Stats } from 'fs'\nimport { parse, resolve } from 'path'\nimport { RimrafAsyncOptions, RimrafSyncOptions } from './index.js'\nimport { fixEPERM, fixEPERMSync } from './fix-eperm.js'\nimport { lstatSync, promises, rmdirSync, unlinkSync } from './fs.js'\nimport { ignoreENOENT, ignoreENOENTSync } from './ignore-enoent.js'\nimport { readdirOrError, readdirOrErrorSync } from './readdir-or-error.js'\nimport { retryBusy, retryBusySync } from './retry-busy.js'\nimport { rimrafMoveRemove, rimrafMoveRemoveSync } from './rimraf-move-remove.js'\nconst { unlink, rmdir, lstat } = promises\n\nconst rimrafWindowsFile = retryBusy(fixEPERM(unlink))\nconst rimrafWindowsFileSync = retryBusySync(fixEPERMSync(unlinkSync))\nconst rimrafWindowsDirRetry = retryBusy(fixEPERM(rmdir))\nconst rimrafWindowsDirRetrySync = retryBusySync(fixEPERMSync(rmdirSync))\n\nconst rimrafWindowsDirMoveRemoveFallback = async (\n path: string,\n opt: RimrafAsyncOptions,\n): Promise => {\n /* c8 ignore start */\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n /* c8 ignore stop */\n // already filtered, remove from options so we don't call unnecessarily\n const { filter, ...options } = opt\n try {\n return await rimrafWindowsDirRetry(path, options)\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'ENOTEMPTY') {\n return await rimrafMoveRemove(path, options)\n }\n throw er\n }\n}\n\nconst rimrafWindowsDirMoveRemoveFallbackSync = (\n path: string,\n opt: RimrafSyncOptions,\n): boolean => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n // already filtered, remove from options so we don't call unnecessarily\n const { filter, ...options } = opt\n try {\n return rimrafWindowsDirRetrySync(path, options)\n } catch (er) {\n const fer = er as NodeJS.ErrnoException\n if (fer?.code === 'ENOTEMPTY') {\n return rimrafMoveRemoveSync(path, options)\n }\n throw er\n }\n}\n\nconst START = Symbol('start')\nconst CHILD = Symbol('child')\nconst FINISH = Symbol('finish')\n\nexport const rimrafWindows = async (path: string, opt: RimrafAsyncOptions) => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n try {\n return await rimrafWindowsDir(path, opt, await lstat(path), START)\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'ENOENT') return true\n throw er\n }\n}\n\nexport const rimrafWindowsSync = (path: string, opt: RimrafSyncOptions) => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n try {\n return rimrafWindowsDirSync(path, opt, lstatSync(path), START)\n } catch (er) {\n if ((er as NodeJS.ErrnoException)?.code === 'ENOENT') return true\n throw er\n }\n}\n\nconst rimrafWindowsDir = async (\n path: string,\n opt: RimrafAsyncOptions,\n ent: Dirent | Stats,\n state = START,\n): Promise => {\n if (opt?.signal?.aborted) {\n throw opt.signal.reason\n }\n\n const entries = ent.isDirectory() ? await readdirOrError(path) : null\n if (!Array.isArray(entries)) {\n // this can only happen if lstat/readdir lied, or if the dir was\n // swapped out with a file at just the right moment.\n /* c8 ignore start */\n if (entries) {\n if (entries.code === 'ENOENT') {\n return true\n }\n if (entries.code !== 'ENOTDIR') {\n throw entries\n }\n }\n /* c8 ignore stop */\n if (opt.filter && !(await opt.filter(path, ent))) {\n return false\n }\n // is a file\n await ignoreENOENT(rimrafWindowsFile(path, opt))\n return true\n }\n\n const s = state === START ? CHILD : state\n const removedAll = (\n await Promise.all(\n entries.map(ent =>\n rimrafWindowsDir(resolve(path, ent.name), opt, ent, s),\n ),\n )\n ).reduce((a, b) => a && b, true)\n\n if (state === START) {\n return rimrafWindowsDir(path, opt, ent, FINISH)\n } else if (state === FINISH) {\n if (opt.preserveRoot === false && path === parse(path).root) {\n return false\n }\n if (!removedAll) {\n return false\n }\n if (opt.filter && !(await opt.filter(path, ent))) {\n return false\n }\n await ignoreENOENT(rimrafWindowsDirMoveRemoveFallback(path, opt))\n }\n return true\n}\n\nconst rimrafWindowsDirSync = (\n path: string,\n opt: RimrafSyncOptions,\n ent: Dirent | Stats,\n state = START,\n): boolean => {\n const entries = ent.isDirectory() ? readdirOrErrorSync(path) : null\n if (!Array.isArray(entries)) {\n // this can only happen if lstat/readdir lied, or if the dir was\n // swapped out with a file at just the right moment.\n /* c8 ignore start */\n if (entries) {\n if (entries.code === 'ENOENT') {\n return true\n }\n if (entries.code !== 'ENOTDIR') {\n throw entries\n }\n }\n /* c8 ignore stop */\n if (opt.filter && !opt.filter(path, ent)) {\n return false\n }\n // is a file\n ignoreENOENTSync(() => rimrafWindowsFileSync(path, opt))\n return true\n }\n\n let removedAll = true\n for (const ent of entries) {\n const s = state === START ? CHILD : state\n const p = resolve(path, ent.name)\n removedAll = rimrafWindowsDirSync(p, opt, ent, s) && removedAll\n }\n\n if (state === START) {\n return rimrafWindowsDirSync(path, opt, ent, FINISH)\n } else if (state === FINISH) {\n if (opt.preserveRoot === false && path === parse(path).root) {\n return false\n }\n if (!removedAll) {\n return false\n }\n if (opt.filter && !opt.filter(path, ent)) {\n return false\n }\n ignoreENOENTSync(() => {\n rimrafWindowsDirMoveRemoveFallbackSync(path, opt)\n })\n }\n return true\n}\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/use-native.d.ts b/node_modules/rimraf/dist/esm/use-native.d.ts new file mode 100644 index 0000000..e191fd9 --- /dev/null +++ b/node_modules/rimraf/dist/esm/use-native.d.ts @@ -0,0 +1,4 @@ +import { RimrafAsyncOptions, RimrafOptions } from './index.js'; +export declare const useNative: (opt?: RimrafAsyncOptions) => boolean; +export declare const useNativeSync: (opt?: RimrafOptions) => boolean; +//# sourceMappingURL=use-native.d.ts.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/use-native.d.ts.map b/node_modules/rimraf/dist/esm/use-native.d.ts.map new file mode 100644 index 0000000..b182beb --- /dev/null +++ b/node_modules/rimraf/dist/esm/use-native.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"use-native.d.ts","sourceRoot":"","sources":["../../src/use-native.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAa9D,eAAO,MAAM,SAAS,EAAE,CAAC,GAAG,CAAC,EAAE,kBAAkB,KAAK,OAGf,CAAA;AACvC,eAAO,MAAM,aAAa,EAAE,CAAC,GAAG,CAAC,EAAE,aAAa,KAAK,OAGd,CAAA"} \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/use-native.js b/node_modules/rimraf/dist/esm/use-native.js new file mode 100644 index 0000000..bf1ea5a --- /dev/null +++ b/node_modules/rimraf/dist/esm/use-native.js @@ -0,0 +1,16 @@ +import platform from './platform.js'; +const version = process.env.__TESTING_RIMRAF_NODE_VERSION__ || process.version; +const versArr = version.replace(/^v/, '').split('.'); +/* c8 ignore start */ +const [major = 0, minor = 0] = versArr.map(v => parseInt(v, 10)); +/* c8 ignore stop */ +const hasNative = major > 14 || (major === 14 && minor >= 14); +// we do NOT use native by default on Windows, because Node's native +// rm implementation is less advanced. Change this code if that changes. +export const useNative = !hasNative || platform === 'win32' ? + () => false + : opt => !opt?.signal && !opt?.filter; +export const useNativeSync = !hasNative || platform === 'win32' ? + () => false + : opt => !opt?.signal && !opt?.filter; +//# sourceMappingURL=use-native.js.map \ No newline at end of file diff --git a/node_modules/rimraf/dist/esm/use-native.js.map b/node_modules/rimraf/dist/esm/use-native.js.map new file mode 100644 index 0000000..32da371 --- /dev/null +++ b/node_modules/rimraf/dist/esm/use-native.js.map @@ -0,0 +1 @@ +{"version":3,"file":"use-native.js","sourceRoot":"","sources":["../../src/use-native.ts"],"names":[],"mappings":"AACA,OAAO,QAAQ,MAAM,eAAe,CAAA;AAEpC,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,+BAA+B,IAAI,OAAO,CAAC,OAAO,CAAA;AAC9E,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;AAEpD,qBAAqB;AACrB,MAAM,CAAC,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAA;AAChE,oBAAoB;AACpB,MAAM,SAAS,GAAG,KAAK,GAAG,EAAE,IAAI,CAAC,KAAK,KAAK,EAAE,IAAI,KAAK,IAAI,EAAE,CAAC,CAAA;AAE7D,oEAAoE;AACpE,yEAAyE;AACzE,MAAM,CAAC,MAAM,SAAS,GACpB,CAAC,SAAS,IAAI,QAAQ,KAAK,OAAO,CAAC,CAAC;IAClC,GAAG,EAAE,CAAC,KAAK;IACb,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,MAAM,IAAI,CAAC,GAAG,EAAE,MAAM,CAAA;AACvC,MAAM,CAAC,MAAM,aAAa,GACxB,CAAC,SAAS,IAAI,QAAQ,KAAK,OAAO,CAAC,CAAC;IAClC,GAAG,EAAE,CAAC,KAAK;IACb,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,MAAM,IAAI,CAAC,GAAG,EAAE,MAAM,CAAA","sourcesContent":["import { RimrafAsyncOptions, RimrafOptions } from './index.js'\nimport platform from './platform.js'\n\nconst version = process.env.__TESTING_RIMRAF_NODE_VERSION__ || process.version\nconst versArr = version.replace(/^v/, '').split('.')\n\n/* c8 ignore start */\nconst [major = 0, minor = 0] = versArr.map(v => parseInt(v, 10))\n/* c8 ignore stop */\nconst hasNative = major > 14 || (major === 14 && minor >= 14)\n\n// we do NOT use native by default on Windows, because Node's native\n// rm implementation is less advanced. Change this code if that changes.\nexport const useNative: (opt?: RimrafAsyncOptions) => boolean =\n !hasNative || platform === 'win32' ?\n () => false\n : opt => !opt?.signal && !opt?.filter\nexport const useNativeSync: (opt?: RimrafOptions) => boolean =\n !hasNative || platform === 'win32' ?\n () => false\n : opt => !opt?.signal && !opt?.filter\n"]} \ No newline at end of file diff --git a/node_modules/rimraf/package.json b/node_modules/rimraf/package.json new file mode 100644 index 0000000..212180c --- /dev/null +++ b/node_modules/rimraf/package.json @@ -0,0 +1,89 @@ +{ + "name": "rimraf", + "version": "5.0.10", + "publishConfig": { + "tag": "v5-legacy" + }, + "type": "module", + "tshy": { + "main": true, + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "bin": "./dist/esm/bin.mjs", + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "files": [ + "dist" + ], + "description": "A deep deletion module for node (like `rm -rf`)", + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC", + "repository": "git://github.com/isaacs/rimraf.git", + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "prepare": "tshy", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "format": "prettier --write . --log-level warn", + "benchmark": "node benchmark/index.js", + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" + }, + "prettier": { + "experimentalTernaries": true, + "semi": false, + "printWidth": 80, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "devDependencies": { + "@types/node": "^20.12.11", + "mkdirp": "^3.0.1", + "prettier": "^3.2.5", + "tap": "^19.0.1", + "tshy": "^1.14.0", + "typedoc": "^0.25.13", + "typescript": "^5.4.5" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "dependencies": { + "glob": "^10.3.7" + }, + "keywords": [ + "rm", + "rm -rf", + "rm -fr", + "remove", + "directory", + "cli", + "rmdir", + "recursive" + ], + "module": "./dist/esm/index.js" +} diff --git a/node_modules/run-parallel/LICENSE b/node_modules/run-parallel/LICENSE new file mode 100644 index 0000000..c7e6852 --- /dev/null +++ b/node_modules/run-parallel/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/run-parallel/README.md b/node_modules/run-parallel/README.md new file mode 100644 index 0000000..edc3da4 --- /dev/null +++ b/node_modules/run-parallel/README.md @@ -0,0 +1,85 @@ +# run-parallel [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/run-parallel/master.svg +[travis-url]: https://travis-ci.org/feross/run-parallel +[npm-image]: https://img.shields.io/npm/v/run-parallel.svg +[npm-url]: https://npmjs.org/package/run-parallel +[downloads-image]: https://img.shields.io/npm/dm/run-parallel.svg +[downloads-url]: https://npmjs.org/package/run-parallel +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +### Run an array of functions in parallel + +![parallel](https://raw.githubusercontent.com/feross/run-parallel/master/img.png) [![Sauce Test Status](https://saucelabs.com/browser-matrix/run-parallel.svg)](https://saucelabs.com/u/run-parallel) + +### install + +``` +npm install run-parallel +``` + +### usage + +#### parallel(tasks, [callback]) + +Run the `tasks` array of functions in parallel, without waiting until the previous +function has completed. If any of the functions pass an error to its callback, the main +`callback` is immediately called with the value of the error. Once the `tasks` have +completed, the results are passed to the final `callback` as an array. + +It is also possible to use an object instead of an array. Each property will be run as a +function and the results will be passed to the final `callback` as an object instead of +an array. This can be a more readable way of handling the results. + +##### arguments + +- `tasks` - An array or object containing functions to run. Each function is passed a +`callback(err, result)` which it must call on completion with an error `err` (which can +be `null`) and an optional `result` value. +- `callback(err, results)` - An optional callback to run once all the functions have +completed. This function gets a results array (or object) containing all the result +arguments passed to the task callbacks. + +##### example + +```js +var parallel = require('run-parallel') + +parallel([ + function (callback) { + setTimeout(function () { + callback(null, 'one') + }, 200) + }, + function (callback) { + setTimeout(function () { + callback(null, 'two') + }, 100) + } +], +// optional callback +function (err, results) { + // the results array will equal ['one','two'] even though + // the second function had a shorter timeout. +}) +``` + +This module is basically equavalent to +[`async.parallel`](https://github.com/caolan/async#paralleltasks-callback), but it's +handy to just have the one function you need instead of the kitchen sink. Modularity! +Especially handy if you're serving to the browser and need to reduce your javascript +bundle size. + +Works great in the browser with [browserify](http://browserify.org/)! + +### see also + +- [run-auto](https://github.com/feross/run-auto) +- [run-parallel-limit](https://github.com/feross/run-parallel-limit) +- [run-series](https://github.com/feross/run-series) +- [run-waterfall](https://github.com/feross/run-waterfall) + +### license + +MIT. Copyright (c) [Feross Aboukhadijeh](http://feross.org). diff --git a/node_modules/run-parallel/index.js b/node_modules/run-parallel/index.js new file mode 100644 index 0000000..6307141 --- /dev/null +++ b/node_modules/run-parallel/index.js @@ -0,0 +1,51 @@ +/*! run-parallel. MIT License. Feross Aboukhadijeh */ +module.exports = runParallel + +const queueMicrotask = require('queue-microtask') + +function runParallel (tasks, cb) { + let results, pending, keys + let isSync = true + + if (Array.isArray(tasks)) { + results = [] + pending = tasks.length + } else { + keys = Object.keys(tasks) + results = {} + pending = keys.length + } + + function done (err) { + function end () { + if (cb) cb(err, results) + cb = null + } + if (isSync) queueMicrotask(end) + else end() + } + + function each (i, err, result) { + results[i] = result + if (--pending === 0 || err) { + done(err) + } + } + + if (!pending) { + // empty + done(null) + } else if (keys) { + // object + keys.forEach(function (key) { + tasks[key](function (err, result) { each(key, err, result) }) + }) + } else { + // array + tasks.forEach(function (task, i) { + task(function (err, result) { each(i, err, result) }) + }) + } + + isSync = false +} diff --git a/node_modules/run-parallel/package.json b/node_modules/run-parallel/package.json new file mode 100644 index 0000000..1f14757 --- /dev/null +++ b/node_modules/run-parallel/package.json @@ -0,0 +1,58 @@ +{ + "name": "run-parallel", + "description": "Run an array of functions in parallel", + "version": "1.2.0", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/run-parallel/issues" + }, + "dependencies": { + "queue-microtask": "^1.2.2" + }, + "devDependencies": { + "airtap": "^3.0.0", + "standard": "*", + "tape": "^5.0.1" + }, + "homepage": "https://github.com/feross/run-parallel", + "keywords": [ + "parallel", + "async", + "function", + "callback", + "asynchronous", + "run", + "array", + "run parallel" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/feross/run-parallel.git" + }, + "scripts": { + "test": "standard && npm run test-node && npm run test-browser", + "test-browser": "airtap -- test/*.js", + "test-browser-local": "airtap --local -- test/*.js", + "test-node": "tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/safe-array-concat/.eslintrc b/node_modules/safe-array-concat/.eslintrc new file mode 100644 index 0000000..fc909f1 --- /dev/null +++ b/node_modules/safe-array-concat/.eslintrc @@ -0,0 +1,15 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": "off", + "max-lines-per-function": "off", + "new-cap": ["error", { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/node_modules/safe-array-concat/.github/FUNDING.yml b/node_modules/safe-array-concat/.github/FUNDING.yml new file mode 100644 index 0000000..bbd94cd --- /dev/null +++ b/node_modules/safe-array-concat/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/safe-array-concat +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/safe-array-concat/.nycrc b/node_modules/safe-array-concat/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/safe-array-concat/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/safe-array-concat/CHANGELOG.md b/node_modules/safe-array-concat/CHANGELOG.md new file mode 100644 index 0000000..70d78df --- /dev/null +++ b/node_modules/safe-array-concat/CHANGELOG.md @@ -0,0 +1,58 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.2](https://github.com/ljharb/safe-array-concat/compare/v1.1.1...v1.1.2) - 2024-03-09 + +### Commits + +- [types] use a generic [`a1d744d`](https://github.com/ljharb/safe-array-concat/commit/a1d744d749033c91f0c108b28ac6dbc6016ecce4) +- [Dev Deps] update `@ljharb/tsconfig`, `set-function-length` [`3d3da0a`](https://github.com/ljharb/safe-array-concat/commit/3d3da0ab110bce21f466381c5d09f93200a20f85) + +## [v1.1.1](https://github.com/ljharb/safe-array-concat/compare/v1.1.0...v1.1.1) - 2024-03-09 + +### Commits + +- [types] use shared config [`f509f80`](https://github.com/ljharb/safe-array-concat/commit/f509f80fb2dd9734c309ccb59ca9451c5a5de885) +- [actions] remove redundant finisher; use reusable workflows [`b5f5ff4`](https://github.com/ljharb/safe-array-concat/commit/b5f5ff497976a48e291788b26b741cd4f3d388eb) +- [types] use handwritten d.ts instead of emit [`e717048`](https://github.com/ljharb/safe-array-concat/commit/e717048433b52d3a3240b7c697b5736756ed296e) +- [Dev Deps] update `set-function-length`, `tape` [`dde26a7`](https://github.com/ljharb/safe-array-concat/commit/dde26a7600ebe8ebc8f45d1bf8f1a970175604d8) +- [Deps] update `call-bind`, `get-intrinsic` [`d5d2cde`](https://github.com/ljharb/safe-array-concat/commit/d5d2cde9e5b7179d00d85e007b80b138969c5968) +- [Dev Deps] update `tape` [`9454c5a`](https://github.com/ljharb/safe-array-concat/commit/9454c5a3beacb08200b4b00b7ffa54a572cb76ab) +- [Tests] add `@arethetypeswrong/cli [`00a5243`](https://github.com/ljharb/safe-array-concat/commit/00a5243a5b923ff2b694b3b5ef4ce39027e30f6e) +- [Deps] update `get-intrinsic` [`c935764`](https://github.com/ljharb/safe-array-concat/commit/c9357646c3923a1351dca21f175b2b421dd15da5) + +## [v1.1.0](https://github.com/ljharb/safe-array-concat/compare/v1.0.1...v1.1.0) - 2024-01-15 + +### Commits + +- [New] add types [`bd92413`](https://github.com/ljharb/safe-array-concat/commit/bd92413643b2bd0ad62e854172fad129d3899dc1) +- [Dev Deps] update `aud`, `mock-property`, `npmignore`, `set-function-length`, `tape` [`497ffcb`](https://github.com/ljharb/safe-array-concat/commit/497ffcbb271ad61752756ec363ad5b9400e4d367) +- [Deps] update `call-bind`, `get-intrinsic` [`770f870`](https://github.com/ljharb/safe-array-concat/commit/770f8704d3751b947c7f4772d9ee38d8bcdecf44) +- [Dev Deps] update `mock-property`, `tape` [`be76bd9`](https://github.com/ljharb/safe-array-concat/commit/be76bd958fa73607a105122a8770677ecbdf78f0) +- [Tests] use `set-function-length/env` [`89b1167`](https://github.com/ljharb/safe-array-concat/commit/89b116758d91ad521f963cccf056f9a3f0b18c20) +- [meta] add missing npmrc values [`3185cc7`](https://github.com/ljharb/safe-array-concat/commit/3185cc7a6773baf625c65bb58ffb9b7ee5f3306e) +- [meta] add `sideEffects` flag [`df6c7eb`](https://github.com/ljharb/safe-array-concat/commit/df6c7ebca7f2fd2f152fe2c2a2260d21728e70a3) + +## [v1.0.1](https://github.com/ljharb/safe-array-concat/compare/v1.0.0...v1.0.1) - 2023-09-05 + +### Fixed + +- [Perf] set `Symbol.isConcatSpreadable` only when required [`#2`](https://github.com/ljharb/safe-array-concat/issues/2) + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`c0791b0`](https://github.com/ljharb/safe-array-concat/commit/c0791b00b74e70113921c32d4d1fd494b7e8f555) +- [Deps] update `get-intrinsic` [`7d07ae6`](https://github.com/ljharb/safe-array-concat/commit/7d07ae69d512bb3b6fb2131f1c824b5ffd85af9f) + +## v1.0.0 - 2023-04-20 + +### Commits + +- Initial implementation, tests, readme [`31b8e70`](https://github.com/ljharb/safe-array-concat/commit/31b8e709bbba4b01ebc51cc15cdcc7012fe58341) +- Initial commit [`83d38c6`](https://github.com/ljharb/safe-array-concat/commit/83d38c6f4cde453063393482d9129b134d403d0a) +- npm init [`516fdc2`](https://github.com/ljharb/safe-array-concat/commit/516fdc2bef306ec13f98b1f1b49c929b5308907f) +- Only apps should have lockfiles [`9cfa07b`](https://github.com/ljharb/safe-array-concat/commit/9cfa07b9112107b5ba22c74baca8cb80934a09f2) diff --git a/node_modules/safe-array-concat/LICENSE b/node_modules/safe-array-concat/LICENSE new file mode 100644 index 0000000..b4213ac --- /dev/null +++ b/node_modules/safe-array-concat/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/safe-array-concat/README.md b/node_modules/safe-array-concat/README.md new file mode 100644 index 0000000..c7e1d45 --- /dev/null +++ b/node_modules/safe-array-concat/README.md @@ -0,0 +1,53 @@ +# safe-array-concat [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +`Array.prototype.concat`, but made safe by ignoring Symbol.isConcatSpreadable + +## Getting started + +```sh +npm install --save safe-array-concat +``` + +## Usage/Examples + +```js +var safeConcat = require('safe-array-concat'); +var assert = require('assert'); + +assert.deepEqual([].concat([1, 2], 3, [[4]]), [1, 2, 3, [4]], 'arrays spread as expected with normal concat'); +assert.deepEqual(safeConcat([1, 2], 3, [[4]]), [1, 2, 3, [4]], 'arrays spread as expected with safe concat'); + +String.prototype[Symbol.isConcatSpreadable] = true; +assert.deepEqual([].concat('foo', Object('bar')), ['foo', 'b', 'a', 'r'], 'spreadable String objects are spread with normal concat!!!'); +assert.deepEqual(safeConcat('foo', Object('bar')), ['foo', Object('bar')], 'spreadable String objects are not spread with safe concat'); + +Array.prototype[Symbol.isConcatSpreadable] = false; +assert.deepEqual([].concat([1, 2], 3, [[4]]), [[], [1, 2], 3, [[4]]], 'non-concat-spreadable arrays do not spread with normal concat!!!'); +assert.deepEqual(safeConcat([1, 2], 3, [[4]]), [1, 2, 3, [4]], 'non-concat-spreadable arrays still spread with safe concat'); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/safe-array-concat +[npm-version-svg]: https://versionbadg.es/ljharb/safe-array-concat.svg +[deps-svg]: https://david-dm.org/ljharb/safe-array-concat.svg +[deps-url]: https://david-dm.org/ljharb/safe-array-concat +[dev-deps-svg]: https://david-dm.org/ljharb/safe-array-concat/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/safe-array-concat#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/safe-array-concat.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/safe-array-concat.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/safe-array-concat.svg +[downloads-url]: https://npm-stat.com/charts.html?package=safe-array-concat +[codecov-image]: https://codecov.io/gh/ljharb/safe-array-concat/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/safe-array-concat/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/safe-array-concat +[actions-url]: https://github.com/ljharb/safe-array-concat/actions diff --git a/node_modules/safe-array-concat/index.d.ts b/node_modules/safe-array-concat/index.d.ts new file mode 100644 index 0000000..4b204c0 --- /dev/null +++ b/node_modules/safe-array-concat/index.d.ts @@ -0,0 +1,3 @@ +declare function safeArrayConcat(item: T | T[], ...items: (T | T[])[]): T[]; + +export = safeArrayConcat; diff --git a/node_modules/safe-array-concat/index.js b/node_modules/safe-array-concat/index.js new file mode 100644 index 0000000..ec9119a --- /dev/null +++ b/node_modules/safe-array-concat/index.js @@ -0,0 +1,43 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var $concat = GetIntrinsic('%Array.prototype.concat%'); + +var callBind = require('call-bind'); + +var callBound = require('call-bind/callBound'); +var $slice = callBound('Array.prototype.slice'); + +var hasSymbols = require('has-symbols/shams')(); +var isConcatSpreadable = hasSymbols && Symbol.isConcatSpreadable; + +/** @type {never[]} */ var empty = []; +var $concatApply = isConcatSpreadable ? callBind.apply($concat, empty) : null; + +// eslint-disable-next-line no-extra-parens +var isArray = isConcatSpreadable ? /** @type {(value: unknown) => value is unknown[]} */ (require('isarray')) : null; + +/** @type {import('.')} */ +module.exports = isConcatSpreadable + // eslint-disable-next-line no-unused-vars + ? function safeArrayConcat(item) { + for (var i = 0; i < arguments.length; i += 1) { + /** @type {typeof item} */ var arg = arguments[i]; + // @ts-expect-error ts(2538) see https://github.com/microsoft/TypeScript/issues/9998#issuecomment-1890787975; works if `const` + if (arg && typeof arg === 'object' && typeof arg[isConcatSpreadable] === 'boolean') { + // @ts-expect-error ts(7015) TS doesn't yet support Symbol indexing + if (!empty[isConcatSpreadable]) { + // @ts-expect-error ts(7015) TS doesn't yet support Symbol indexing + empty[isConcatSpreadable] = true; + } + // @ts-expect-error ts(2721) ts(18047) not sure why TS can't figure out this can't be null + var arr = isArray(arg) ? $slice(arg) : [arg]; + // @ts-expect-error ts(7015) TS can't handle expandos on an array + arr[isConcatSpreadable] = true; // shadow the property. TODO: use [[Define]] + arguments[i] = arr; + } + } + // @ts-expect-error ts(2345) https://github.com/microsoft/TypeScript/issues/57164 TS doesn't understand that apply can take an arguments object + return $concatApply(arguments); + } + : callBind($concat, empty); diff --git a/node_modules/safe-array-concat/package.json b/node_modules/safe-array-concat/package.json new file mode 100644 index 0000000..1cee4fe --- /dev/null +++ b/node_modules/safe-array-concat/package.json @@ -0,0 +1,92 @@ +{ + "name": "safe-array-concat", + "version": "1.1.2", + "description": "`Array.prototype.concat`, but made safe by ignoring Symbol.isConcatSpreadable", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", + "prelint": "npm run tsc", + "lint": "eslint --ext=js,mjs .", + "tsc": "tsc -p .", + "posttsc": "attw -P", + "postlint": "evalmd README.md", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run lint", + "tests-only": "nyc tape test", + "test": "npm run tests-only", + "posttest": "aud --production" + }, + "keywords": [ + "safe", + "Array", + "concat", + "push", + "isConcatSpreadable" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/safe-array-concat.git" + }, + "bugs": { + "url": "https://github.com/ljharb/safe-array-concat/issues" + }, + "homepage": "https://github.com/ljharb/safe-array-concat#readme", + "devDependencies": { + "@arethetypeswrong/cli": "^0.15.1", + "@ljharb/eslint-config": "^21.1.0", + "@ljharb/tsconfig": "^0.2.0", + "@types/call-bind": "^1.0.5", + "@types/get-intrinsic": "^1.2.2", + "@types/has-symbols": "^1.0.2", + "@types/isarray": "^2.0.2", + "@types/mock-property": "^1.0.2", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "mock-property": "^1.0.3", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "set-function-length": "^1.2.2", + "tape": "^5.7.5", + "typescript": "next" + }, + "dependencies": { + "call-bind": "^1.0.7", + "get-intrinsic": "^1.2.4", + "has-symbols": "^1.0.3", + "isarray": "^2.0.5" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">=0.4" + } +} diff --git a/node_modules/safe-array-concat/test/index.js b/node_modules/safe-array-concat/test/index.js new file mode 100644 index 0000000..ce52abe --- /dev/null +++ b/node_modules/safe-array-concat/test/index.js @@ -0,0 +1,95 @@ +'use strict'; + +var test = require('tape'); +var mockProperty = require('mock-property'); +var hasSymbols = require('has-symbols/shams')(); +var isConcatSpreadable = hasSymbols && Symbol.isConcatSpreadable; +var species = hasSymbols && Symbol.species; + +var boundFnsHaveConfigurableLengths = require('set-function-length/env').boundFnsHaveConfigurableLengths; + +var safeConcat = require('../'); + +test('safe-array-concat', function (t) { + t.equal(typeof safeConcat, 'function', 'is a function'); + t.equal( + safeConcat.length, + boundFnsHaveConfigurableLengths ? 1 : 0, + 'has a length of ' + (boundFnsHaveConfigurableLengths ? 1 : '0 (function lengths are not configurable)') + ); + + t.deepEqual( + // eslint-disable-next-line no-extra-parens + safeConcat(/** @type {(string | number | number[])[]} */ ([1, 2]), [3, 4], 'foo', 5, 6, [[7]]), + [1, 2, 3, 4, 'foo', 5, 6, [7]], + 'works with flat and nested arrays' + ); + + t.deepEqual( + safeConcat(undefined, 1, 2), + [undefined, 1, 2], + 'first item as undefined is not the concat receiver, which would throw via ToObject' + ); + t.deepEqual( + safeConcat(null, 1, 2), + [null, 1, 2], + 'first item as null is not the concat receiver, which would throw via ToObject' + ); + + var arr = [1, 2]; + arr.constructor = function C() { + return { args: arguments }; + }; + t.deepEqual( + safeConcat(arr, 3, 4), + [1, 2, 3, 4], + 'first item as an array with a nonArray .constructor; ignores constructor' + ); + + t.test('has Symbol.species', { skip: !species }, function (st) { + var speciesArr = [1, 2]; + // @ts-expect-error ts(2740) TS's `constructor` type requires a function + speciesArr.constructor = {}; + // @ts-expect-error ts(2538) TS can't type narrow from tape's `skip` + speciesArr.constructor[species] = function Species() { + return { args: arguments }; + }; + + st.deepEqual( + safeConcat(speciesArr, 3, 4), + [1, 2, 3, 4], + 'first item as an array with a .constructor object with a Symbol.species; ignores constructor and species' + ); + + st.end(); + }); + + t.test('has isConcatSpreadable', { skip: !isConcatSpreadable }, function (st) { + // TS can't type narrow from tape's `skip` + if (isConcatSpreadable) { + st.teardown(mockProperty(String.prototype, isConcatSpreadable, { value: true })); + + var nonSpreadable = [1, 2]; + // @ts-expect-error ts(7015) TS can't handle expandos on an array + nonSpreadable[isConcatSpreadable] = false; + + st.deepEqual( + safeConcat(nonSpreadable, 3, 4, 'foo', Object('bar')), + [1, 2, 3, 4, 'foo', Object('bar')], + 'a non-concat-spreadable array is spreaded, and a concat-spreadable String is not spreaded' + ); + + st.teardown(mockProperty(Array.prototype, isConcatSpreadable, { value: false })); + + st.deepEqual( + safeConcat([1, 2], 3, 4, 'foo', Object('bar')), + [1, 2, 3, 4, 'foo', Object('bar')], + 'all arrays marked non-concat-spreadable are still spreaded, and a concat-spreadable String is not spreaded' + ); + } + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/safe-array-concat/tsconfig.json b/node_modules/safe-array-concat/tsconfig.json new file mode 100644 index 0000000..0ce1896 --- /dev/null +++ b/node_modules/safe-array-concat/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/safe-regex-test/.eslintrc b/node_modules/safe-regex-test/.eslintrc new file mode 100644 index 0000000..ff89be3 --- /dev/null +++ b/node_modules/safe-regex-test/.eslintrc @@ -0,0 +1,9 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + }, +} diff --git a/node_modules/safe-regex-test/.github/FUNDING.yml b/node_modules/safe-regex-test/.github/FUNDING.yml new file mode 100644 index 0000000..ef4a267 --- /dev/null +++ b/node_modules/safe-regex-test/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/safe-regex-test +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/safe-regex-test/.nycrc b/node_modules/safe-regex-test/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/safe-regex-test/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/safe-regex-test/CHANGELOG.md b/node_modules/safe-regex-test/CHANGELOG.md new file mode 100644 index 0000000..850a489 --- /dev/null +++ b/node_modules/safe-regex-test/CHANGELOG.md @@ -0,0 +1,43 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.3](https://github.com/ljharb/safe-regex-test/compare/v1.0.2...v1.0.3) - 2024-02-06 + +### Commits + +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`d6ba2f9`](https://github.com/ljharb/safe-regex-test/commit/d6ba2f948c679c3104ce6d6c897bedff0f1c5b74) +- [Deps] update `call-bind`, `get-intrinsic` [`5a3b1d7`](https://github.com/ljharb/safe-regex-test/commit/5a3b1d755e46f010e6930f15ec30eae023feffd3) +- [Dev Deps] update `tape` [`75fb719`](https://github.com/ljharb/safe-regex-test/commit/75fb71937c5daf1326052c59d6f251f439cd9332) + +## [v1.0.2](https://github.com/ljharb/safe-regex-test/compare/v1.0.1...v1.0.2) - 2024-01-11 + +### Commits + +- [meta] package.json `sideEffects` should be boolean [`094bb88`](https://github.com/ljharb/safe-regex-test/commit/094bb88d93ce25e26d20f5badee4e45acf0e3ac5) + +## [v1.0.1](https://github.com/ljharb/safe-regex-test/compare/v1.0.0...v1.0.1) - 2024-01-09 + +### Commits + +- [Tests] add nyc for coverage [`7e3f525`](https://github.com/ljharb/safe-regex-test/commit/7e3f5254efdf0979f72492f0e7f52a3a9814591f) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `npmignore`, `object-inspect`, `tape` [`e7e0169`](https://github.com/ljharb/safe-regex-test/commit/e7e016949b78602f24debc1185c26f33cc4e9d1b) +- [actions] update rebase action [`2962694`](https://github.com/ljharb/safe-regex-test/commit/2962694bce7ffa278e873911072c11119bb3a608) +- [readme] add testing badges; remove david-dm badges [`e9dfd83`](https://github.com/ljharb/safe-regex-test/commit/e9dfd830655ac702ac7b7947f7076bb524994968) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` [`496fe99`](https://github.com/ljharb/safe-regex-test/commit/496fe99aa66f20cadb1cf79f6d479b87ae95b620) +- [Deps] update `call-bind`, `get-intrinsic` [`d94c5ba`](https://github.com/ljharb/safe-regex-test/commit/d94c5badd0362df8ff7ced38b50d20550fd629c1) +- [meta] add missing `engines.node` [`f3d4711`](https://github.com/ljharb/safe-regex-test/commit/f3d4711a51b21330e34f5f27e45452fbdb924715) +- [Deps] update `get-intrinsic` [`0eeedd7`](https://github.com/ljharb/safe-regex-test/commit/0eeedd74d0313fab9b0718895c02905f702ecb4d) +- [meta] add `sideEffects` flag [`fe1655f`](https://github.com/ljharb/safe-regex-test/commit/fe1655f16449208d987d9f4b7dafb15564ca80f7) + +## v1.0.0 - 2022-09-22 + +### Commits + +- Initial implementation, tests, readme [`0273e9f`](https://github.com/ljharb/safe-regex-test/commit/0273e9f96f4b09df413523f4faacc8ae9ac5e6cb) +- Initial commit [`b6c1edf`](https://github.com/ljharb/safe-regex-test/commit/b6c1edf740e6105fb71c34c1c69fadd837e8f7ab) +- npm init [`c7f5765`](https://github.com/ljharb/safe-regex-test/commit/c7f576580607b16458b5a16e6bfa3b639e49c6bd) +- Only apps should have lockfiles [`1162bf0`](https://github.com/ljharb/safe-regex-test/commit/1162bf011835040f7e2c9936734294b2d98536bf) diff --git a/node_modules/safe-regex-test/LICENSE b/node_modules/safe-regex-test/LICENSE new file mode 100644 index 0000000..6abfe14 --- /dev/null +++ b/node_modules/safe-regex-test/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/safe-regex-test/README.md b/node_modules/safe-regex-test/README.md new file mode 100644 index 0000000..fca66d4 --- /dev/null +++ b/node_modules/safe-regex-test/README.md @@ -0,0 +1,46 @@ +# safe-regex-test [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Give a regex, get a robust predicate function that tests it against a string. This will work even if `RegExp.prototype` is altered later. + +## Getting started + +```sh +npm install --save safe-regex-test +``` + +## Usage/Examples + +```js +var regexTester = require('safe-regex-test'); +var assert = require('assert'); + +var tester = regexTester('a'); +assert.ok(tester('a')); +assert.notOk(tester('b')); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/safe-regex-test +[npm-version-svg]: https://versionbadg.es/ljharb/safe-regex-test.svg +[deps-svg]: https://david-dm.org/ljharb/safe-regex-test.svg +[deps-url]: https://david-dm.org/ljharb/safe-regex-test +[dev-deps-svg]: https://david-dm.org/ljharb/safe-regex-test/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/safe-regex-test#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/safe-regex-test.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/safe-regex-test.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/safe-regex-test.svg +[downloads-url]: https://npm-stat.com/charts.html?package=safe-regex-test +[codecov-image]: https://codecov.io/gh/ljharb/safe-regex-test/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/safe-regex-test/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/safe-regex-test +[actions-url]: https://github.com/ljharb/safe-regex-test/actions diff --git a/node_modules/safe-regex-test/index.js b/node_modules/safe-regex-test/index.js new file mode 100644 index 0000000..c57aad7 --- /dev/null +++ b/node_modules/safe-regex-test/index.js @@ -0,0 +1,16 @@ +'use strict'; + +var callBound = require('call-bind/callBound'); +var isRegex = require('is-regex'); + +var $exec = callBound('RegExp.prototype.exec'); +var $TypeError = require('es-errors/type'); + +module.exports = function regexTester(regex) { + if (!isRegex(regex)) { + throw new $TypeError('`regex` must be a RegExp'); + } + return function test(s) { + return $exec(regex, s) !== null; + }; +}; diff --git a/node_modules/safe-regex-test/package.json b/node_modules/safe-regex-test/package.json new file mode 100644 index 0000000..902178c --- /dev/null +++ b/node_modules/safe-regex-test/package.json @@ -0,0 +1,80 @@ +{ + "name": "safe-regex-test", + "version": "1.0.3", + "description": "Give a regex, get a robust predicate function that tests it against a string.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", + "lint": "eslint --ext=js,mjs .", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run lint", + "tests-only": "nyc tape test", + "test": "npm run tests-only", + "posttest": "aud --production" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/safe-regex-test.git" + }, + "keywords": [ + "regex", + "regexp", + "test", + "tester", + "safe", + "robust", + "exec" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/safe-regex-test/issues" + }, + "homepage": "https://github.com/ljharb/safe-regex-test#readme", + "dependencies": { + "call-bind": "^1.0.6", + "es-errors": "^1.3.0", + "is-regex": "^1.1.4" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "for-each": "^0.3.3", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/safe-regex-test/test/index.js b/node_modules/safe-regex-test/test/index.js new file mode 100644 index 0000000..a2e1f9d --- /dev/null +++ b/node_modules/safe-regex-test/test/index.js @@ -0,0 +1,37 @@ +'use strict'; + +var test = require('tape'); +var v = require('es-value-fixtures'); +var forEach = require('for-each'); +var inspect = require('object-inspect'); + +var regexTester = require('../'); + +test('regex tester', function (t) { + t.equal(typeof regexTester, 'function', 'is a function'); + + t.test('non-regexes', function (st) { + forEach(v.primitives.concat(v.objects), function (val) { + st['throws']( + function () { regexTester(val); }, + TypeError, + inspect(val) + ' is not a regex' + ); + }); + + st.end(); + }); + + t.test('regexes', function (st) { + var tester = regexTester(/a/); + + st.equal(typeof tester, 'function', 'returns a function'); + st.equal(tester('a'), true, 'returns true for a match'); + st.equal(tester('b'), false, 'returns false for a non-match'); + st.equal(tester('a'), true, 'returns true for a match again'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/section-matter/LICENSE b/node_modules/section-matter/LICENSE new file mode 100644 index 0000000..5385a09 --- /dev/null +++ b/node_modules/section-matter/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/section-matter/README.md b/node_modules/section-matter/README.md new file mode 100644 index 0000000..95a7a46 --- /dev/null +++ b/node_modules/section-matter/README.md @@ -0,0 +1,236 @@ +# section-matter [![NPM version](https://img.shields.io/npm/v/section-matter.svg?style=flat)](https://www.npmjs.com/package/section-matter) [![NPM monthly downloads](https://img.shields.io/npm/dm/section-matter.svg?style=flat)](https://npmjs.org/package/section-matter) [![NPM total downloads](https://img.shields.io/npm/dt/section-matter.svg?style=flat)](https://npmjs.org/package/section-matter) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/section-matter.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/section-matter) + +> Like front-matter, but supports multiple sections in a document. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save section-matter +``` + +## Usage + +**Params** + +* `input` **{String|Buffer|Object}**: If input is an object, it's `content` property must be a string or buffer. +* **{Object}**: options +* `returns` **{Object}**: Returns an object with a `content` string and an array of `sections` objects. + +**Example** + +```js +var sections = require('{%= name %}'); +var result = sections(input, options); +// { content: 'Content before sections', sections: [] } +``` + +See available [options](#options). + +## Example + +_With the exception of front-matter, **which must be the very first thing in the string**, the opening delimiter of all other sections must be followed by a string to be used as the `key` for the section._ + +Given the following string: + +``` +Content before the sections. + +--- + +More content. + +---one +title: One +--- + +This is the first section. +``` + +The following code: + +```js +console.log(sections(input)); +``` + +Results in: + +```js +{ + content: 'Content before the sections.\n\n---\n\nMore content.\n', + sections: [ + { + key: 'one', + data: 'title: One', + content: '\nThis is the first section.' + } + ] +} +``` + +## Options + +### options.section_parse + +**Type**: `function` + +**Default**: `undefined` + +Function to be called on each section after it's parsed from the string. + +**Example** + +Given the following string (`foo.md`): + +``` +This is content before the sections. + +---one +title: First section +--- + +This is section one. + +---two +title: Second section +--- + +This is section two. +``` + +Using the following custom `section_parse` function: + +```js +var fs = require('fs'); +var path = require('path'); +var yaml = require('js-yaml'); +var sections = require('section-matter'); + +var str = fs.readFileSync('foo.md'); +var options = { + section_parse: function(section) { + console.log(section) + section.key = 'section-' + section.key; + section.data = yaml.safeLoad(section.data); + } +}; + +var result = sections(str, options); +console.log(result); +``` + +Results in: + +```js +{ + content: 'This is content before the sections.\n', + sections: [ + { + key: 'section-one', + data: { title: 'First section' }, + content: '\nThis is section one.\n' + }, + { + key: 'section-two', + data: { title: 'Second section' }, + content: '\nThis is section two.\n' + } + ] +} +``` + +### options.section_delimiter + +**Type**: `string` + +**Default**: `---` + +Delimiter to use as the separator for sections. _With the exception of front-matter, which must be the very first thing in the string, the opening delimiter of all other sections must be followed by a string to be used as the `key` for the section._ + +**Example** + +```js +var input = '~~~\ntitle: bar\n~~~\n\nfoo\n~~~one\ntitle: One\n~~~\nThis is one'; +console.log(sections(input, {section_delimiter: '~~~'})); +``` + +Results in: + +```js +{ + content: '', + sections: [ + { + key: '', + data: 'title: bar', + content: '\nfoo' + }, + { + key: 'one', + data: 'title: One', + content: 'This is one' + } + ] +} +``` + +## About +
+ Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. + +
+ +
+ Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+ Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +You might also be interested in these projects: + +- [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") +- [gray-matter](https://www.npmjs.com/package/gray-matter): Parse front-matter from a string or file. Fast, reliable and easy to use. Parses YAML… [more](https://github.com/jonschlinkert/gray-matter) | [homepage](https://github.com/jonschlinkert/gray-matter "Parse front-matter from a string or file. Fast, reliable and easy to use. Parses YAML front matter by default, but also has support for YAML, JSON, TOML or Coffee Front-Matter, with options to set custom delimiters. Used by metalsmith, assemble, verb and ") +- [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") + +### Contributors + +### Author +**Jon Schlinkert** + ++ [github/jonschlinkert](https://github.com/jonschlinkert) ++ [twitter/jonschlinkert](https://twitter.com/jonschlinkert) + +### License +Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on October 23, 2017._ + diff --git a/node_modules/section-matter/index.js b/node_modules/section-matter/index.js new file mode 100644 index 0000000..2b4d21e --- /dev/null +++ b/node_modules/section-matter/index.js @@ -0,0 +1,136 @@ +'use strict'; + +var typeOf = require('kind-of'); +var extend = require('extend-shallow'); + +/** + * Parse sections in `input` with the given `options`. + * + * ```js + * var sections = require('{%= name %}'); + * var result = sections(input, options); + * // { content: 'Content before sections', sections: [] } + * ``` + * @param {String|Buffer|Object} `input` If input is an object, it's `content` property must be a string or buffer. + * @param {Object} options + * @return {Object} Returns an object with a `content` string and an array of `sections` objects. + * @api public + */ + +module.exports = function(input, options) { + if (typeof options === 'function') { + options = { parse: options }; + } + + var file = toObject(input); + var defaults = {section_delimiter: '---', parse: identity}; + var opts = extend({}, defaults, options); + var delim = opts.section_delimiter; + var lines = file.content.split(/\r?\n/); + var sections = null; + var section = createSection(); + var content = []; + var stack = []; + + function initSections(val) { + file.content = val; + sections = []; + content = []; + } + + function closeSection(val) { + if (stack.length) { + section.key = getKey(stack[0], delim); + section.content = val; + opts.parse(section, sections); + sections.push(section); + section = createSection(); + content = []; + stack = []; + } + } + + for (var i = 0; i < lines.length; i++) { + var line = lines[i]; + var len = stack.length; + var ln = line.trim(); + + if (isDelimiter(ln, delim)) { + if (ln.length === 3 && i !== 0) { + if (len === 0 || len === 2) { + content.push(line); + continue; + } + stack.push(ln); + section.data = content.join('\n'); + content = []; + continue; + } + + if (sections === null) { + initSections(content.join('\n')); + } + + if (len === 2) { + closeSection(content.join('\n')); + } + + stack.push(ln); + continue; + } + + content.push(line); + } + + if (sections === null) { + initSections(content.join('\n')); + } else { + closeSection(content.join('\n')); + } + + file.sections = sections; + return file; +}; + +function isDelimiter(line, delim) { + if (line.slice(0, delim.length) !== delim) { + return false; + } + if (line.charAt(delim.length + 1) === delim.slice(-1)) { + return false; + } + return true; +} + +function toObject(input) { + if (typeOf(input) !== 'object') { + input = { content: input }; + } + + if (typeof input.content !== 'string' && !isBuffer(input.content)) { + throw new TypeError('expected a buffer or string'); + } + + input.content = input.content.toString(); + input.sections = []; + return input; +} + +function getKey(val, delim) { + return val ? val.slice(delim.length).trim() : ''; +} + +function createSection() { + return { key: '', data: '', content: '' }; +} + +function identity(val) { + return val; +} + +function isBuffer(val) { + if (val && val.constructor && typeof val.constructor.isBuffer === 'function') { + return val.constructor.isBuffer(val); + } + return false; +} diff --git a/node_modules/section-matter/package.json b/node_modules/section-matter/package.json new file mode 100644 index 0000000..a706c6d --- /dev/null +++ b/node_modules/section-matter/package.json @@ -0,0 +1,55 @@ +{ + "name": "section-matter", + "description": "Like front-matter, but supports multiple sections in a document.", + "version": "1.0.0", + "homepage": "https://github.com/jonschlinkert/section-matter", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "repository": "jonschlinkert/section-matter", + "bugs": { + "url": "https://github.com/jonschlinkert/section-matter/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=4" + }, + "scripts": { + "test": "mocha" + }, + "dependencies": { + "extend-shallow": "^2.0.1", + "kind-of": "^6.0.0" + }, + "devDependencies": { + "gulp-format-md": "^1.0.0", + "js-yaml": "^3.10.0", + "mocha": "^4.0.1" + }, + "keywords": [ + "matter", + "section" + ], + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "related": { + "list": [ + "gray-matter", + "assemble", + "verb" + ] + }, + "lint": { + "reflinks": true + } + } +} diff --git a/node_modules/semver-compare/.travis.yml b/node_modules/semver-compare/.travis.yml new file mode 100644 index 0000000..8d4715c --- /dev/null +++ b/node_modules/semver-compare/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.8" + - "0.10" +before_install: + - npm install -g npm diff --git a/node_modules/semver-compare/LICENSE b/node_modules/semver-compare/LICENSE new file mode 100644 index 0000000..ee27ba4 --- /dev/null +++ b/node_modules/semver-compare/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/semver-compare/example/cmp.js b/node_modules/semver-compare/example/cmp.js new file mode 100644 index 0000000..458eae1 --- /dev/null +++ b/node_modules/semver-compare/example/cmp.js @@ -0,0 +1,13 @@ +var cmp = require('../'); +var versions = [ + '1.2.3', + '4.11.6', + '4.2.0', + '1.5.19', + '1.5.5', + '4.1.3', + '2.3.1', + '10.5.5', + '11.3.0' +]; +console.log(versions.sort(cmp).join('\n')); diff --git a/node_modules/semver-compare/example/lex.js b/node_modules/semver-compare/example/lex.js new file mode 100644 index 0000000..c04d9f6 --- /dev/null +++ b/node_modules/semver-compare/example/lex.js @@ -0,0 +1,12 @@ +var versions = [ + '1.2.3', + '4.11.6', + '4.2.0', + '1.5.19', + '1.5.5', + '4.1.3', + '2.3.1', + '10.5.5', + '11.3.0' +]; +console.log(versions.sort().join('\n')); diff --git a/node_modules/semver-compare/index.js b/node_modules/semver-compare/index.js new file mode 100644 index 0000000..cec978d --- /dev/null +++ b/node_modules/semver-compare/index.js @@ -0,0 +1,13 @@ +module.exports = function cmp (a, b) { + var pa = a.split('.'); + var pb = b.split('.'); + for (var i = 0; i < 3; i++) { + var na = Number(pa[i]); + var nb = Number(pb[i]); + if (na > nb) return 1; + if (nb > na) return -1; + if (!isNaN(na) && isNaN(nb)) return 1; + if (isNaN(na) && !isNaN(nb)) return -1; + } + return 0; +}; diff --git a/node_modules/semver-compare/package.json b/node_modules/semver-compare/package.json new file mode 100644 index 0000000..0b111ff --- /dev/null +++ b/node_modules/semver-compare/package.json @@ -0,0 +1,31 @@ +{ + "name": "semver-compare", + "version": "1.0.0", + "description": "compare two semver version strings, returning -1, 0, or 1", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "tape": "^3.0.0" + }, + "scripts": { + "test": "tape test/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/substack/semver-compare.git" + }, + "homepage": "https://github.com/substack/semver-compare", + "keywords": [ + "semver", + "compare", + "cmp", + "comparison", + "sort" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "license": "MIT" +} diff --git a/node_modules/semver-compare/readme.markdown b/node_modules/semver-compare/readme.markdown new file mode 100644 index 0000000..927a369 --- /dev/null +++ b/node_modules/semver-compare/readme.markdown @@ -0,0 +1,77 @@ +# semver-compare + +compare two semver version strings, returning -1, 0, or 1 + +The return value can be fed straight into `[].sort`. + +[![build status](https://secure.travis-ci.org/substack/semver-compare.png)](http://travis-ci.org/substack/semver-compare) + +# example + +``` js +var cmp = require('semver-compare'); +var versions = [ + '1.2.3', + '4.11.6', + '4.2.0', + '1.5.19', + '1.5.5', + '4.1.3', + '2.3.1', + '10.5.5', + '11.3.0' +]; +console.log(versions.sort(cmp).join('\n')); +``` + +prints: + +``` +1.2.3 +1.5.5 +1.5.19 +2.3.1 +4.1.3 +4.2.0 +4.11.6 +10.5.5 +11.3.0 +``` + +whereas the default lexicographic sort (`versions.sort()`) would be: + +``` +1.2.3 +1.5.19 +1.5.5 +10.5.5 +11.3.0 +2.3.1 +4.1.3 +4.11.6 +4.2.0 +``` + +# methods + +``` +var cmp = require('semver-compare') +``` + +## cmp(a, b) + +If the semver string `a` is greater than `b`, return `1`. +If the semver string `b` is greater than `a`, return `-1`. +If `a` equals `b`, return 0; + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install semver-compare +``` + +# license + +MIT diff --git a/node_modules/semver-compare/test/cmp.js b/node_modules/semver-compare/test/cmp.js new file mode 100644 index 0000000..a706234 --- /dev/null +++ b/node_modules/semver-compare/test/cmp.js @@ -0,0 +1,29 @@ +var cmp = require('../'); +var test = require('tape'); + +var versions = [ + '1.2.3', + '4.11.6', + '4.2.0', + '1.5.19', + '1.5.5', + '4.1.3', + '2.3.1', + '10.5.5', + '11.3.0' +]; + +test('cmp', function (t) { + t.plan(1); + t.deepEqual(versions.sort(cmp), [ + '1.2.3', + '1.5.5', + '1.5.19', + '2.3.1', + '4.1.3', + '4.2.0', + '4.11.6', + '10.5.5', + '11.3.0' + ]); +}); diff --git a/node_modules/semver/LICENSE b/node_modules/semver/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/semver/README.md b/node_modules/semver/README.md new file mode 100644 index 0000000..ede7b7d --- /dev/null +++ b/node_modules/semver/README.md @@ -0,0 +1,654 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +You can also just load the module for the function that you care about if +you'd like to minimize your footprint. + +```js +// load the whole API at once in a single object +const semver = require('semver') + +// or just load the bits you need +// all of them listed here, just pick and choose what you want + +// classes +const SemVer = require('semver/classes/semver') +const Comparator = require('semver/classes/comparator') +const Range = require('semver/classes/range') + +// functions for working with versions +const semverParse = require('semver/functions/parse') +const semverValid = require('semver/functions/valid') +const semverClean = require('semver/functions/clean') +const semverInc = require('semver/functions/inc') +const semverDiff = require('semver/functions/diff') +const semverMajor = require('semver/functions/major') +const semverMinor = require('semver/functions/minor') +const semverPatch = require('semver/functions/patch') +const semverPrerelease = require('semver/functions/prerelease') +const semverCompare = require('semver/functions/compare') +const semverRcompare = require('semver/functions/rcompare') +const semverCompareLoose = require('semver/functions/compare-loose') +const semverCompareBuild = require('semver/functions/compare-build') +const semverSort = require('semver/functions/sort') +const semverRsort = require('semver/functions/rsort') + +// low-level comparators between versions +const semverGt = require('semver/functions/gt') +const semverLt = require('semver/functions/lt') +const semverEq = require('semver/functions/eq') +const semverNeq = require('semver/functions/neq') +const semverGte = require('semver/functions/gte') +const semverLte = require('semver/functions/lte') +const semverCmp = require('semver/functions/cmp') +const semverCoerce = require('semver/functions/coerce') + +// working with ranges +const semverSatisfies = require('semver/functions/satisfies') +const semverMaxSatisfying = require('semver/ranges/max-satisfying') +const semverMinSatisfying = require('semver/ranges/min-satisfying') +const semverToComparators = require('semver/ranges/to-comparators') +const semverMinVersion = require('semver/ranges/min-version') +const semverValidRange = require('semver/ranges/valid') +const semverOutside = require('semver/ranges/outside') +const semverGtr = require('semver/ranges/gtr') +const semverLtr = require('semver/ranges/ltr') +const semverIntersects = require('semver/ranges/intersects') +const semverSimplifyRange = require('semver/ranges/simplify') +const semverRangeSubset = require('semver/ranges/subset') +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-n <0|1> + This is the base to be used for the prerelease identifier. + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` that specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. The comparator `>1` is equivalent to `>=2.0.0` and +would match the versions `2.0.0` and `3.1.0`, but not the versions +`1.0.1` or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. +Version `3.4.5` *would* satisfy the range because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose of this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range-matching +semantics. + +Second, a user who has opted into using a prerelease version has +indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for range-matching) +by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +#### Prerelease Identifier Base + +The method `.inc` takes an optional parameter 'identifierBase' string +that will let you let your prerelease number as zero-based or one-based. +Set to `false` to omit the prerelease number altogether. +If you do not specify this parameter, it will default to zero-based. + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta', '1') +// '1.2.4-beta.1' +``` + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta', false) +// '1.2.4-beta' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta -n 1 +1.2.4-beta.1 +``` + +```bash +$ semver 1.2.3 -i prerelease --preid beta -n false +1.2.4-beta +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless + `includePrerelease` is specified, in which case any version at all + satisfies) +* `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero element in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0-0` +* `^0.2.3` := `>=0.2.3 <0.3.0-0` +* `^0.0.3` := `>=0.0.3 <0.0.4-0` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0-0` +* `^0.0.x` := `>=0.0.0 <0.1.0-0` +* `^0.0` := `>=0.0.0 <0.1.0-0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0-0` +* `^0.x` := `>=0.0.0 <1.0.0-0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose`: Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease`: Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release, options, identifier, identifierBase)`: + Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, `prerelease` will work the + same as `prepatch`. It increments the patch version and then makes a + prerelease. If the input version is already a prerelease it simply + increments it. + * `identifier` can be used to prefix `premajor`, `preminor`, + `prepatch`, or `prerelease` version increments. `identifierBase` + is the base to be used for the `prerelease` identifier. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of `compare`. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions + are equal. Sorts in ascending order if passed to `Array.sort()`. +* `compareLoose(v1, v2)`: Short for `compare(v1, v2, { loose: true })`. +* `diff(v1, v2)`: Returns the difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Sorting + +* `sort(versions)`: Returns a sorted array of versions based on the `compareBuild` + function. +* `rsort(versions)`: The reverse of `sort`. Returns an array of versions based on + the `compareBuild` function in descending order. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can match + the given range. +* `gtr(version, range)`: Return `true` if the version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if the version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the range comparators intersect. +* `simplifyRange(versions, range)`: Return a "simplified" range that + matches the same items in the `versions` list as the range specified. Note + that it does *not* guarantee that it would match the same versions in all + cases, only for the set of versions provided. This is useful when + generating ranges by joining together multiple versions with `||` + programmatically, to provide the user with something a bit more + ergonomic. If the provided range is shorter in string-length than the + generated range, then that is returned. +* `subset(subRange, superRange)`: Return `true` if the `subRange` range is + entirely contained by the `superRange` range. + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version, options)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). + +If the `options.rtl` flag is set, then `coerce` will return the right-most +coercible tuple that does not share an ending index with a longer coercible +tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not +`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of +any other overlapping SemVer tuple. + +If the `options.includePrerelease` flag is set, then the `coerce` result will contain +prerelease and build parts of a version. For example, `1.2.3.4-rc.1+rev.2` +will preserve prerelease `rc.1` and build `rev.2` in the result. + +### Clean + +* `clean(version)`: Clean a string to be a valid semver if possible + +This will return a cleaned and trimmed semver version. If the provided +version is not valid a null will be returned. This does not work for +ranges. + +ex. +* `s.clean(' = v 2.1.5foo')`: `null` +* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean(' = v 2.1.5-foo')`: `null` +* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean('=v2.1.5')`: `'2.1.5'` +* `s.clean(' =v2.1.5')`: `'2.1.5'` +* `s.clean(' 2.1.5 ')`: `'2.1.5'` +* `s.clean('~1.0.0')`: `null` + +## Constants + +As a convenience, helper constants are exported to provide information about what `node-semver` supports: + +### `RELEASE_TYPES` + +- major +- premajor +- minor +- preminor +- patch +- prepatch +- prerelease + +``` +const semver = require('semver'); + +if (semver.RELEASE_TYPES.includes(arbitraryUserInput)) { + console.log('This is a valid release type!'); +} else { + console.warn('This is NOT a valid release type!'); +} +``` + +### `SEMVER_SPEC_VERSION` + +2.0.0 + +``` +const semver = require('semver'); + +console.log('We are currently using the semver specification version:', semver.SEMVER_SPEC_VERSION); +``` + +## Exported Modules + + + +You may pull in just the part of this semver utility that you need if you +are sensitive to packing and tree-shaking concerns. The main +`require('semver')` export uses getter functions to lazily load the parts +of the API that are used. + +The following modules are available: + +* `require('semver')` +* `require('semver/classes')` +* `require('semver/classes/comparator')` +* `require('semver/classes/range')` +* `require('semver/classes/semver')` +* `require('semver/functions/clean')` +* `require('semver/functions/cmp')` +* `require('semver/functions/coerce')` +* `require('semver/functions/compare')` +* `require('semver/functions/compare-build')` +* `require('semver/functions/compare-loose')` +* `require('semver/functions/diff')` +* `require('semver/functions/eq')` +* `require('semver/functions/gt')` +* `require('semver/functions/gte')` +* `require('semver/functions/inc')` +* `require('semver/functions/lt')` +* `require('semver/functions/lte')` +* `require('semver/functions/major')` +* `require('semver/functions/minor')` +* `require('semver/functions/neq')` +* `require('semver/functions/parse')` +* `require('semver/functions/patch')` +* `require('semver/functions/prerelease')` +* `require('semver/functions/rcompare')` +* `require('semver/functions/rsort')` +* `require('semver/functions/satisfies')` +* `require('semver/functions/sort')` +* `require('semver/functions/valid')` +* `require('semver/ranges/gtr')` +* `require('semver/ranges/intersects')` +* `require('semver/ranges/ltr')` +* `require('semver/ranges/max-satisfying')` +* `require('semver/ranges/min-satisfying')` +* `require('semver/ranges/min-version')` +* `require('semver/ranges/outside')` +* `require('semver/ranges/simplify')` +* `require('semver/ranges/subset')` +* `require('semver/ranges/to-comparators')` +* `require('semver/ranges/valid')` + diff --git a/node_modules/semver/bin/semver.js b/node_modules/semver/bin/semver.js new file mode 100755 index 0000000..f62b566 --- /dev/null +++ b/node_modules/semver/bin/semver.js @@ -0,0 +1,188 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +const argv = process.argv.slice(2) + +let versions = [] + +const range = [] + +let inc = null + +const version = require('../package.json').version + +let loose = false + +let includePrerelease = false + +let coerce = false + +let rtl = false + +let identifier + +let identifierBase + +const semver = require('../') +const parseOptions = require('../internal/parse-options') + +let reverse = false + +let options = {} + +const main = () => { + if (!argv.length) { + return help() + } + while (argv.length) { + let a = argv.shift() + const indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + const value = a.slice(indexOfEqualSign + 1) + a = a.slice(0, indexOfEqualSign) + argv.unshift(value) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-n': + identifierBase = argv.shift() + if (identifierBase === 'false') { + identifierBase = false + } + break + case '-c': case '--coerce': + coerce = true + break + case '--rtl': + rtl = true + break + case '--ltr': + rtl = false + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + options = parseOptions({ loose, includePrerelease, rtl }) + + versions = versions.map((v) => { + return coerce ? (semver.coerce(v, options) || { version: v }).version : v + }).filter((v) => { + return semver.valid(v) + }) + if (!versions.length) { + return fail() + } + if (inc && (versions.length !== 1 || range.length)) { + return failInc() + } + + for (let i = 0, l = range.length; i < l; i++) { + versions = versions.filter((v) => { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) { + return fail() + } + } + versions + .sort((a, b) => semver[reverse ? 'rcompare' : 'compare'](a, b, options)) + .map(v => semver.clean(v, options)) + .map(v => inc ? semver.inc(v, inc, options, identifier, identifierBase) : v) + .forEach(v => console.log(v)) +} + +const failInc = () => { + console.error('--inc can only be used on a single version with no range') + fail() +} + +const fail = () => process.exit(1) + +const help = () => console.log( +`SemVer ${version} + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +-n + Base number to be used for the prerelease identifier. + Can be either 0 or 1, or false to omit the number altogether. + Defaults to 0. + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them.`) + +main() diff --git a/node_modules/semver/classes/comparator.js b/node_modules/semver/classes/comparator.js new file mode 100644 index 0000000..3d39c0e --- /dev/null +++ b/node_modules/semver/classes/comparator.js @@ -0,0 +1,141 @@ +const ANY = Symbol('SemVer ANY') +// hoisted class for cyclic dependency +class Comparator { + static get ANY () { + return ANY + } + + constructor (comp, options) { + options = parseOptions(options) + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + comp = comp.trim().split(/\s+/).join(' ') + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const m = comp.match(r) + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } + + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } + } + + toString () { + return this.value + } + + test (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY || version === ANY) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range(this.value, options).test(comp.semver) + } + + options = parseOptions(options) + + // Special cases where nothing can possibly be lower + if (options.includePrerelease && + (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { + return false + } + if (!options.includePrerelease && + (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { + return false + } + + // Same direction increasing (> or >=) + if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { + return true + } + // Same direction decreasing (< or <=) + if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { + return true + } + // same SemVer and both sides are inclusive (<= or >=) + if ( + (this.semver.version === comp.semver.version) && + this.operator.includes('=') && comp.operator.includes('=')) { + return true + } + // opposite directions less than + if (cmp(this.semver, '<', comp.semver, options) && + this.operator.startsWith('>') && comp.operator.startsWith('<')) { + return true + } + // opposite directions greater than + if (cmp(this.semver, '>', comp.semver, options) && + this.operator.startsWith('<') && comp.operator.startsWith('>')) { + return true + } + return false + } +} + +module.exports = Comparator + +const parseOptions = require('../internal/parse-options') +const { safeRe: re, t } = require('../internal/re') +const cmp = require('../functions/cmp') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const Range = require('./range') diff --git a/node_modules/semver/classes/index.js b/node_modules/semver/classes/index.js new file mode 100644 index 0000000..5e3f5c9 --- /dev/null +++ b/node_modules/semver/classes/index.js @@ -0,0 +1,5 @@ +module.exports = { + SemVer: require('./semver.js'), + Range: require('./range.js'), + Comparator: require('./comparator.js'), +} diff --git a/node_modules/semver/classes/range.js b/node_modules/semver/classes/range.js new file mode 100644 index 0000000..ceee231 --- /dev/null +++ b/node_modules/semver/classes/range.js @@ -0,0 +1,554 @@ +const SPACE_CHARACTERS = /\s+/g + +// hoisted class for cyclic dependency +class Range { + constructor (range, options) { + options = parseOptions(options) + + if (range instanceof Range) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + // just put it in the set and return + this.raw = range.value + this.set = [[range]] + this.formatted = undefined + return this + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First reduce all whitespace as much as possible so we do not have to rely + // on potentially slow regexes like \s*. This is then stored and used for + // future error messages as well. + this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') + + // First, split on || + this.set = this.raw + .split('||') + // map the range to a 2d array of comparators + .map(r => this.parseRange(r.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length) + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${this.raw}`) + } + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0] + this.set = this.set.filter(c => !isNullSet(c[0])) + if (this.set.length === 0) { + this.set = [first] + } else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c] + break + } + } + } + } + + this.formatted = undefined + } + + get range () { + if (this.formatted === undefined) { + this.formatted = '' + for (let i = 0; i < this.set.length; i++) { + if (i > 0) { + this.formatted += '||' + } + const comps = this.set[i] + for (let k = 0; k < comps.length; k++) { + if (k > 0) { + this.formatted += ' ' + } + this.formatted += comps[k].toString().trim() + } + } + } + return this.formatted + } + + format () { + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = + (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | + (this.options.loose && FLAG_LOOSE) + const memoKey = memoOpts + ':' + range + const cached = cache.get(memoKey) + if (cached) { + return cached + } + + const loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) + debug('hyphen replace', range) + + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + debug('tilde trim', range) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + debug('caret trim', range) + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + let rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + + if (loose) { + // in loose mode, throw out any that are not valid comparators + rangeList = rangeList.filter(comp => { + debug('loose invalid filter', comp, this.options) + return !!comp.match(re[t.COMPARATORLOOSE]) + }) + } + debug('range list', rangeList) + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + const rangeMap = new Map() + const comparators = rangeList.map(comp => new Comparator(comp, this.options)) + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp] + } + rangeMap.set(comp.value, comp) + } + if (rangeMap.size > 1 && rangeMap.has('')) { + rangeMap.delete('') + } + + const result = [...rangeMap.values()] + cache.set(memoKey, result) + return result + } + + intersects (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } +} + +module.exports = Range + +const LRU = require('../internal/lrucache') +const cache = new LRU() + +const parseOptions = require('../internal/parse-options') +const Comparator = require('./comparator') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const { + safeRe: re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace, +} = require('../internal/re') +const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants') + +const isNullSet = c => c.value === '<0.0.0-0' +const isAny = c => c.value === '' + +// take a set of comparators and determine whether there +// exists a version which can satisfy it +const isSatisfiable = (comparators, options) => { + let result = true + const remainingComparators = comparators.slice() + let testComparator = remainingComparators.pop() + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }) + + testComparator = remainingComparators.pop() + } + + return result +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +const parseComparator = (comp, options) => { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +const isX = id => !id || id.toLowerCase() === 'x' || id === '*' + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 +// ~0.0.1 --> >=0.0.1 <0.1.0-0 +const replaceTildes = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceTilde(c, options)) + .join(' ') +} + +const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0` + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` + } else if (pr) { + debug('replaceTilde pr', pr) + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0` + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 +// ^1.2.3 --> >=1.2.3 <2.0.0-0 +// ^1.2.0 --> >=1.2.0 <2.0.0-0 +// ^0.0.1 --> >=0.0.1 <0.0.2-0 +// ^0.1.0 --> >=0.1.0 <0.2.0-0 +const replaceCarets = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceCaret(c, options)) + .join(' ') +} + +const replaceCaret = (comp, options) => { + debug('caret', comp, options) + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + const z = options.includePrerelease ? '-0' : '' + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0` + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0` + } + } + + debug('caret return', ret) + return ret + }) +} + +const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options) + return comp + .split(/\s+/) + .map((c) => replaceXRange(c, options)) + .join(' ') +} + +const replaceXRange = (comp, options) => { + comp = comp.trim() + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + const xM = isX(M) + const xm = xM || isX(m) + const xp = xm || isX(p) + const anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + if (gtlt === '<') { + pr = '-0' + } + + ret = `${gtlt + M}.${m}.${p}${pr}` + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0` + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +const replaceStars = (comp, options) => { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp + .trim() + .replace(re[t.STAR], '') +} + +const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options) + return comp + .trim() + .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') +} + +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 +// TODO build? +const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr) => { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}` + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` + } else if (fpr) { + from = `>=${from}` + } else { + from = `>=${from}${incPr ? '-0' : ''}` + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0` + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0` + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}` + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0` + } else { + to = `<=${to}` + } + + return `${from} ${to}`.trim() +} + +const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === Comparator.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} diff --git a/node_modules/semver/classes/semver.js b/node_modules/semver/classes/semver.js new file mode 100644 index 0000000..13e66ce --- /dev/null +++ b/node_modules/semver/classes/semver.js @@ -0,0 +1,302 @@ +const debug = require('../internal/debug') +const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants') +const { safeRe: re, t } = require('../internal/re') + +const parseOptions = require('../internal/parse-options') +const { compareIdentifiers } = require('../internal/identifiers') +class SemVer { + constructor (version, options) { + options = parseOptions(options) + + if (version instanceof SemVer) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease + + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}` + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}` + } + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer(other, this.options) + } + + if (other.version === this.version) { + return 0 + } + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0 + do { + const a = this.prerelease[i] + const b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + let i = 0 + do { + const a = this.build[i] + const b = other.build[i] + debug('build compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier, identifierBase) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier, identifierBase) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier, identifierBase) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier, identifierBase) + this.inc('pre', identifier, identifierBase) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier, identifierBase) + } + this.inc('pre', identifier, identifierBase) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': { + const base = Number(identifierBase) ? 1 : 0 + + if (!identifier && identifierBase === false) { + throw new Error('invalid increment argument: identifier is empty') + } + + if (this.prerelease.length === 0) { + this.prerelease = [base] + } else { + let i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + if (identifier === this.prerelease.join('.') && identifierBase === false) { + throw new Error('invalid increment argument: identifier already exists') + } + this.prerelease.push(base) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + let prerelease = [identifier, base] + if (identifierBase === false) { + prerelease = [identifier] + } + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = prerelease + } + } else { + this.prerelease = prerelease + } + } + break + } + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.raw = this.format() + if (this.build.length) { + this.raw += `+${this.build.join('.')}` + } + return this + } +} + +module.exports = SemVer diff --git a/node_modules/semver/functions/clean.js b/node_modules/semver/functions/clean.js new file mode 100644 index 0000000..811fe6b --- /dev/null +++ b/node_modules/semver/functions/clean.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const clean = (version, options) => { + const s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} +module.exports = clean diff --git a/node_modules/semver/functions/cmp.js b/node_modules/semver/functions/cmp.js new file mode 100644 index 0000000..4011909 --- /dev/null +++ b/node_modules/semver/functions/cmp.js @@ -0,0 +1,52 @@ +const eq = require('./eq') +const neq = require('./neq') +const gt = require('./gt') +const gte = require('./gte') +const lt = require('./lt') +const lte = require('./lte') + +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a === b + + case '!==': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } +} +module.exports = cmp diff --git a/node_modules/semver/functions/coerce.js b/node_modules/semver/functions/coerce.js new file mode 100644 index 0000000..b378dce --- /dev/null +++ b/node_modules/semver/functions/coerce.js @@ -0,0 +1,60 @@ +const SemVer = require('../classes/semver') +const parse = require('./parse') +const { safeRe: re, t } = require('../internal/re') + +const coerce = (version, options) => { + if (version instanceof SemVer) { + return version + } + + if (typeof version === 'number') { + version = String(version) + } + + if (typeof version !== 'string') { + return null + } + + options = options || {} + + let match = null + if (!options.rtl) { + match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] + let next + while ((next = coerceRtlRegex.exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length + } + // leave it in a clean state + coerceRtlRegex.lastIndex = -1 + } + + if (match === null) { + return null + } + + const major = match[2] + const minor = match[3] || '0' + const patch = match[4] || '0' + const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' + const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' + + return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) +} +module.exports = coerce diff --git a/node_modules/semver/functions/compare-build.js b/node_modules/semver/functions/compare-build.js new file mode 100644 index 0000000..9eb881b --- /dev/null +++ b/node_modules/semver/functions/compare-build.js @@ -0,0 +1,7 @@ +const SemVer = require('../classes/semver') +const compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose) + const versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} +module.exports = compareBuild diff --git a/node_modules/semver/functions/compare-loose.js b/node_modules/semver/functions/compare-loose.js new file mode 100644 index 0000000..4881fbe --- /dev/null +++ b/node_modules/semver/functions/compare-loose.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const compareLoose = (a, b) => compare(a, b, true) +module.exports = compareLoose diff --git a/node_modules/semver/functions/compare.js b/node_modules/semver/functions/compare.js new file mode 100644 index 0000000..748b7af --- /dev/null +++ b/node_modules/semver/functions/compare.js @@ -0,0 +1,5 @@ +const SemVer = require('../classes/semver') +const compare = (a, b, loose) => + new SemVer(a, loose).compare(new SemVer(b, loose)) + +module.exports = compare diff --git a/node_modules/semver/functions/diff.js b/node_modules/semver/functions/diff.js new file mode 100644 index 0000000..fc224e3 --- /dev/null +++ b/node_modules/semver/functions/diff.js @@ -0,0 +1,65 @@ +const parse = require('./parse.js') + +const diff = (version1, version2) => { + const v1 = parse(version1, null, true) + const v2 = parse(version2, null, true) + const comparison = v1.compare(v2) + + if (comparison === 0) { + return null + } + + const v1Higher = comparison > 0 + const highVersion = v1Higher ? v1 : v2 + const lowVersion = v1Higher ? v2 : v1 + const highHasPre = !!highVersion.prerelease.length + const lowHasPre = !!lowVersion.prerelease.length + + if (lowHasPre && !highHasPre) { + // Going from prerelease -> no prerelease requires some special casing + + // If the low version has only a major, then it will always be a major + // Some examples: + // 1.0.0-1 -> 1.0.0 + // 1.0.0-1 -> 1.1.1 + // 1.0.0-1 -> 2.0.0 + if (!lowVersion.patch && !lowVersion.minor) { + return 'major' + } + + // Otherwise it can be determined by checking the high version + + if (highVersion.patch) { + // anything higher than a patch bump would result in the wrong version + return 'patch' + } + + if (highVersion.minor) { + // anything higher than a minor bump would result in the wrong version + return 'minor' + } + + // bumping major/minor/patch all have same result + return 'major' + } + + // add the `pre` prefix if we are going to a prerelease version + const prefix = highHasPre ? 'pre' : '' + + if (v1.major !== v2.major) { + return prefix + 'major' + } + + if (v1.minor !== v2.minor) { + return prefix + 'minor' + } + + if (v1.patch !== v2.patch) { + return prefix + 'patch' + } + + // high and low are preleases + return 'prerelease' +} + +module.exports = diff diff --git a/node_modules/semver/functions/eq.js b/node_modules/semver/functions/eq.js new file mode 100644 index 0000000..271fed9 --- /dev/null +++ b/node_modules/semver/functions/eq.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const eq = (a, b, loose) => compare(a, b, loose) === 0 +module.exports = eq diff --git a/node_modules/semver/functions/gt.js b/node_modules/semver/functions/gt.js new file mode 100644 index 0000000..d9b2156 --- /dev/null +++ b/node_modules/semver/functions/gt.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const gt = (a, b, loose) => compare(a, b, loose) > 0 +module.exports = gt diff --git a/node_modules/semver/functions/gte.js b/node_modules/semver/functions/gte.js new file mode 100644 index 0000000..5aeaa63 --- /dev/null +++ b/node_modules/semver/functions/gte.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const gte = (a, b, loose) => compare(a, b, loose) >= 0 +module.exports = gte diff --git a/node_modules/semver/functions/inc.js b/node_modules/semver/functions/inc.js new file mode 100644 index 0000000..7670b1b --- /dev/null +++ b/node_modules/semver/functions/inc.js @@ -0,0 +1,19 @@ +const SemVer = require('../classes/semver') + +const inc = (version, release, options, identifier, identifierBase) => { + if (typeof (options) === 'string') { + identifierBase = identifier + identifier = options + options = undefined + } + + try { + return new SemVer( + version instanceof SemVer ? version.version : version, + options + ).inc(release, identifier, identifierBase).version + } catch (er) { + return null + } +} +module.exports = inc diff --git a/node_modules/semver/functions/lt.js b/node_modules/semver/functions/lt.js new file mode 100644 index 0000000..b440ab7 --- /dev/null +++ b/node_modules/semver/functions/lt.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const lt = (a, b, loose) => compare(a, b, loose) < 0 +module.exports = lt diff --git a/node_modules/semver/functions/lte.js b/node_modules/semver/functions/lte.js new file mode 100644 index 0000000..6dcc956 --- /dev/null +++ b/node_modules/semver/functions/lte.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const lte = (a, b, loose) => compare(a, b, loose) <= 0 +module.exports = lte diff --git a/node_modules/semver/functions/major.js b/node_modules/semver/functions/major.js new file mode 100644 index 0000000..4283165 --- /dev/null +++ b/node_modules/semver/functions/major.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const major = (a, loose) => new SemVer(a, loose).major +module.exports = major diff --git a/node_modules/semver/functions/minor.js b/node_modules/semver/functions/minor.js new file mode 100644 index 0000000..57b3455 --- /dev/null +++ b/node_modules/semver/functions/minor.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const minor = (a, loose) => new SemVer(a, loose).minor +module.exports = minor diff --git a/node_modules/semver/functions/neq.js b/node_modules/semver/functions/neq.js new file mode 100644 index 0000000..f944c01 --- /dev/null +++ b/node_modules/semver/functions/neq.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const neq = (a, b, loose) => compare(a, b, loose) !== 0 +module.exports = neq diff --git a/node_modules/semver/functions/parse.js b/node_modules/semver/functions/parse.js new file mode 100644 index 0000000..459b3b1 --- /dev/null +++ b/node_modules/semver/functions/parse.js @@ -0,0 +1,16 @@ +const SemVer = require('../classes/semver') +const parse = (version, options, throwErrors = false) => { + if (version instanceof SemVer) { + return version + } + try { + return new SemVer(version, options) + } catch (er) { + if (!throwErrors) { + return null + } + throw er + } +} + +module.exports = parse diff --git a/node_modules/semver/functions/patch.js b/node_modules/semver/functions/patch.js new file mode 100644 index 0000000..63afca2 --- /dev/null +++ b/node_modules/semver/functions/patch.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const patch = (a, loose) => new SemVer(a, loose).patch +module.exports = patch diff --git a/node_modules/semver/functions/prerelease.js b/node_modules/semver/functions/prerelease.js new file mode 100644 index 0000000..06aa132 --- /dev/null +++ b/node_modules/semver/functions/prerelease.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const prerelease = (version, options) => { + const parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} +module.exports = prerelease diff --git a/node_modules/semver/functions/rcompare.js b/node_modules/semver/functions/rcompare.js new file mode 100644 index 0000000..0ac509e --- /dev/null +++ b/node_modules/semver/functions/rcompare.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const rcompare = (a, b, loose) => compare(b, a, loose) +module.exports = rcompare diff --git a/node_modules/semver/functions/rsort.js b/node_modules/semver/functions/rsort.js new file mode 100644 index 0000000..82404c5 --- /dev/null +++ b/node_modules/semver/functions/rsort.js @@ -0,0 +1,3 @@ +const compareBuild = require('./compare-build') +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) +module.exports = rsort diff --git a/node_modules/semver/functions/satisfies.js b/node_modules/semver/functions/satisfies.js new file mode 100644 index 0000000..50af1c1 --- /dev/null +++ b/node_modules/semver/functions/satisfies.js @@ -0,0 +1,10 @@ +const Range = require('../classes/range') +const satisfies = (version, range, options) => { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} +module.exports = satisfies diff --git a/node_modules/semver/functions/sort.js b/node_modules/semver/functions/sort.js new file mode 100644 index 0000000..4d10917 --- /dev/null +++ b/node_modules/semver/functions/sort.js @@ -0,0 +1,3 @@ +const compareBuild = require('./compare-build') +const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) +module.exports = sort diff --git a/node_modules/semver/functions/valid.js b/node_modules/semver/functions/valid.js new file mode 100644 index 0000000..f27bae1 --- /dev/null +++ b/node_modules/semver/functions/valid.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const valid = (version, options) => { + const v = parse(version, options) + return v ? v.version : null +} +module.exports = valid diff --git a/node_modules/semver/index.js b/node_modules/semver/index.js new file mode 100644 index 0000000..86d42ac --- /dev/null +++ b/node_modules/semver/index.js @@ -0,0 +1,89 @@ +// just pre-load all the stuff that index.js lazily exports +const internalRe = require('./internal/re') +const constants = require('./internal/constants') +const SemVer = require('./classes/semver') +const identifiers = require('./internal/identifiers') +const parse = require('./functions/parse') +const valid = require('./functions/valid') +const clean = require('./functions/clean') +const inc = require('./functions/inc') +const diff = require('./functions/diff') +const major = require('./functions/major') +const minor = require('./functions/minor') +const patch = require('./functions/patch') +const prerelease = require('./functions/prerelease') +const compare = require('./functions/compare') +const rcompare = require('./functions/rcompare') +const compareLoose = require('./functions/compare-loose') +const compareBuild = require('./functions/compare-build') +const sort = require('./functions/sort') +const rsort = require('./functions/rsort') +const gt = require('./functions/gt') +const lt = require('./functions/lt') +const eq = require('./functions/eq') +const neq = require('./functions/neq') +const gte = require('./functions/gte') +const lte = require('./functions/lte') +const cmp = require('./functions/cmp') +const coerce = require('./functions/coerce') +const Comparator = require('./classes/comparator') +const Range = require('./classes/range') +const satisfies = require('./functions/satisfies') +const toComparators = require('./ranges/to-comparators') +const maxSatisfying = require('./ranges/max-satisfying') +const minSatisfying = require('./ranges/min-satisfying') +const minVersion = require('./ranges/min-version') +const validRange = require('./ranges/valid') +const outside = require('./ranges/outside') +const gtr = require('./ranges/gtr') +const ltr = require('./ranges/ltr') +const intersects = require('./ranges/intersects') +const simplifyRange = require('./ranges/simplify') +const subset = require('./ranges/subset') +module.exports = { + parse, + valid, + clean, + inc, + diff, + major, + minor, + patch, + prerelease, + compare, + rcompare, + compareLoose, + compareBuild, + sort, + rsort, + gt, + lt, + eq, + neq, + gte, + lte, + cmp, + coerce, + Comparator, + Range, + satisfies, + toComparators, + maxSatisfying, + minSatisfying, + minVersion, + validRange, + outside, + gtr, + ltr, + intersects, + simplifyRange, + subset, + SemVer, + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + RELEASE_TYPES: constants.RELEASE_TYPES, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, +} diff --git a/node_modules/semver/internal/constants.js b/node_modules/semver/internal/constants.js new file mode 100644 index 0000000..94be1c5 --- /dev/null +++ b/node_modules/semver/internal/constants.js @@ -0,0 +1,35 @@ +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +const SEMVER_SPEC_VERSION = '2.0.0' + +const MAX_LENGTH = 256 +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || +/* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +const MAX_SAFE_COMPONENT_LENGTH = 16 + +// Max safe length for a build identifier. The max length minus 6 characters for +// the shortest version with a build 0.0.0+BUILD. +const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 + +const RELEASE_TYPES = [ + 'major', + 'premajor', + 'minor', + 'preminor', + 'patch', + 'prepatch', + 'prerelease', +] + +module.exports = { + MAX_LENGTH, + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_SAFE_INTEGER, + RELEASE_TYPES, + SEMVER_SPEC_VERSION, + FLAG_INCLUDE_PRERELEASE: 0b001, + FLAG_LOOSE: 0b010, +} diff --git a/node_modules/semver/internal/debug.js b/node_modules/semver/internal/debug.js new file mode 100644 index 0000000..1c00e13 --- /dev/null +++ b/node_modules/semver/internal/debug.js @@ -0,0 +1,9 @@ +const debug = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) +) ? (...args) => console.error('SEMVER', ...args) + : () => {} + +module.exports = debug diff --git a/node_modules/semver/internal/identifiers.js b/node_modules/semver/internal/identifiers.js new file mode 100644 index 0000000..e612d0a --- /dev/null +++ b/node_modules/semver/internal/identifiers.js @@ -0,0 +1,23 @@ +const numeric = /^[0-9]+$/ +const compareIdentifiers = (a, b) => { + const anum = numeric.test(a) + const bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) + +module.exports = { + compareIdentifiers, + rcompareIdentifiers, +} diff --git a/node_modules/semver/internal/lrucache.js b/node_modules/semver/internal/lrucache.js new file mode 100644 index 0000000..6d89ec9 --- /dev/null +++ b/node_modules/semver/internal/lrucache.js @@ -0,0 +1,40 @@ +class LRUCache { + constructor () { + this.max = 1000 + this.map = new Map() + } + + get (key) { + const value = this.map.get(key) + if (value === undefined) { + return undefined + } else { + // Remove the key from the map and add it to the end + this.map.delete(key) + this.map.set(key, value) + return value + } + } + + delete (key) { + return this.map.delete(key) + } + + set (key, value) { + const deleted = this.delete(key) + + if (!deleted && value !== undefined) { + // If cache is full, delete the least recently used item + if (this.map.size >= this.max) { + const firstKey = this.map.keys().next().value + this.delete(firstKey) + } + + this.map.set(key, value) + } + + return this + } +} + +module.exports = LRUCache diff --git a/node_modules/semver/internal/parse-options.js b/node_modules/semver/internal/parse-options.js new file mode 100644 index 0000000..10d64ce --- /dev/null +++ b/node_modules/semver/internal/parse-options.js @@ -0,0 +1,15 @@ +// parse out just the options we care about +const looseOption = Object.freeze({ loose: true }) +const emptyOpts = Object.freeze({ }) +const parseOptions = options => { + if (!options) { + return emptyOpts + } + + if (typeof options !== 'object') { + return looseOption + } + + return options +} +module.exports = parseOptions diff --git a/node_modules/semver/internal/re.js b/node_modules/semver/internal/re.js new file mode 100644 index 0000000..fd8920e --- /dev/null +++ b/node_modules/semver/internal/re.js @@ -0,0 +1,217 @@ +const { + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_LENGTH, +} = require('./constants') +const debug = require('./debug') +exports = module.exports = {} + +// The actual regexps go on exports.re +const re = exports.re = [] +const safeRe = exports.safeRe = [] +const src = exports.src = [] +const t = exports.t = {} +let R = 0 + +const LETTERDASHNUMBER = '[a-zA-Z0-9-]' + +// Replace some greedy regex tokens to prevent regex dos issues. These regex are +// used internally via the safeRe object since all inputs in this library get +// normalized first to trim and collapse all extra whitespace. The original +// regexes are exported for userland consumption and lower level usage. A +// future breaking change could export the safer regex only with a note that +// all input should have extra whitespace removed. +const safeRegexReplacements = [ + ['\\s', 1], + ['\\d', MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], +] + +const makeSafeRegex = (value) => { + for (const [token, max] of safeRegexReplacements) { + value = value + .split(`${token}*`).join(`${token}{0,${max}}`) + .split(`${token}+`).join(`${token}{1,${max}}`) + } + return value +} + +const createToken = (name, value, isGlobal) => { + const safe = makeSafeRegex(value) + const index = R++ + debug(name, index, value) + t[name] = index + src[index] = value + re[index] = new RegExp(value, isGlobal ? 'g' : undefined) + safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) +} + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') +createToken('NUMERICIDENTIFIERLOOSE', '\\d+') + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) + +// ## Main Version +// Three dot-separated numeric identifiers. + +createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`) + +createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`) + +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`) + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) + +createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`) + +createToken('FULL', `^${src[t.FULLPLAIN]}$`) + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`) + +createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) + +createToken('GTLT', '((?:<|>)?=?)') + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) +createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) + +createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) +createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +createToken('COERCEPLAIN', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) +createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) +createToken('COERCEFULL', src[t.COERCEPLAIN] + + `(?:${src[t.PRERELEASE]})?` + + `(?:${src[t.BUILD]})?` + + `(?:$|[^\\d])`) +createToken('COERCERTL', src[t.COERCE], true) +createToken('COERCERTLFULL', src[t.COERCEFULL], true) + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +createToken('LONETILDE', '(?:~>?)') + +createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) +exports.tildeTrimReplace = '$1~' + +createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) +createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +createToken('LONECARET', '(?:\\^)') + +createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) +exports.caretTrimReplace = '$1^' + +createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) +createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) +createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) +exports.comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`) + +createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`) + +// Star ranges basically just allow anything at all. +createToken('STAR', '(<|>)?=?\\s*\\*') +// >=0.0.0 is like a star +createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') +createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') diff --git a/node_modules/semver/package.json b/node_modules/semver/package.json new file mode 100644 index 0000000..663d370 --- /dev/null +++ b/node_modules/semver/package.json @@ -0,0 +1,77 @@ +{ + "name": "semver", + "version": "7.6.3", + "description": "The semantic version parser used by npm.", + "main": "index.js", + "scripts": { + "test": "tap", + "snap": "tap", + "lint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"", + "postlint": "template-oss-check", + "lintfix": "npm run lint -- --fix", + "posttest": "npm run lint", + "template-oss-apply": "template-oss-apply --force" + }, + "devDependencies": { + "@npmcli/eslint-config": "^4.0.0", + "@npmcli/template-oss": "4.22.0", + "benchmark": "^2.1.4", + "tap": "^16.0.0" + }, + "license": "ISC", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/node-semver.git" + }, + "bin": { + "semver": "bin/semver.js" + }, + "files": [ + "bin/", + "lib/", + "classes/", + "functions/", + "internal/", + "ranges/", + "index.js", + "preload.js", + "range.bnf" + ], + "tap": { + "timeout": 30, + "coverage-map": "map.js", + "nyc-arg": [ + "--exclude", + "tap-snapshots/**" + ] + }, + "engines": { + "node": ">=10" + }, + "author": "GitHub Inc.", + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "version": "4.22.0", + "engines": ">=10", + "distPaths": [ + "classes/", + "functions/", + "internal/", + "ranges/", + "index.js", + "preload.js", + "range.bnf" + ], + "allowPaths": [ + "/classes/", + "/functions/", + "/internal/", + "/ranges/", + "/index.js", + "/preload.js", + "/range.bnf", + "/benchmarks" + ], + "publish": "true" + } +} diff --git a/node_modules/semver/preload.js b/node_modules/semver/preload.js new file mode 100644 index 0000000..947cd4f --- /dev/null +++ b/node_modules/semver/preload.js @@ -0,0 +1,2 @@ +// XXX remove in v8 or beyond +module.exports = require('./index.js') diff --git a/node_modules/semver/range.bnf b/node_modules/semver/range.bnf new file mode 100644 index 0000000..d4c6ae0 --- /dev/null +++ b/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/semver/ranges/gtr.js b/node_modules/semver/ranges/gtr.js new file mode 100644 index 0000000..db7e355 --- /dev/null +++ b/node_modules/semver/ranges/gtr.js @@ -0,0 +1,4 @@ +// Determine if version is greater than all the versions possible in the range. +const outside = require('./outside') +const gtr = (version, range, options) => outside(version, range, '>', options) +module.exports = gtr diff --git a/node_modules/semver/ranges/intersects.js b/node_modules/semver/ranges/intersects.js new file mode 100644 index 0000000..e0e9b7c --- /dev/null +++ b/node_modules/semver/ranges/intersects.js @@ -0,0 +1,7 @@ +const Range = require('../classes/range') +const intersects = (r1, r2, options) => { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2, options) +} +module.exports = intersects diff --git a/node_modules/semver/ranges/ltr.js b/node_modules/semver/ranges/ltr.js new file mode 100644 index 0000000..528a885 --- /dev/null +++ b/node_modules/semver/ranges/ltr.js @@ -0,0 +1,4 @@ +const outside = require('./outside') +// Determine if version is less than all the versions possible in the range +const ltr = (version, range, options) => outside(version, range, '<', options) +module.exports = ltr diff --git a/node_modules/semver/ranges/max-satisfying.js b/node_modules/semver/ranges/max-satisfying.js new file mode 100644 index 0000000..6e3d993 --- /dev/null +++ b/node_modules/semver/ranges/max-satisfying.js @@ -0,0 +1,25 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') + +const maxSatisfying = (versions, range, options) => { + let max = null + let maxSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} +module.exports = maxSatisfying diff --git a/node_modules/semver/ranges/min-satisfying.js b/node_modules/semver/ranges/min-satisfying.js new file mode 100644 index 0000000..9b60974 --- /dev/null +++ b/node_modules/semver/ranges/min-satisfying.js @@ -0,0 +1,24 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const minSatisfying = (versions, range, options) => { + let min = null + let minSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} +module.exports = minSatisfying diff --git a/node_modules/semver/ranges/min-version.js b/node_modules/semver/ranges/min-version.js new file mode 100644 index 0000000..350e1f7 --- /dev/null +++ b/node_modules/semver/ranges/min-version.js @@ -0,0 +1,61 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const gt = require('../functions/gt') + +const minVersion = (range, loose) => { + range = new Range(range, loose) + + let minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let setMin = null + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt(compver, setMin)) { + setMin = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }) + if (setMin && (!minver || gt(minver, setMin))) { + minver = setMin + } + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} +module.exports = minVersion diff --git a/node_modules/semver/ranges/outside.js b/node_modules/semver/ranges/outside.js new file mode 100644 index 0000000..ae99b10 --- /dev/null +++ b/node_modules/semver/ranges/outside.js @@ -0,0 +1,80 @@ +const SemVer = require('../classes/semver') +const Comparator = require('../classes/comparator') +const { ANY } = Comparator +const Range = require('../classes/range') +const satisfies = require('../functions/satisfies') +const gt = require('../functions/gt') +const lt = require('../functions/lt') +const lte = require('../functions/lte') +const gte = require('../functions/gte') + +const outside = (version, range, hilo, options) => { + version = new SemVer(version, options) + range = new Range(range, options) + + let gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let high = null + let low = null + + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +module.exports = outside diff --git a/node_modules/semver/ranges/simplify.js b/node_modules/semver/ranges/simplify.js new file mode 100644 index 0000000..618d5b6 --- /dev/null +++ b/node_modules/semver/ranges/simplify.js @@ -0,0 +1,47 @@ +// given a set of versions and a range, create a "simplified" range +// that includes the same versions that the original range does +// If the original range is shorter than the simplified one, return that. +const satisfies = require('../functions/satisfies.js') +const compare = require('../functions/compare.js') +module.exports = (versions, range, options) => { + const set = [] + let first = null + let prev = null + const v = versions.sort((a, b) => compare(a, b, options)) + for (const version of v) { + const included = satisfies(version, range, options) + if (included) { + prev = version + if (!first) { + first = version + } + } else { + if (prev) { + set.push([first, prev]) + } + prev = null + first = null + } + } + if (first) { + set.push([first, null]) + } + + const ranges = [] + for (const [min, max] of set) { + if (min === max) { + ranges.push(min) + } else if (!max && min === v[0]) { + ranges.push('*') + } else if (!max) { + ranges.push(`>=${min}`) + } else if (min === v[0]) { + ranges.push(`<=${max}`) + } else { + ranges.push(`${min} - ${max}`) + } + } + const simplified = ranges.join(' || ') + const original = typeof range.raw === 'string' ? range.raw : String(range) + return simplified.length < original.length ? simplified : range +} diff --git a/node_modules/semver/ranges/subset.js b/node_modules/semver/ranges/subset.js new file mode 100644 index 0000000..1e5c268 --- /dev/null +++ b/node_modules/semver/ranges/subset.js @@ -0,0 +1,247 @@ +const Range = require('../classes/range.js') +const Comparator = require('../classes/comparator.js') +const { ANY } = Comparator +const satisfies = require('../functions/satisfies.js') +const compare = require('../functions/compare.js') + +// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: +// - Every simple range `r1, r2, ...` is a null set, OR +// - Every simple range `r1, r2, ...` which is not a null set is a subset of +// some `R1, R2, ...` +// +// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: +// - If c is only the ANY comparator +// - If C is only the ANY comparator, return true +// - Else if in prerelease mode, return false +// - else replace c with `[>=0.0.0]` +// - If C is only the ANY comparator +// - if in prerelease mode, return true +// - else replace C with `[>=0.0.0]` +// - Let EQ be the set of = comparators in c +// - If EQ is more than one, return true (null set) +// - Let GT be the highest > or >= comparator in c +// - Let LT be the lowest < or <= comparator in c +// - If GT and LT, and GT.semver > LT.semver, return true (null set) +// - If any C is a = range, and GT or LT are set, return false +// - If EQ +// - If GT, and EQ does not satisfy GT, return true (null set) +// - If LT, and EQ does not satisfy LT, return true (null set) +// - If EQ satisfies every C, return true +// - Else return false +// - If GT +// - If GT.semver is lower than any > or >= comp in C, return false +// - If GT is >=, and GT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the GT.semver tuple, return false +// - If LT +// - If LT.semver is greater than any < or <= comp in C, return false +// - If LT is <=, and LT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the LT.semver tuple, return false +// - Else return true + +const subset = (sub, dom, options = {}) => { + if (sub === dom) { + return true + } + + sub = new Range(sub, options) + dom = new Range(dom, options) + let sawNonNull = false + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options) + sawNonNull = sawNonNull || isSub !== null + if (isSub) { + continue OUTER + } + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) { + return false + } + } + return true +} + +const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] +const minimumVersion = [new Comparator('>=0.0.0')] + +const simpleSubset = (sub, dom, options) => { + if (sub === dom) { + return true + } + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true + } else if (options.includePrerelease) { + sub = minimumVersionWithPreRelease + } else { + sub = minimumVersion + } + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true + } else { + dom = minimumVersion + } + } + + const eqSet = new Set() + let gt, lt + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') { + gt = higherGT(gt, c, options) + } else if (c.operator === '<' || c.operator === '<=') { + lt = lowerLT(lt, c, options) + } else { + eqSet.add(c.semver) + } + } + + if (eqSet.size > 1) { + return null + } + + let gtltComp + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options) + if (gtltComp > 0) { + return null + } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { + return null + } + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) { + return null + } + + if (lt && !satisfies(eq, String(lt), options)) { + return null + } + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) { + return false + } + } + + return true + } + + let higher, lower + let hasDomLT, hasDomGT + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options) + if (higher === c && higher !== gt) { + return false + } + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { + return false + } + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options) + if (lower === c && lower !== lt) { + return false + } + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { + return false + } + } + if (!c.operator && (lt || gt) && gtltComp !== 0) { + return false + } + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false + } + + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false + } + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) { + return false + } + + return true +} + +// >=1.2.3 is lower than >1.2.3 +const higherGT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a +} + +// <=1.2.3 is higher than <1.2.3 +const lowerLT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a +} + +module.exports = subset diff --git a/node_modules/semver/ranges/to-comparators.js b/node_modules/semver/ranges/to-comparators.js new file mode 100644 index 0000000..6c8bc7e --- /dev/null +++ b/node_modules/semver/ranges/to-comparators.js @@ -0,0 +1,8 @@ +const Range = require('../classes/range') + +// Mostly just for testing and legacy API reasons +const toComparators = (range, options) => + new Range(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) + +module.exports = toComparators diff --git a/node_modules/semver/ranges/valid.js b/node_modules/semver/ranges/valid.js new file mode 100644 index 0000000..365f356 --- /dev/null +++ b/node_modules/semver/ranges/valid.js @@ -0,0 +1,11 @@ +const Range = require('../classes/range') +const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} +module.exports = validRange diff --git a/node_modules/send/HISTORY.md b/node_modules/send/HISTORY.md new file mode 100644 index 0000000..07ee6b4 --- /dev/null +++ b/node_modules/send/HISTORY.md @@ -0,0 +1,531 @@ +0.19.1 / 2024-10-09 +=================== + +* deps: encodeurl@~2.0.0 + +0.19.0 / 2024-09-10 +=================== + +* Remove link renderization in html while redirecting + +0.18.0 / 2022-03-23 +=================== + + * Fix emitted 416 error missing headers property + * Limit the headers removed for 304 response + * deps: depd@2.0.0 + - Replace internal `eval` usage with `Function` constructor + - Use instance methods on `process` to check for listeners + * deps: destroy@1.2.0 + * deps: http-errors@2.0.0 + - deps: depd@2.0.0 + - deps: statuses@2.0.1 + * deps: on-finished@2.4.1 + * deps: statuses@2.0.1 + +0.17.2 / 2021-12-11 +=================== + + * pref: ignore empty http tokens + * deps: http-errors@1.8.1 + - deps: inherits@2.0.4 + - deps: toidentifier@1.0.1 + - deps: setprototypeof@1.2.0 + * deps: ms@2.1.3 + +0.17.1 / 2019-05-10 +=================== + + * Set stricter CSP header in redirect & error responses + * deps: range-parser@~1.2.1 + +0.17.0 / 2019-05-03 +=================== + + * deps: http-errors@~1.7.2 + - Set constructor name when possible + - Use `toidentifier` module to make class names + - deps: depd@~1.1.2 + - deps: setprototypeof@1.1.1 + - deps: statuses@'>= 1.5.0 < 2' + * deps: mime@1.6.0 + - Add extensions for JPEG-2000 images + - Add new `font/*` types from IANA + - Add WASM mapping + - Update `.bdoc` to `application/bdoc` + - Update `.bmp` to `image/bmp` + - Update `.m4a` to `audio/mp4` + - Update `.rtf` to `application/rtf` + - Update `.wav` to `audio/wav` + - Update `.xml` to `application/xml` + - Update generic extensions to `application/octet-stream`: + `.deb`, `.dll`, `.dmg`, `.exe`, `.iso`, `.msi` + - Use mime-score module to resolve extension conflicts + * deps: ms@2.1.1 + - Add `week`/`w` support + - Fix negative number handling + * deps: statuses@~1.5.0 + * perf: remove redundant `path.normalize` call + +0.16.2 / 2018-02-07 +=================== + + * Fix incorrect end tag in default error & redirects + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: statuses@~1.4.0 + +0.16.1 / 2017-09-29 +=================== + + * Fix regression in edge-case behavior for empty `path` + +0.16.0 / 2017-09-27 +=================== + + * Add `immutable` option + * Fix missing `` in default error & redirects + * Use instance methods on steam to check for listeners + * deps: mime@1.4.1 + - Add 70 new types for file extensions + - Set charset as "UTF-8" for .js and .json + * perf: improve path validation speed + +0.15.6 / 2017-09-22 +=================== + + * deps: debug@2.6.9 + * perf: improve `If-Match` token parsing + +0.15.5 / 2017-09-20 +=================== + + * deps: etag@~1.8.1 + - perf: replace regular expression with substring + * deps: fresh@0.5.2 + - Fix handling of modified headers with invalid dates + - perf: improve ETag match loop + - perf: improve `If-None-Match` token parsing + +0.15.4 / 2017-08-05 +=================== + + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: http-errors@~1.6.2 + - deps: depd@1.1.1 + +0.15.3 / 2017-05-16 +=================== + + * deps: debug@2.6.7 + - deps: ms@2.0.0 + * deps: ms@2.0.0 + +0.15.2 / 2017-04-26 +=================== + + * deps: debug@2.6.4 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@0.7.3 + * deps: ms@1.0.0 + +0.15.1 / 2017-03-04 +=================== + + * Fix issue when `Date.parse` does not return `NaN` on invalid date + * Fix strict violation in broken environments + +0.15.0 / 2017-02-25 +=================== + + * Support `If-Match` and `If-Unmodified-Since` headers + * Add `res` and `path` arguments to `directory` event + * Remove usage of `res._headers` private field + - Improves compatibility with Node.js 8 nightly + * Send complete HTML document in redirect & error responses + * Set default CSP header in redirect & error responses + * Use `res.getHeaderNames()` when available + * Use `res.headersSent` when available + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: etag@~1.8.0 + * deps: fresh@0.5.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - perf: delay reading header values until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove duplicate conditional + - perf: remove unnecessary boolean coercions + - perf: skip checking modified time if ETag check failed + - perf: skip parsing `If-None-Match` when no `ETag` header + - perf: use `Date.parse` instead of `new Date` + * deps: http-errors@~1.6.1 + - Make `message` property enumerable for `HttpError`s + - deps: setprototypeof@1.0.3 + +0.14.2 / 2017-01-23 +=================== + + * deps: http-errors@~1.5.1 + - deps: inherits@2.0.3 + - deps: setprototypeof@1.0.2 + - deps: statuses@'>= 1.3.1 < 2' + * deps: ms@0.7.2 + * deps: statuses@~1.3.1 + +0.14.1 / 2016-06-09 +=================== + + * Fix redirect error when `path` contains raw non-URL characters + * Fix redirect when `path` starts with multiple forward slashes + +0.14.0 / 2016-06-06 +=================== + + * Add `acceptRanges` option + * Add `cacheControl` option + * Attempt to combine multiple ranges into single range + * Correctly inherit from `Stream` class + * Fix `Content-Range` header in 416 responses when using `start`/`end` options + * Fix `Content-Range` header missing from default 416 responses + * Ignore non-byte `Range` headers + * deps: http-errors@~1.5.0 + - Add `HttpError` export, for `err instanceof createError.HttpError` + - Support new code `421 Misdirected Request` + - Use `setprototypeof` module to replace `__proto__` setting + - deps: inherits@2.0.1 + - deps: statuses@'>= 1.3.0 < 2' + - perf: enable strict mode + * deps: range-parser@~1.2.0 + - Fix incorrectly returning -1 when there is at least one valid range + - perf: remove internal function + * deps: statuses@~1.3.0 + - Add `421 Misdirected Request` + - perf: enable strict mode + * perf: remove argument reassignment + +0.13.2 / 2016-03-05 +=================== + + * Fix invalid `Content-Type` header when `send.mime.default_type` unset + +0.13.1 / 2016-01-16 +=================== + + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: destroy@~1.0.4 + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: range-parser@~1.0.3 + - perf: enable strict mode + +0.13.0 / 2015-06-16 +=================== + + * Allow Node.js HTTP server to set `Date` response header + * Fix incorrectly removing `Content-Location` on 304 response + * Improve the default redirect response headers + * Send appropriate headers on default error response + * Use `http-errors` for standard emitted errors + * Use `statuses` instead of `http` module for status messages + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Improve stat performance by removing hashing + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove unnecessary array allocations + +0.12.3 / 2015-05-13 +=================== + + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: etag@~1.6.0 + - Improve support for JXcore + - Support "fake" stats objects in environments without `fs` + * deps: ms@0.7.1 + - Prevent extraordinarily long inputs + * deps: on-finished@~2.2.1 + +0.12.2 / 2015-03-13 +=================== + + * Throw errors early for invalid `extensions` or `index` options + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +0.12.1 / 2015-02-17 +=================== + + * Fix regression sending zero-length files + +0.12.0 / 2015-02-16 +=================== + + * Always read the stat size from the file + * Fix mutating passed-in `options` + * deps: mime@1.3.4 + +0.11.1 / 2015-01-20 +=================== + + * Fix `root` path disclosure + +0.11.0 / 2015-01-05 +=================== + + * deps: debug@~2.1.1 + * deps: etag@~1.5.1 + - deps: crc@3.2.1 + * deps: ms@0.7.0 + - Add `milliseconds` + - Add `msecs` + - Add `secs` + - Add `mins` + - Add `hrs` + - Add `yrs` + * deps: on-finished@~2.2.0 + +0.10.1 / 2014-10-22 +=================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + +0.10.0 / 2014-10-15 +=================== + + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: etag@~1.5.0 + - Improve string performance + - Slightly improve speed for weak ETags over 1KB + +0.9.3 / 2014-09-24 +================== + + * deps: etag@~1.4.0 + - Support "fake" stats objects + +0.9.2 / 2014-09-15 +================== + + * deps: depd@0.4.5 + * deps: etag@~1.3.1 + * deps: range-parser@~1.0.2 + +0.9.1 / 2014-09-07 +================== + + * deps: fresh@0.2.4 + +0.9.0 / 2014-09-07 +================== + + * Add `lastModified` option + * Use `etag` to generate `ETag` header + * deps: debug@~2.0.0 + +0.8.5 / 2014-09-04 +================== + + * Fix malicious path detection for empty string path + +0.8.4 / 2014-09-04 +================== + + * Fix a path traversal issue when using `root` + +0.8.3 / 2014-08-16 +================== + + * deps: destroy@1.0.3 + - renamed from dethroy + * deps: on-finished@2.1.0 + +0.8.2 / 2014-08-14 +================== + + * Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + * deps: dethroy@1.0.2 + +0.8.1 / 2014-08-05 +================== + + * Fix `extensions` behavior when file already has extension + +0.8.0 / 2014-08-05 +================== + + * Add `extensions` option + +0.7.4 / 2014-08-04 +================== + + * Fix serving index files without root dir + +0.7.3 / 2014-07-29 +================== + + * Fix incorrect 403 on Windows and Node.js 0.11 + +0.7.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +0.7.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +0.7.0 / 2014-07-20 +================== + + * Deprecate `hidden` option; use `dotfiles` option + * Add `dotfiles` option + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + +0.6.0 / 2014-07-11 +================== + + * Deprecate `from` option; use `root` option + * Deprecate `send.etag()` -- use `etag` in `options` + * Deprecate `send.hidden()` -- use `hidden` in `options` + * Deprecate `send.index()` -- use `index` in `options` + * Deprecate `send.maxage()` -- use `maxAge` in `options` + * Deprecate `send.root()` -- use `root` in `options` + * Cap `maxAge` value to 1 year + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + +0.5.0 / 2014-06-28 +================== + + * Accept string for `maxAge` (converted by `ms`) + * Add `headers` event + * Include link in default redirect response + * Use `EventEmitter.listenerCount` to count listeners + +0.4.3 / 2014-06-11 +================== + + * Do not throw un-catchable error on file open race condition + * Use `escape-html` for HTML escaping + * deps: debug@1.0.2 + - fix some debugging output colors on node.js 0.8 + * deps: finished@1.2.2 + * deps: fresh@0.2.2 + +0.4.2 / 2014-06-09 +================== + + * fix "event emitter leak" warnings + * deps: debug@1.0.1 + * deps: finished@1.2.1 + +0.4.1 / 2014-06-02 +================== + + * Send `max-age` in `Cache-Control` in correct format + +0.4.0 / 2014-05-27 +================== + + * Calculate ETag with md5 for reduced collisions + * Fix wrong behavior when index file matches directory + * Ignore stream errors after request ends + - Goodbye `EBADF, read` + * Skip directories in index file search + * deps: debug@0.8.1 + +0.3.0 / 2014-04-24 +================== + + * Fix sending files with dots without root set + * Coerce option types + * Accept API options in options object + * Set etags to "weak" + * Include file path in etag + * Make "Can't set headers after they are sent." catchable + * Send full entity-body for multi range requests + * Default directory access to 403 when index disabled + * Support multiple index paths + * Support "If-Range" header + * Control whether to generate etags + * deps: mime@1.2.11 + +0.2.0 / 2014-01-29 +================== + + * update range-parser and fresh + +0.1.4 / 2013-08-11 +================== + + * update fresh + +0.1.3 / 2013-07-08 +================== + + * Revert "Fix fd leak" + +0.1.2 / 2013-07-03 +================== + + * Fix fd leak + +0.1.0 / 2012-08-25 +================== + + * add options parameter to send() that is passed to fs.createReadStream() [kanongil] + +0.0.4 / 2012-08-16 +================== + + * allow custom "Accept-Ranges" definition + +0.0.3 / 2012-07-16 +================== + + * fix normalization of the root directory. Closes #3 + +0.0.2 / 2012-07-09 +================== + + * add passing of req explicitly for now (YUCK) + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/send/LICENSE b/node_modules/send/LICENSE new file mode 100644 index 0000000..b6ea1c1 --- /dev/null +++ b/node_modules/send/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk +Copyright (c) 2014-2022 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/send/README.md b/node_modules/send/README.md new file mode 100644 index 0000000..fadf838 --- /dev/null +++ b/node_modules/send/README.md @@ -0,0 +1,327 @@ +# send + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Linux Build][github-actions-ci-image]][github-actions-ci-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Send is a library for streaming files from the file system as a http response +supporting partial responses (Ranges), conditional-GET negotiation (If-Match, +If-Unmodified-Since, If-None-Match, If-Modified-Since), high test coverage, +and granular events which may be leveraged to take appropriate actions in your +application or framework. + +Looking to serve up entire folders mapped to URLs? Try [serve-static](https://www.npmjs.org/package/serve-static). + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install send +``` + +## API + +```js +var send = require('send') +``` + +### send(req, path, [options]) + +Create a new `SendStream` for the given path to send to a `res`. The `req` is +the Node.js HTTP request and the `path` is a urlencoded path to send (urlencoded, +not the actual file-system path). + +#### Options + +##### acceptRanges + +Enable or disable accepting ranged requests, defaults to true. +Disabling this will not send `Accept-Ranges` and ignore the contents +of the `Range` request header. + +##### cacheControl + +Enable or disable setting `Cache-Control` response header, defaults to +true. Disabling this will ignore the `immutable` and `maxAge` options. + +##### dotfiles + +Set how "dotfiles" are treated when encountered. A dotfile is a file +or directory that begins with a dot ("."). Note this check is done on +the path itself without checking if the path actually exists on the +disk. If `root` is specified, only the dotfiles above the root are +checked (i.e. the root itself can be within a dotfile when when set +to "deny"). + + - `'allow'` No special treatment for dotfiles. + - `'deny'` Send a 403 for any request for a dotfile. + - `'ignore'` Pretend like the dotfile does not exist and 404. + +The default value is _similar_ to `'ignore'`, with the exception that +this default will not ignore the files within a directory that begins +with a dot, for backward-compatibility. + +##### end + +Byte offset at which the stream ends, defaults to the length of the file +minus 1. The end is inclusive in the stream, meaning `end: 3` will include +the 4th byte in the stream. + +##### etag + +Enable or disable etag generation, defaults to true. + +##### extensions + +If a given file doesn't exist, try appending one of the given extensions, +in the given order. By default, this is disabled (set to `false`). An +example value that will serve extension-less HTML files: `['html', 'htm']`. +This is skipped if the requested file already has an extension. + +##### immutable + +Enable or disable the `immutable` directive in the `Cache-Control` response +header, defaults to `false`. If set to `true`, the `maxAge` option should +also be specified to enable caching. The `immutable` directive will prevent +supported clients from making conditional requests during the life of the +`maxAge` option to check if the file has changed. + +##### index + +By default send supports "index.html" files, to disable this +set `false` or to supply a new index pass a string or an array +in preferred order. + +##### lastModified + +Enable or disable `Last-Modified` header, defaults to true. Uses the file +system's last modified value. + +##### maxAge + +Provide a max-age in milliseconds for http caching, defaults to 0. +This can also be a string accepted by the +[ms](https://www.npmjs.org/package/ms#readme) module. + +##### root + +Serve files relative to `path`. + +##### start + +Byte offset at which the stream starts, defaults to 0. The start is inclusive, +meaning `start: 2` will include the 3rd byte in the stream. + +#### Events + +The `SendStream` is an event emitter and will emit the following events: + + - `error` an error occurred `(err)` + - `directory` a directory was requested `(res, path)` + - `file` a file was requested `(path, stat)` + - `headers` the headers are about to be set on a file `(res, path, stat)` + - `stream` file streaming has started `(stream)` + - `end` streaming has completed + +#### .pipe + +The `pipe` method is used to pipe the response into the Node.js HTTP response +object, typically `send(req, path, options).pipe(res)`. + +### .mime + +The `mime` export is the global instance of of the +[`mime` npm module](https://www.npmjs.com/package/mime). + +This is used to configure the MIME types that are associated with file extensions +as well as other options for how to resolve the MIME type of a file (like the +default type to use for an unknown file extension). + +## Error-handling + +By default when no `error` listeners are present an automatic response will be +made, otherwise you have full control over the response, aka you may show a 5xx +page etc. + +## Caching + +It does _not_ perform internal caching, you should use a reverse proxy cache +such as Varnish for this, or those fancy things called CDNs. If your +application is small enough that it would benefit from single-node memory +caching, it's small enough that it does not need caching at all ;). + +## Debugging + +To enable `debug()` instrumentation output export __DEBUG__: + +``` +$ DEBUG=send node app +``` + +## Running tests + +``` +$ npm install +$ npm test +``` + +## Examples + +### Serve a specific file + +This simple example will send a specific file to all requests. + +```js +var http = require('http') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + send(req, '/path/to/index.html') + .pipe(res) +}) + +server.listen(3000) +``` + +### Serve all files from a directory + +This simple example will just serve up all the files in a +given directory as the top-level. For example, a request +`GET /foo.txt` will send back `/www/public/foo.txt`. + +```js +var http = require('http') +var parseUrl = require('parseurl') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + send(req, parseUrl(req).pathname, { root: '/www/public' }) + .pipe(res) +}) + +server.listen(3000) +``` + +### Custom file types + +```js +var http = require('http') +var parseUrl = require('parseurl') +var send = require('send') + +// Default unknown types to text/plain +send.mime.default_type = 'text/plain' + +// Add a custom type +send.mime.define({ + 'application/x-my-type': ['x-mt', 'x-mtt'] +}) + +var server = http.createServer(function onRequest (req, res) { + send(req, parseUrl(req).pathname, { root: '/www/public' }) + .pipe(res) +}) + +server.listen(3000) +``` + +### Custom directory index view + +This is a example of serving up a structure of directories with a +custom function to render a listing of a directory. + +```js +var http = require('http') +var fs = require('fs') +var parseUrl = require('parseurl') +var send = require('send') + +// Transfer arbitrary files from within /www/example.com/public/* +// with a custom handler for directory listing +var server = http.createServer(function onRequest (req, res) { + send(req, parseUrl(req).pathname, { index: false, root: '/www/public' }) + .once('directory', directory) + .pipe(res) +}) + +server.listen(3000) + +// Custom directory handler +function directory (res, path) { + var stream = this + + // redirect to trailing slash for consistent url + if (!stream.hasTrailingSlash()) { + return stream.redirect(path) + } + + // get directory list + fs.readdir(path, function onReaddir (err, list) { + if (err) return stream.error(err) + + // render an index for the directory + res.setHeader('Content-Type', 'text/plain; charset=UTF-8') + res.end(list.join('\n') + '\n') + }) +} +``` + +### Serving from a root directory with custom error-handling + +```js +var http = require('http') +var parseUrl = require('parseurl') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + // your custom error-handling logic: + function error (err) { + res.statusCode = err.status || 500 + res.end(err.message) + } + + // your custom headers + function headers (res, path, stat) { + // serve all files for download + res.setHeader('Content-Disposition', 'attachment') + } + + // your custom directory handling logic: + function redirect () { + res.statusCode = 301 + res.setHeader('Location', req.url + '/') + res.end('Redirecting to ' + req.url + '/') + } + + // transfer arbitrary files from within + // /www/example.com/public/* + send(req, parseUrl(req).pathname, { root: '/www/public' }) + .on('error', error) + .on('directory', redirect) + .on('headers', headers) + .pipe(res) +}) + +server.listen(3000) +``` + +## License + +[MIT](LICENSE) + +[appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/send/master?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/send +[coveralls-image]: https://badgen.net/coveralls/c/github/pillarjs/send/master +[coveralls-url]: https://coveralls.io/r/pillarjs/send?branch=master +[github-actions-ci-image]: https://badgen.net/github/checks/pillarjs/send/master?label=linux +[github-actions-ci-url]: https://github.com/pillarjs/send/actions/workflows/ci.yml +[node-image]: https://badgen.net/npm/node/send +[node-url]: https://nodejs.org/en/download/ +[npm-downloads-image]: https://badgen.net/npm/dm/send +[npm-url]: https://npmjs.org/package/send +[npm-version-image]: https://badgen.net/npm/v/send diff --git a/node_modules/send/SECURITY.md b/node_modules/send/SECURITY.md new file mode 100644 index 0000000..46b48f7 --- /dev/null +++ b/node_modules/send/SECURITY.md @@ -0,0 +1,24 @@ +# Security Policies and Procedures + +## Reporting a Bug + +The `send` team and community take all security bugs seriously. Thank you +for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing the current owner(s) of `send`. This information +can be found in the npm registry using the command `npm owner ls send`. +If unsure or unable to get the information from the above, open an issue +in the [project issue tracker](https://github.com/pillarjs/send/issues) +asking for the current contact information. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +At least one owner will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. After the initial reply to your report, the owners will +endeavor to keep you informed of the progress towards a fix and full +announcement, and may ask for additional information or guidance. diff --git a/node_modules/send/index.js b/node_modules/send/index.js new file mode 100644 index 0000000..768f8ca --- /dev/null +++ b/node_modules/send/index.js @@ -0,0 +1,1142 @@ +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var debug = require('debug')('send') +var deprecate = require('depd')('send') +var destroy = require('destroy') +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var etag = require('etag') +var fresh = require('fresh') +var fs = require('fs') +var mime = require('mime') +var ms = require('ms') +var onFinished = require('on-finished') +var parseRange = require('range-parser') +var path = require('path') +var statuses = require('statuses') +var Stream = require('stream') +var util = require('util') + +/** + * Path function references. + * @private + */ + +var extname = path.extname +var join = path.join +var normalize = path.normalize +var resolve = path.resolve +var sep = path.sep + +/** + * Regular expression for identifying a bytes Range header. + * @private + */ + +var BYTES_RANGE_REGEXP = /^ *bytes=/ + +/** + * Maximum value allowed for the max age. + * @private + */ + +var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1000 // 1 year + +/** + * Regular expression to match a path with a directory up component. + * @private + */ + +var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/ + +/** + * Module exports. + * @public + */ + +module.exports = send +module.exports.mime = mime + +/** + * Return a `SendStream` for `req` and `path`. + * + * @param {object} req + * @param {string} path + * @param {object} [options] + * @return {SendStream} + * @public + */ + +function send (req, path, options) { + return new SendStream(req, path, options) +} + +/** + * Initialize a `SendStream` with the given `path`. + * + * @param {Request} req + * @param {String} path + * @param {object} [options] + * @private + */ + +function SendStream (req, path, options) { + Stream.call(this) + + var opts = options || {} + + this.options = opts + this.path = path + this.req = req + + this._acceptRanges = opts.acceptRanges !== undefined + ? Boolean(opts.acceptRanges) + : true + + this._cacheControl = opts.cacheControl !== undefined + ? Boolean(opts.cacheControl) + : true + + this._etag = opts.etag !== undefined + ? Boolean(opts.etag) + : true + + this._dotfiles = opts.dotfiles !== undefined + ? opts.dotfiles + : 'ignore' + + if (this._dotfiles !== 'ignore' && this._dotfiles !== 'allow' && this._dotfiles !== 'deny') { + throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"') + } + + this._hidden = Boolean(opts.hidden) + + if (opts.hidden !== undefined) { + deprecate('hidden: use dotfiles: \'' + (this._hidden ? 'allow' : 'ignore') + '\' instead') + } + + // legacy support + if (opts.dotfiles === undefined) { + this._dotfiles = undefined + } + + this._extensions = opts.extensions !== undefined + ? normalizeList(opts.extensions, 'extensions option') + : [] + + this._immutable = opts.immutable !== undefined + ? Boolean(opts.immutable) + : false + + this._index = opts.index !== undefined + ? normalizeList(opts.index, 'index option') + : ['index.html'] + + this._lastModified = opts.lastModified !== undefined + ? Boolean(opts.lastModified) + : true + + this._maxage = opts.maxAge || opts.maxage + this._maxage = typeof this._maxage === 'string' + ? ms(this._maxage) + : Number(this._maxage) + this._maxage = !isNaN(this._maxage) + ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) + : 0 + + this._root = opts.root + ? resolve(opts.root) + : null + + if (!this._root && opts.from) { + this.from(opts.from) + } +} + +/** + * Inherits from `Stream`. + */ + +util.inherits(SendStream, Stream) + +/** + * Enable or disable etag generation. + * + * @param {Boolean} val + * @return {SendStream} + * @api public + */ + +SendStream.prototype.etag = deprecate.function(function etag (val) { + this._etag = Boolean(val) + debug('etag %s', this._etag) + return this +}, 'send.etag: pass etag as option') + +/** + * Enable or disable "hidden" (dot) files. + * + * @param {Boolean} path + * @return {SendStream} + * @api public + */ + +SendStream.prototype.hidden = deprecate.function(function hidden (val) { + this._hidden = Boolean(val) + this._dotfiles = undefined + debug('hidden %s', this._hidden) + return this +}, 'send.hidden: use dotfiles option') + +/** + * Set index `paths`, set to a falsy + * value to disable index support. + * + * @param {String|Boolean|Array} paths + * @return {SendStream} + * @api public + */ + +SendStream.prototype.index = deprecate.function(function index (paths) { + var index = !paths ? [] : normalizeList(paths, 'paths argument') + debug('index %o', paths) + this._index = index + return this +}, 'send.index: pass index as option') + +/** + * Set root `path`. + * + * @param {String} path + * @return {SendStream} + * @api public + */ + +SendStream.prototype.root = function root (path) { + this._root = resolve(String(path)) + debug('root %s', this._root) + return this +} + +SendStream.prototype.from = deprecate.function(SendStream.prototype.root, + 'send.from: pass root as option') + +SendStream.prototype.root = deprecate.function(SendStream.prototype.root, + 'send.root: pass root as option') + +/** + * Set max-age to `maxAge`. + * + * @param {Number} maxAge + * @return {SendStream} + * @api public + */ + +SendStream.prototype.maxage = deprecate.function(function maxage (maxAge) { + this._maxage = typeof maxAge === 'string' + ? ms(maxAge) + : Number(maxAge) + this._maxage = !isNaN(this._maxage) + ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) + : 0 + debug('max-age %d', this._maxage) + return this +}, 'send.maxage: pass maxAge as option') + +/** + * Emit error with `status`. + * + * @param {number} status + * @param {Error} [err] + * @private + */ + +SendStream.prototype.error = function error (status, err) { + // emit if listeners instead of responding + if (hasListeners(this, 'error')) { + return this.emit('error', createHttpError(status, err)) + } + + var res = this.res + var msg = statuses.message[status] || String(status) + var doc = createHtmlDocument('Error', escapeHtml(msg)) + + // clear existing headers + clearHeaders(res) + + // add error headers + if (err && err.headers) { + setHeaders(res, err.headers) + } + + // send basic response + res.statusCode = status + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.end(doc) +} + +/** + * Check if the pathname ends with "/". + * + * @return {boolean} + * @private + */ + +SendStream.prototype.hasTrailingSlash = function hasTrailingSlash () { + return this.path[this.path.length - 1] === '/' +} + +/** + * Check if this is a conditional GET request. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isConditionalGET = function isConditionalGET () { + return this.req.headers['if-match'] || + this.req.headers['if-unmodified-since'] || + this.req.headers['if-none-match'] || + this.req.headers['if-modified-since'] +} + +/** + * Check if the request preconditions failed. + * + * @return {boolean} + * @private + */ + +SendStream.prototype.isPreconditionFailure = function isPreconditionFailure () { + var req = this.req + var res = this.res + + // if-match + var match = req.headers['if-match'] + if (match) { + var etag = res.getHeader('ETag') + return !etag || (match !== '*' && parseTokenList(match).every(function (match) { + return match !== etag && match !== 'W/' + etag && 'W/' + match !== etag + })) + } + + // if-unmodified-since + var unmodifiedSince = parseHttpDate(req.headers['if-unmodified-since']) + if (!isNaN(unmodifiedSince)) { + var lastModified = parseHttpDate(res.getHeader('Last-Modified')) + return isNaN(lastModified) || lastModified > unmodifiedSince + } + + return false +} + +/** + * Strip various content header fields for a change in entity. + * + * @private + */ + +SendStream.prototype.removeContentHeaderFields = function removeContentHeaderFields () { + var res = this.res + + res.removeHeader('Content-Encoding') + res.removeHeader('Content-Language') + res.removeHeader('Content-Length') + res.removeHeader('Content-Range') + res.removeHeader('Content-Type') +} + +/** + * Respond with 304 not modified. + * + * @api private + */ + +SendStream.prototype.notModified = function notModified () { + var res = this.res + debug('not modified') + this.removeContentHeaderFields() + res.statusCode = 304 + res.end() +} + +/** + * Raise error that headers already sent. + * + * @api private + */ + +SendStream.prototype.headersAlreadySent = function headersAlreadySent () { + var err = new Error('Can\'t set headers after they are sent.') + debug('headers already sent') + this.error(500, err) +} + +/** + * Check if the request is cacheable, aka + * responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}). + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isCachable = function isCachable () { + var statusCode = this.res.statusCode + return (statusCode >= 200 && statusCode < 300) || + statusCode === 304 +} + +/** + * Handle stat() error. + * + * @param {Error} error + * @private + */ + +SendStream.prototype.onStatError = function onStatError (error) { + switch (error.code) { + case 'ENAMETOOLONG': + case 'ENOENT': + case 'ENOTDIR': + this.error(404, error) + break + default: + this.error(500, error) + break + } +} + +/** + * Check if the cache is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isFresh = function isFresh () { + return fresh(this.req.headers, { + etag: this.res.getHeader('ETag'), + 'last-modified': this.res.getHeader('Last-Modified') + }) +} + +/** + * Check if the range is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isRangeFresh = function isRangeFresh () { + var ifRange = this.req.headers['if-range'] + + if (!ifRange) { + return true + } + + // if-range as etag + if (ifRange.indexOf('"') !== -1) { + var etag = this.res.getHeader('ETag') + return Boolean(etag && ifRange.indexOf(etag) !== -1) + } + + // if-range as modified date + var lastModified = this.res.getHeader('Last-Modified') + return parseHttpDate(lastModified) <= parseHttpDate(ifRange) +} + +/** + * Redirect to path. + * + * @param {string} path + * @private + */ + +SendStream.prototype.redirect = function redirect (path) { + var res = this.res + + if (hasListeners(this, 'directory')) { + this.emit('directory', res, path) + return + } + + if (this.hasTrailingSlash()) { + this.error(403) + return + } + + var loc = encodeUrl(collapseLeadingSlashes(this.path + '/')) + var doc = createHtmlDocument('Redirecting', 'Redirecting to ' + escapeHtml(loc)) + + // redirect + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(doc) +} + +/** + * Pipe to `res. + * + * @param {Stream} res + * @return {Stream} res + * @api public + */ + +SendStream.prototype.pipe = function pipe (res) { + // root path + var root = this._root + + // references + this.res = res + + // decode the path + var path = decode(this.path) + if (path === -1) { + this.error(400) + return res + } + + // null byte(s) + if (~path.indexOf('\0')) { + this.error(400) + return res + } + + var parts + if (root !== null) { + // normalize + if (path) { + path = normalize('.' + sep + path) + } + + // malicious path + if (UP_PATH_REGEXP.test(path)) { + debug('malicious path "%s"', path) + this.error(403) + return res + } + + // explode path parts + parts = path.split(sep) + + // join / normalize from optional root dir + path = normalize(join(root, path)) + } else { + // ".." is malicious without "root" + if (UP_PATH_REGEXP.test(path)) { + debug('malicious path "%s"', path) + this.error(403) + return res + } + + // explode path parts + parts = normalize(path).split(sep) + + // resolve the path + path = resolve(path) + } + + // dotfile handling + if (containsDotFile(parts)) { + var access = this._dotfiles + + // legacy support + if (access === undefined) { + access = parts[parts.length - 1][0] === '.' + ? (this._hidden ? 'allow' : 'ignore') + : 'allow' + } + + debug('%s dotfile "%s"', access, path) + switch (access) { + case 'allow': + break + case 'deny': + this.error(403) + return res + case 'ignore': + default: + this.error(404) + return res + } + } + + // index file support + if (this._index.length && this.hasTrailingSlash()) { + this.sendIndex(path) + return res + } + + this.sendFile(path) + return res +} + +/** + * Transfer `path`. + * + * @param {String} path + * @api public + */ + +SendStream.prototype.send = function send (path, stat) { + var len = stat.size + var options = this.options + var opts = {} + var res = this.res + var req = this.req + var ranges = req.headers.range + var offset = options.start || 0 + + if (headersSent(res)) { + // impossible to send now + this.headersAlreadySent() + return + } + + debug('pipe "%s"', path) + + // set header fields + this.setHeader(path, stat) + + // set content-type + this.type(path) + + // conditional GET support + if (this.isConditionalGET()) { + if (this.isPreconditionFailure()) { + this.error(412) + return + } + + if (this.isCachable() && this.isFresh()) { + this.notModified() + return + } + } + + // adjust len to start/end options + len = Math.max(0, len - offset) + if (options.end !== undefined) { + var bytes = options.end - offset + 1 + if (len > bytes) len = bytes + } + + // Range support + if (this._acceptRanges && BYTES_RANGE_REGEXP.test(ranges)) { + // parse + ranges = parseRange(len, ranges, { + combine: true + }) + + // If-Range support + if (!this.isRangeFresh()) { + debug('range stale') + ranges = -2 + } + + // unsatisfiable + if (ranges === -1) { + debug('range unsatisfiable') + + // Content-Range + res.setHeader('Content-Range', contentRange('bytes', len)) + + // 416 Requested Range Not Satisfiable + return this.error(416, { + headers: { 'Content-Range': res.getHeader('Content-Range') } + }) + } + + // valid (syntactically invalid/multiple ranges are treated as a regular response) + if (ranges !== -2 && ranges.length === 1) { + debug('range %j', ranges) + + // Content-Range + res.statusCode = 206 + res.setHeader('Content-Range', contentRange('bytes', len, ranges[0])) + + // adjust for requested range + offset += ranges[0].start + len = ranges[0].end - ranges[0].start + 1 + } + } + + // clone options + for (var prop in options) { + opts[prop] = options[prop] + } + + // set read options + opts.start = offset + opts.end = Math.max(offset, offset + len - 1) + + // content-length + res.setHeader('Content-Length', len) + + // HEAD support + if (req.method === 'HEAD') { + res.end() + return + } + + this.stream(path, opts) +} + +/** + * Transfer file for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendFile = function sendFile (path) { + var i = 0 + var self = this + + debug('stat "%s"', path) + fs.stat(path, function onstat (err, stat) { + if (err && err.code === 'ENOENT' && !extname(path) && path[path.length - 1] !== sep) { + // not found, check extensions + return next(err) + } + if (err) return self.onStatError(err) + if (stat.isDirectory()) return self.redirect(path) + self.emit('file', path, stat) + self.send(path, stat) + }) + + function next (err) { + if (self._extensions.length <= i) { + return err + ? self.onStatError(err) + : self.error(404) + } + + var p = path + '.' + self._extensions[i++] + + debug('stat "%s"', p) + fs.stat(p, function (err, stat) { + if (err) return next(err) + if (stat.isDirectory()) return next() + self.emit('file', p, stat) + self.send(p, stat) + }) + } +} + +/** + * Transfer index for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendIndex = function sendIndex (path) { + var i = -1 + var self = this + + function next (err) { + if (++i >= self._index.length) { + if (err) return self.onStatError(err) + return self.error(404) + } + + var p = join(path, self._index[i]) + + debug('stat "%s"', p) + fs.stat(p, function (err, stat) { + if (err) return next(err) + if (stat.isDirectory()) return next() + self.emit('file', p, stat) + self.send(p, stat) + }) + } + + next() +} + +/** + * Stream `path` to the response. + * + * @param {String} path + * @param {Object} options + * @api private + */ + +SendStream.prototype.stream = function stream (path, options) { + var self = this + var res = this.res + + // pipe + var stream = fs.createReadStream(path, options) + this.emit('stream', stream) + stream.pipe(res) + + // cleanup + function cleanup () { + destroy(stream, true) + } + + // response finished, cleanup + onFinished(res, cleanup) + + // error handling + stream.on('error', function onerror (err) { + // clean up stream early + cleanup() + + // error + self.onStatError(err) + }) + + // end + stream.on('end', function onend () { + self.emit('end') + }) +} + +/** + * Set content-type based on `path` + * if it hasn't been explicitly set. + * + * @param {String} path + * @api private + */ + +SendStream.prototype.type = function type (path) { + var res = this.res + + if (res.getHeader('Content-Type')) return + + var type = mime.lookup(path) + + if (!type) { + debug('no content-type') + return + } + + var charset = mime.charsets.lookup(type) + + debug('content-type %s', type) + res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : '')) +} + +/** + * Set response header fields, most + * fields may be pre-defined. + * + * @param {String} path + * @param {Object} stat + * @api private + */ + +SendStream.prototype.setHeader = function setHeader (path, stat) { + var res = this.res + + this.emit('headers', res, path, stat) + + if (this._acceptRanges && !res.getHeader('Accept-Ranges')) { + debug('accept ranges') + res.setHeader('Accept-Ranges', 'bytes') + } + + if (this._cacheControl && !res.getHeader('Cache-Control')) { + var cacheControl = 'public, max-age=' + Math.floor(this._maxage / 1000) + + if (this._immutable) { + cacheControl += ', immutable' + } + + debug('cache-control %s', cacheControl) + res.setHeader('Cache-Control', cacheControl) + } + + if (this._lastModified && !res.getHeader('Last-Modified')) { + var modified = stat.mtime.toUTCString() + debug('modified %s', modified) + res.setHeader('Last-Modified', modified) + } + + if (this._etag && !res.getHeader('ETag')) { + var val = etag(stat) + debug('etag %s', val) + res.setHeader('ETag', val) + } +} + +/** + * Clear all headers from a response. + * + * @param {object} res + * @private + */ + +function clearHeaders (res) { + var headers = getHeaderNames(res) + + for (var i = 0; i < headers.length; i++) { + res.removeHeader(headers[i]) + } +} + +/** + * Collapse all leading slashes into a single slash + * + * @param {string} str + * @private + */ +function collapseLeadingSlashes (str) { + for (var i = 0; i < str.length; i++) { + if (str[i] !== '/') { + break + } + } + + return i > 1 + ? '/' + str.substr(i) + : str +} + +/** + * Determine if path parts contain a dotfile. + * + * @api private + */ + +function containsDotFile (parts) { + for (var i = 0; i < parts.length; i++) { + var part = parts[i] + if (part.length > 1 && part[0] === '.') { + return true + } + } + + return false +} + +/** + * Create a Content-Range header. + * + * @param {string} type + * @param {number} size + * @param {array} [range] + */ + +function contentRange (type, size, range) { + return type + ' ' + (range ? range.start + '-' + range.end : '*') + '/' + size +} + +/** + * Create a minimal HTML document. + * + * @param {string} title + * @param {string} body + * @private + */ + +function createHtmlDocument (title, body) { + return '\n' + + '\n' + + '\n' + + '\n' + + '' + title + '\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' +} + +/** + * Create a HttpError object from simple arguments. + * + * @param {number} status + * @param {Error|object} err + * @private + */ + +function createHttpError (status, err) { + if (!err) { + return createError(status) + } + + return err instanceof Error + ? createError(status, err, { expose: false }) + : createError(status, err) +} + +/** + * decodeURIComponent. + * + * Allows V8 to only deoptimize this fn instead of all + * of send(). + * + * @param {String} path + * @api private + */ + +function decode (path) { + try { + return decodeURIComponent(path) + } catch (err) { + return -1 + } +} + +/** + * Get the header names on a respnse. + * + * @param {object} res + * @returns {array[string]} + * @private + */ + +function getHeaderNames (res) { + return typeof res.getHeaderNames !== 'function' + ? Object.keys(res._headers || {}) + : res.getHeaderNames() +} + +/** + * Determine if emitter has listeners of a given type. + * + * The way to do this check is done three different ways in Node.js >= 0.8 + * so this consolidates them into a minimal set using instance methods. + * + * @param {EventEmitter} emitter + * @param {string} type + * @returns {boolean} + * @private + */ + +function hasListeners (emitter, type) { + var count = typeof emitter.listenerCount !== 'function' + ? emitter.listeners(type).length + : emitter.listenerCount(type) + + return count > 0 +} + +/** + * Determine if the response headers have been sent. + * + * @param {object} res + * @returns {boolean} + * @private + */ + +function headersSent (res) { + return typeof res.headersSent !== 'boolean' + ? Boolean(res._header) + : res.headersSent +} + +/** + * Normalize the index option into an array. + * + * @param {boolean|string|array} val + * @param {string} name + * @private + */ + +function normalizeList (val, name) { + var list = [].concat(val || []) + + for (var i = 0; i < list.length; i++) { + if (typeof list[i] !== 'string') { + throw new TypeError(name + ' must be array of strings or false') + } + } + + return list +} + +/** + * Parse an HTTP Date into a number. + * + * @param {string} date + * @private + */ + +function parseHttpDate (date) { + var timestamp = date && Date.parse(date) + + return typeof timestamp === 'number' + ? timestamp + : NaN +} + +/** + * Parse a HTTP token list. + * + * @param {string} str + * @private + */ + +function parseTokenList (str) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = str.length; i < len; i++) { + switch (str.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + if (start !== end) { + list.push(str.substring(start, end)) + } + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + if (start !== end) { + list.push(str.substring(start, end)) + } + + return list +} + +/** + * Set an object of headers on a response. + * + * @param {object} res + * @param {object} headers + * @private + */ + +function setHeaders (res, headers) { + var keys = Object.keys(headers) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + res.setHeader(key, headers[key]) + } +} diff --git a/node_modules/send/node_modules/.bin/mime b/node_modules/send/node_modules/.bin/mime new file mode 120000 index 0000000..fbb7ee0 --- /dev/null +++ b/node_modules/send/node_modules/.bin/mime @@ -0,0 +1 @@ +../mime/cli.js \ No newline at end of file diff --git a/node_modules/send/node_modules/debug/.coveralls.yml b/node_modules/send/node_modules/debug/.coveralls.yml new file mode 100644 index 0000000..20a7068 --- /dev/null +++ b/node_modules/send/node_modules/debug/.coveralls.yml @@ -0,0 +1 @@ +repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/node_modules/send/node_modules/debug/.eslintrc b/node_modules/send/node_modules/debug/.eslintrc new file mode 100644 index 0000000..8a37ae2 --- /dev/null +++ b/node_modules/send/node_modules/debug/.eslintrc @@ -0,0 +1,11 @@ +{ + "env": { + "browser": true, + "node": true + }, + "rules": { + "no-console": 0, + "no-empty": [1, { "allowEmptyCatch": true }] + }, + "extends": "eslint:recommended" +} diff --git a/node_modules/send/node_modules/debug/.npmignore b/node_modules/send/node_modules/debug/.npmignore new file mode 100644 index 0000000..5f60eec --- /dev/null +++ b/node_modules/send/node_modules/debug/.npmignore @@ -0,0 +1,9 @@ +support +test +examples +example +*.sock +dist +yarn.lock +coverage +bower.json diff --git a/node_modules/send/node_modules/debug/.travis.yml b/node_modules/send/node_modules/debug/.travis.yml new file mode 100644 index 0000000..6c6090c --- /dev/null +++ b/node_modules/send/node_modules/debug/.travis.yml @@ -0,0 +1,14 @@ + +language: node_js +node_js: + - "6" + - "5" + - "4" + +install: + - make node_modules + +script: + - make lint + - make test + - make coveralls diff --git a/node_modules/send/node_modules/debug/CHANGELOG.md b/node_modules/send/node_modules/debug/CHANGELOG.md new file mode 100644 index 0000000..eadaa18 --- /dev/null +++ b/node_modules/send/node_modules/debug/CHANGELOG.md @@ -0,0 +1,362 @@ + +2.6.9 / 2017-09-22 +================== + + * remove ReDoS regexp in %o formatter (#504) + +2.6.8 / 2017-05-18 +================== + + * Fix: Check for undefined on browser globals (#462, @marbemac) + +2.6.7 / 2017-05-16 +================== + + * Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom) + * Fix: Inline extend function in node implementation (#452, @dougwilson) + * Docs: Fix typo (#455, @msasad) + +2.6.5 / 2017-04-27 +================== + + * Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek) + * Misc: clean up browser reference checks (#447, @thebigredgeek) + * Misc: add npm-debug.log to .gitignore (@thebigredgeek) + + +2.6.4 / 2017-04-20 +================== + + * Fix: bug that would occure if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo) + * Chore: ignore bower.json in npm installations. (#437, @joaovieira) + * Misc: update "ms" to v0.7.3 (@tootallnate) + +2.6.3 / 2017-03-13 +================== + + * Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts) + * Docs: Changelog fix (@thebigredgeek) + +2.6.2 / 2017-03-10 +================== + + * Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin) + * Docs: Add backers and sponsors from Open Collective (#422, @piamancini) + * Docs: Add Slackin invite badge (@tootallnate) + +2.6.1 / 2017-02-10 +================== + + * Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error + * Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0) + * Fix: IE8 "Expected identifier" error (#414, @vgoma) + * Fix: Namespaces would not disable once enabled (#409, @musikov) + +2.6.0 / 2016-12-28 +================== + + * Fix: added better null pointer checks for browser useColors (@thebigredgeek) + * Improvement: removed explicit `window.debug` export (#404, @tootallnate) + * Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate) + +2.5.2 / 2016-12-25 +================== + + * Fix: reference error on window within webworkers (#393, @KlausTrainer) + * Docs: fixed README typo (#391, @lurch) + * Docs: added notice about v3 api discussion (@thebigredgeek) + +2.5.1 / 2016-12-20 +================== + + * Fix: babel-core compatibility + +2.5.0 / 2016-12-20 +================== + + * Fix: wrong reference in bower file (@thebigredgeek) + * Fix: webworker compatibility (@thebigredgeek) + * Fix: output formatting issue (#388, @kribblo) + * Fix: babel-loader compatibility (#383, @escwald) + * Misc: removed built asset from repo and publications (@thebigredgeek) + * Misc: moved source files to /src (#378, @yamikuronue) + * Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue) + * Test: coveralls integration (#378, @yamikuronue) + * Docs: simplified language in the opening paragraph (#373, @yamikuronue) + +2.4.5 / 2016-12-17 +================== + + * Fix: `navigator` undefined in Rhino (#376, @jochenberger) + * Fix: custom log function (#379, @hsiliev) + * Improvement: bit of cleanup + linting fixes (@thebigredgeek) + * Improvement: rm non-maintainted `dist/` dir (#375, @freewil) + * Docs: simplified language in the opening paragraph. (#373, @yamikuronue) + +2.4.4 / 2016-12-14 +================== + + * Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts) + +2.4.3 / 2016-12-14 +================== + + * Fix: navigation.userAgent error for react native (#364, @escwald) + +2.4.2 / 2016-12-14 +================== + + * Fix: browser colors (#367, @tootallnate) + * Misc: travis ci integration (@thebigredgeek) + * Misc: added linting and testing boilerplate with sanity check (@thebigredgeek) + +2.4.1 / 2016-12-13 +================== + + * Fix: typo that broke the package (#356) + +2.4.0 / 2016-12-13 +================== + + * Fix: bower.json references unbuilt src entry point (#342, @justmatt) + * Fix: revert "handle regex special characters" (@tootallnate) + * Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate) + * Feature: %O`(big O) pretty-prints objects (#322, @tootallnate) + * Improvement: allow colors in workers (#335, @botverse) + * Improvement: use same color for same namespace. (#338, @lchenay) + +2.3.3 / 2016-11-09 +================== + + * Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne) + * Fix: Returning `localStorage` saved values (#331, Levi Thomason) + * Improvement: Don't create an empty object when no `process` (Nathan Rajlich) + +2.3.2 / 2016-11-09 +================== + + * Fix: be super-safe in index.js as well (@TooTallNate) + * Fix: should check whether process exists (Tom Newby) + +2.3.1 / 2016-11-09 +================== + + * Fix: Added electron compatibility (#324, @paulcbetts) + * Improvement: Added performance optimizations (@tootallnate) + * Readme: Corrected PowerShell environment variable example (#252, @gimre) + * Misc: Removed yarn lock file from source control (#321, @fengmk2) + +2.3.0 / 2016-11-07 +================== + + * Fix: Consistent placement of ms diff at end of output (#215, @gorangajic) + * Fix: Escaping of regex special characters in namespace strings (#250, @zacronos) + * Fix: Fixed bug causing crash on react-native (#282, @vkarpov15) + * Feature: Enabled ES6+ compatible import via default export (#212 @bucaran) + * Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom) + * Package: Update "ms" to 0.7.2 (#315, @DevSide) + * Package: removed superfluous version property from bower.json (#207 @kkirsche) + * Readme: fix USE_COLORS to DEBUG_COLORS + * Readme: Doc fixes for format string sugar (#269, @mlucool) + * Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0) + * Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable) + * Readme: better docs for browser support (#224, @matthewmueller) + * Tooling: Added yarn integration for development (#317, @thebigredgeek) + * Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek) + * Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman) + * Misc: Updated contributors (@thebigredgeek) + +2.2.0 / 2015-05-09 +================== + + * package: update "ms" to v0.7.1 (#202, @dougwilson) + * README: add logging to file example (#193, @DanielOchoa) + * README: fixed a typo (#191, @amir-s) + * browser: expose `storage` (#190, @stephenmathieson) + * Makefile: add a `distclean` target (#189, @stephenmathieson) + +2.1.3 / 2015-03-13 +================== + + * Updated stdout/stderr example (#186) + * Updated example/stdout.js to match debug current behaviour + * Renamed example/stderr.js to stdout.js + * Update Readme.md (#184) + * replace high intensity foreground color for bold (#182, #183) + +2.1.2 / 2015-03-01 +================== + + * dist: recompile + * update "ms" to v0.7.0 + * package: update "browserify" to v9.0.3 + * component: fix "ms.js" repo location + * changed bower package name + * updated documentation about using debug in a browser + * fix: security error on safari (#167, #168, @yields) + +2.1.1 / 2014-12-29 +================== + + * browser: use `typeof` to check for `console` existence + * browser: check for `console.log` truthiness (fix IE 8/9) + * browser: add support for Chrome apps + * Readme: added Windows usage remarks + * Add `bower.json` to properly support bower install + +2.1.0 / 2014-10-15 +================== + + * node: implement `DEBUG_FD` env variable support + * package: update "browserify" to v6.1.0 + * package: add "license" field to package.json (#135, @panuhorsmalahti) + +2.0.0 / 2014-09-01 +================== + + * package: update "browserify" to v5.11.0 + * node: use stderr rather than stdout for logging (#29, @stephenmathieson) + +1.0.4 / 2014-07-15 +================== + + * dist: recompile + * example: remove `console.info()` log usage + * example: add "Content-Type" UTF-8 header to browser example + * browser: place %c marker after the space character + * browser: reset the "content" color via `color: inherit` + * browser: add colors support for Firefox >= v31 + * debug: prefer an instance `log()` function over the global one (#119) + * Readme: update documentation about styled console logs for FF v31 (#116, @wryk) + +1.0.3 / 2014-07-09 +================== + + * Add support for multiple wildcards in namespaces (#122, @seegno) + * browser: fix lint + +1.0.2 / 2014-06-10 +================== + + * browser: update color palette (#113, @gscottolson) + * common: make console logging function configurable (#108, @timoxley) + * node: fix %o colors on old node <= 0.8.x + * Makefile: find node path using shell/which (#109, @timoxley) + +1.0.1 / 2014-06-06 +================== + + * browser: use `removeItem()` to clear localStorage + * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) + * package: add "contributors" section + * node: fix comment typo + * README: list authors + +1.0.0 / 2014-06-04 +================== + + * make ms diff be global, not be scope + * debug: ignore empty strings in enable() + * node: make DEBUG_COLORS able to disable coloring + * *: export the `colors` array + * npmignore: don't publish the `dist` dir + * Makefile: refactor to use browserify + * package: add "browserify" as a dev dependency + * Readme: add Web Inspector Colors section + * node: reset terminal color for the debug content + * node: map "%o" to `util.inspect()` + * browser: map "%j" to `JSON.stringify()` + * debug: add custom "formatters" + * debug: use "ms" module for humanizing the diff + * Readme: add "bash" syntax highlighting + * browser: add Firebug color support + * browser: add colors for WebKit browsers + * node: apply log to `console` + * rewrite: abstract common logic for Node & browsers + * add .jshintrc file + +0.8.1 / 2014-04-14 +================== + + * package: re-add the "component" section + +0.8.0 / 2014-03-30 +================== + + * add `enable()` method for nodejs. Closes #27 + * change from stderr to stdout + * remove unnecessary index.js file + +0.7.4 / 2013-11-13 +================== + + * remove "browserify" key from package.json (fixes something in browserify) + +0.7.3 / 2013-10-30 +================== + + * fix: catch localStorage security error when cookies are blocked (Chrome) + * add debug(err) support. Closes #46 + * add .browser prop to package.json. Closes #42 + +0.7.2 / 2013-02-06 +================== + + * fix package.json + * fix: Mobile Safari (private mode) is broken with debug + * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript + +0.7.1 / 2013-02-05 +================== + + * add repository URL to package.json + * add DEBUG_COLORED to force colored output + * add browserify support + * fix component. Closes #24 + +0.7.0 / 2012-05-04 +================== + + * Added .component to package.json + * Added debug.component.js build + +0.6.0 / 2012-03-16 +================== + + * Added support for "-" prefix in DEBUG [Vinay Pulim] + * Added `.enabled` flag to the node version [TooTallNate] + +0.5.0 / 2012-02-02 +================== + + * Added: humanize diffs. Closes #8 + * Added `debug.disable()` to the CS variant + * Removed padding. Closes #10 + * Fixed: persist client-side variant again. Closes #9 + +0.4.0 / 2012-02-01 +================== + + * Added browser variant support for older browsers [TooTallNate] + * Added `debug.enable('project:*')` to browser variant [TooTallNate] + * Added padding to diff (moved it to the right) + +0.3.0 / 2012-01-26 +================== + + * Added millisecond diff when isatty, otherwise UTC string + +0.2.0 / 2012-01-22 +================== + + * Added wildcard support + +0.1.0 / 2011-12-02 +================== + + * Added: remove colors unless stderr isatty [TooTallNate] + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/send/node_modules/debug/LICENSE b/node_modules/send/node_modules/debug/LICENSE new file mode 100644 index 0000000..658c933 --- /dev/null +++ b/node_modules/send/node_modules/debug/LICENSE @@ -0,0 +1,19 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the 'Software'), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/send/node_modules/debug/Makefile b/node_modules/send/node_modules/debug/Makefile new file mode 100644 index 0000000..584da8b --- /dev/null +++ b/node_modules/send/node_modules/debug/Makefile @@ -0,0 +1,50 @@ +# get Makefile directory name: http://stackoverflow.com/a/5982798/376773 +THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) +THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) + +# BIN directory +BIN := $(THIS_DIR)/node_modules/.bin + +# Path +PATH := node_modules/.bin:$(PATH) +SHELL := /bin/bash + +# applications +NODE ?= $(shell which node) +YARN ?= $(shell which yarn) +PKG ?= $(if $(YARN),$(YARN),$(NODE) $(shell which npm)) +BROWSERIFY ?= $(NODE) $(BIN)/browserify + +.FORCE: + +install: node_modules + +node_modules: package.json + @NODE_ENV= $(PKG) install + @touch node_modules + +lint: .FORCE + eslint browser.js debug.js index.js node.js + +test-node: .FORCE + istanbul cover node_modules/mocha/bin/_mocha -- test/**.js + +test-browser: .FORCE + mkdir -p dist + + @$(BROWSERIFY) \ + --standalone debug \ + . > dist/debug.js + + karma start --single-run + rimraf dist + +test: .FORCE + concurrently \ + "make test-node" \ + "make test-browser" + +coveralls: + cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js + +.PHONY: all install clean distclean diff --git a/node_modules/send/node_modules/debug/README.md b/node_modules/send/node_modules/debug/README.md new file mode 100644 index 0000000..f67be6b --- /dev/null +++ b/node_modules/send/node_modules/debug/README.md @@ -0,0 +1,312 @@ +# debug +[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) +[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) + + + +A tiny node.js debugging utility modelled after node core's debugging technique. + +**Discussion around the V3 API is under way [here](https://github.com/visionmedia/debug/issues/370)** + +## Installation + +```bash +$ npm install debug +``` + +## Usage + +`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +Example _app.js_: + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %s', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example _worker.js_: + +```js +var debug = require('debug')('worker'); + +setInterval(function(){ + debug('doing some work'); +}, 1000); +``` + + The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: + + ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) + + ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) + +#### Windows note + + On Windows the environment variable is set using the `set` command. + + ```cmd + set DEBUG=*,-not_this + ``` + + Note that PowerShell uses different syntax to set environment variables. + + ```cmd + $env:DEBUG = "*,-not_this" + ``` + +Then, run the program to be debugged as usual. + +## Millisecond diff + + When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) + + When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: + + ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) + +## Conventions + + If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". + +## Wildcards + + The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + + You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". + +## Environment Variables + + When running through Node.js, you can set a few environment variables that will + change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + + + __Note:__ The environment variables beginning with `DEBUG_` end up being + converted into an Options object that gets used with `%o`/`%O` formatters. + See the Node.js documentation for + [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) + for the complete list. + +## Formatters + + + Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + +### Custom formatters + + You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: + +```js +const createDebug = require('debug') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// …elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + +## Browser support + You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), + or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), + if you don't want to build it yourself. + + Debug's enable state is currently persisted by `localStorage`. + Consider the situation shown below where you have `worker:a` and `worker:b`, + and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + +#### Web Inspector Colors + + Colors are also enabled on "Web Inspectors" that understand the `%c` formatting + option. These are WebKit web inspectors, Firefox ([since version + 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) + and the Firebug plugin for Firefox (any version). + + Colored output looks something like: + + ![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png) + + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +Example _stdout.js_: + +```js +var debug = require('debug'); +var error = debug('app:error'); + +// by default stderr is used +error('goes to stderr!'); + +var log = debug('app:log'); +// set this namespace to log via console.log +log.log = console.log.bind(console); // don't forget to bind to console! +log('goes to stdout'); +error('still goes to stderr!'); + +// set all output to go via console.info +// overrides all per-namespace log settings +debug.log = console.info.bind(console); +error('now goes to stdout via console.info'); +log('still goes to stdout, but via console.info now'); +``` + + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + - Andrew Rhyne + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## License + +(The MIT License) + +Copyright (c) 2014-2016 TJ Holowaychuk <tj@vision-media.ca> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/send/node_modules/debug/component.json b/node_modules/send/node_modules/debug/component.json new file mode 100644 index 0000000..9de2641 --- /dev/null +++ b/node_modules/send/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.6.9", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "src/browser.js", + "scripts": [ + "src/browser.js", + "src/debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/node_modules/send/node_modules/debug/karma.conf.js b/node_modules/send/node_modules/debug/karma.conf.js new file mode 100644 index 0000000..103a82d --- /dev/null +++ b/node_modules/send/node_modules/debug/karma.conf.js @@ -0,0 +1,70 @@ +// Karma configuration +// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC) + +module.exports = function(config) { + config.set({ + + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: '', + + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ['mocha', 'chai', 'sinon'], + + + // list of files / patterns to load in the browser + files: [ + 'dist/debug.js', + 'test/*spec.js' + ], + + + // list of files to exclude + exclude: [ + 'src/node.js' + ], + + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + }, + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ['progress'], + + + // web server port + port: 9876, + + + // enable / disable colors in the output (reporters and logs) + colors: true, + + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: true, + + + // start these browsers + // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + browsers: ['PhantomJS'], + + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: false, + + // Concurrency level + // how many browser should be started simultaneous + concurrency: Infinity + }) +} diff --git a/node_modules/send/node_modules/debug/node.js b/node_modules/send/node_modules/debug/node.js new file mode 100644 index 0000000..7fc36fe --- /dev/null +++ b/node_modules/send/node_modules/debug/node.js @@ -0,0 +1 @@ +module.exports = require('./src/node'); diff --git a/node_modules/send/node_modules/debug/node_modules/ms/index.js b/node_modules/send/node_modules/debug/node_modules/ms/index.js new file mode 100644 index 0000000..6a522b1 --- /dev/null +++ b/node_modules/send/node_modules/debug/node_modules/ms/index.js @@ -0,0 +1,152 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} diff --git a/node_modules/send/node_modules/debug/node_modules/ms/license.md b/node_modules/send/node_modules/debug/node_modules/ms/license.md new file mode 100644 index 0000000..69b6125 --- /dev/null +++ b/node_modules/send/node_modules/debug/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Zeit, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/send/node_modules/debug/node_modules/ms/package.json b/node_modules/send/node_modules/debug/node_modules/ms/package.json new file mode 100644 index 0000000..6a31c81 --- /dev/null +++ b/node_modules/send/node_modules/debug/node_modules/ms/package.json @@ -0,0 +1,37 @@ +{ + "name": "ms", + "version": "2.0.0", + "description": "Tiny milisecond conversion utility", + "repository": "zeit/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "3.19.0", + "expect.js": "0.3.1", + "husky": "0.13.3", + "lint-staged": "3.4.1", + "mocha": "3.4.1" + } +} diff --git a/node_modules/send/node_modules/debug/node_modules/ms/readme.md b/node_modules/send/node_modules/debug/node_modules/ms/readme.md new file mode 100644 index 0000000..84a9974 --- /dev/null +++ b/node_modules/send/node_modules/debug/node_modules/ms/readme.md @@ -0,0 +1,51 @@ +# ms + +[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) +[![Slack Channel](http://zeit-slackin.now.sh/badge.svg)](https://zeit.chat/) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +``` + +### Convert from milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(ms('10 hours')) // "10h" +``` + +### Time format written-out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [node](https://nodejs.org) and in the browser. +- If a number is supplied to `ms`, a string with a unit is returned. +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`). +- If you pass a string with a number and a valid unit, the number of equivalent ms is returned. + +## Caught a bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, node will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/send/node_modules/debug/package.json b/node_modules/send/node_modules/debug/package.json new file mode 100644 index 0000000..dc787ba --- /dev/null +++ b/node_modules/send/node_modules/debug/package.json @@ -0,0 +1,49 @@ +{ + "name": "debug", + "version": "2.6.9", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": "TJ Holowaychuk ", + "contributors": [ + "Nathan Rajlich (http://n8.io)", + "Andrew Rhyne " + ], + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + }, + "devDependencies": { + "browserify": "9.0.3", + "chai": "^3.5.0", + "concurrently": "^3.1.0", + "coveralls": "^2.11.15", + "eslint": "^3.12.1", + "istanbul": "^0.4.5", + "karma": "^1.3.0", + "karma-chai": "^0.1.0", + "karma-mocha": "^1.3.0", + "karma-phantomjs-launcher": "^1.0.2", + "karma-sinon": "^1.0.5", + "mocha": "^3.2.0", + "mocha-lcov-reporter": "^1.2.0", + "rimraf": "^2.5.4", + "sinon": "^1.17.6", + "sinon-chai": "^2.8.0" + }, + "main": "./src/index.js", + "browser": "./src/browser.js", + "component": { + "scripts": { + "debug/index.js": "browser.js", + "debug/debug.js": "debug.js" + } + } +} diff --git a/node_modules/send/node_modules/debug/src/browser.js b/node_modules/send/node_modules/debug/src/browser.js new file mode 100644 index 0000000..7106924 --- /dev/null +++ b/node_modules/send/node_modules/debug/src/browser.js @@ -0,0 +1,185 @@ +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return; + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} diff --git a/node_modules/send/node_modules/debug/src/debug.js b/node_modules/send/node_modules/debug/src/debug.js new file mode 100644 index 0000000..6a5e3fc --- /dev/null +++ b/node_modules/send/node_modules/debug/src/debug.js @@ -0,0 +1,202 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + +exports.formatters = {}; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + return debug; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} diff --git a/node_modules/send/node_modules/debug/src/index.js b/node_modules/send/node_modules/debug/src/index.js new file mode 100644 index 0000000..e12cf4d --- /dev/null +++ b/node_modules/send/node_modules/debug/src/index.js @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ + +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} diff --git a/node_modules/send/node_modules/debug/src/inspector-log.js b/node_modules/send/node_modules/debug/src/inspector-log.js new file mode 100644 index 0000000..60ea6c0 --- /dev/null +++ b/node_modules/send/node_modules/debug/src/inspector-log.js @@ -0,0 +1,15 @@ +module.exports = inspectorLog; + +// black hole +const nullStream = new (require('stream').Writable)(); +nullStream._write = () => {}; + +/** + * Outputs a `console.log()` to the Node.js Inspector console *only*. + */ +function inspectorLog() { + const stdout = console._stdout; + console._stdout = nullStream; + console.log.apply(console, arguments); + console._stdout = stdout; +} diff --git a/node_modules/send/node_modules/debug/src/node.js b/node_modules/send/node_modules/debug/src/node.js new file mode 100644 index 0000000..b15109c --- /dev/null +++ b/node_modules/send/node_modules/debug/src/node.js @@ -0,0 +1,248 @@ +/** + * Module dependencies. + */ + +var tty = require('tty'); +var util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); + + obj[prop] = val; + return obj; +}, {}); + +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ + +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} + +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; + +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ + +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; + + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } +} + +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ + +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ + +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); + + // Note stream._type is used for test-module-load-list.js + + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; + + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + case 'FILE': + var fs = require('fs'); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; + + case 'PIPE': + case 'TCP': + var net = require('net'); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); + + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; + + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } + + // For supporting legacy API we put the FD here. + stream.fd = fd; + + stream._isStdio = true; + + return stream; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init (debug) { + debug.inspectOpts = {}; + + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); diff --git a/node_modules/send/node_modules/mime/.npmignore b/node_modules/send/node_modules/mime/.npmignore new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/send/node_modules/mime/CHANGELOG.md b/node_modules/send/node_modules/mime/CHANGELOG.md new file mode 100644 index 0000000..f127535 --- /dev/null +++ b/node_modules/send/node_modules/mime/CHANGELOG.md @@ -0,0 +1,164 @@ +# Changelog + +## v1.6.0 (24/11/2017) +*No changelog for this release.* + +--- + +## v2.0.4 (24/11/2017) +- [**closed**] Switch to mime-score module for resolving extension contention issues. [#182](https://github.com/broofa/node-mime/issues/182) +- [**closed**] Update mime-db to 1.31.0 in v1.x branch [#181](https://github.com/broofa/node-mime/issues/181) + +--- + +## v1.5.0 (22/11/2017) +- [**closed**] need ES5 version ready in npm package [#179](https://github.com/broofa/node-mime/issues/179) +- [**closed**] mime-db no trace of iWork - pages / numbers / etc. [#178](https://github.com/broofa/node-mime/issues/178) +- [**closed**] How it works in brownser ? [#176](https://github.com/broofa/node-mime/issues/176) +- [**closed**] Missing `./Mime` [#175](https://github.com/broofa/node-mime/issues/175) +- [**closed**] Vulnerable Regular Expression [#167](https://github.com/broofa/node-mime/issues/167) + +--- + +## v2.0.3 (25/09/2017) +*No changelog for this release.* + +--- + +## v1.4.1 (25/09/2017) +- [**closed**] Issue when bundling with webpack [#172](https://github.com/broofa/node-mime/issues/172) + +--- + +## v2.0.2 (15/09/2017) +- [**V2**] fs.readFileSync is not a function [#165](https://github.com/broofa/node-mime/issues/165) +- [**closed**] The extension for video/quicktime should map to .mov, not .qt [#164](https://github.com/broofa/node-mime/issues/164) +- [**V2**] [v2 Feedback request] Mime class API [#163](https://github.com/broofa/node-mime/issues/163) +- [**V2**] [v2 Feedback request] Resolving conflicts over extensions [#162](https://github.com/broofa/node-mime/issues/162) +- [**V2**] Allow callers to load module with official, full, or no defined types. [#161](https://github.com/broofa/node-mime/issues/161) +- [**V2**] Use "facets" to resolve extension conflicts [#160](https://github.com/broofa/node-mime/issues/160) +- [**V2**] Remove fs and path dependencies [#152](https://github.com/broofa/node-mime/issues/152) +- [**V2**] Default content-type should not be application/octet-stream [#139](https://github.com/broofa/node-mime/issues/139) +- [**V2**] reset mime-types [#124](https://github.com/broofa/node-mime/issues/124) +- [**V2**] Extensionless paths should return null or false [#113](https://github.com/broofa/node-mime/issues/113) + +--- + +## v2.0.1 (14/09/2017) +- [**closed**] Changelog for v2.0 does not mention breaking changes [#171](https://github.com/broofa/node-mime/issues/171) +- [**closed**] MIME breaking with 'class' declaration as it is without 'use strict mode' [#170](https://github.com/broofa/node-mime/issues/170) + +--- + +## v2.0.0 (12/09/2017) +- [**closed**] woff and woff2 [#168](https://github.com/broofa/node-mime/issues/168) + +--- + +## v1.4.0 (28/08/2017) +- [**closed**] support for ac3 voc files [#159](https://github.com/broofa/node-mime/issues/159) +- [**closed**] Help understanding change from application/xml to text/xml [#158](https://github.com/broofa/node-mime/issues/158) +- [**closed**] no longer able to override mimetype [#157](https://github.com/broofa/node-mime/issues/157) +- [**closed**] application/vnd.adobe.photoshop [#147](https://github.com/broofa/node-mime/issues/147) +- [**closed**] Directories should appear as something other than application/octet-stream [#135](https://github.com/broofa/node-mime/issues/135) +- [**closed**] requested features [#131](https://github.com/broofa/node-mime/issues/131) +- [**closed**] Make types.json loading optional? [#129](https://github.com/broofa/node-mime/issues/129) +- [**closed**] Cannot find module './types.json' [#120](https://github.com/broofa/node-mime/issues/120) +- [**V2**] .wav files show up as "audio/x-wav" instead of "audio/x-wave" [#118](https://github.com/broofa/node-mime/issues/118) +- [**closed**] Don't be a pain in the ass for node community [#108](https://github.com/broofa/node-mime/issues/108) +- [**closed**] don't make default_type global [#78](https://github.com/broofa/node-mime/issues/78) +- [**closed**] mime.extension() fails if the content-type is parameterized [#74](https://github.com/broofa/node-mime/issues/74) + +--- + +## v1.3.6 (11/05/2017) +- [**closed**] .md should be text/markdown as of March 2016 [#154](https://github.com/broofa/node-mime/issues/154) +- [**closed**] Error while installing mime [#153](https://github.com/broofa/node-mime/issues/153) +- [**closed**] application/manifest+json [#149](https://github.com/broofa/node-mime/issues/149) +- [**closed**] Dynamic adaptive streaming over HTTP (DASH) file extension typo [#141](https://github.com/broofa/node-mime/issues/141) +- [**closed**] charsets image/png undefined [#140](https://github.com/broofa/node-mime/issues/140) +- [**closed**] Mime-db dependency out of date [#130](https://github.com/broofa/node-mime/issues/130) +- [**closed**] how to support plist? [#126](https://github.com/broofa/node-mime/issues/126) +- [**closed**] how does .types file format look like? [#123](https://github.com/broofa/node-mime/issues/123) +- [**closed**] Feature: support for expanding MIME patterns [#121](https://github.com/broofa/node-mime/issues/121) +- [**closed**] DEBUG_MIME doesn't work [#117](https://github.com/broofa/node-mime/issues/117) + +--- + +## v1.3.4 (06/02/2015) +*No changelog for this release.* + +--- + +## v1.3.3 (06/02/2015) +*No changelog for this release.* + +--- + +## v1.3.1 (05/02/2015) +- [**closed**] Consider adding support for Handlebars .hbs file ending [#111](https://github.com/broofa/node-mime/issues/111) +- [**closed**] Consider adding support for hjson. [#110](https://github.com/broofa/node-mime/issues/110) +- [**closed**] Add mime type for Opus audio files [#94](https://github.com/broofa/node-mime/issues/94) +- [**closed**] Consider making the `Requesting New Types` information more visible [#77](https://github.com/broofa/node-mime/issues/77) + +--- + +## v1.3.0 (05/02/2015) +- [**closed**] Add common name? [#114](https://github.com/broofa/node-mime/issues/114) +- [**closed**] application/x-yaml [#104](https://github.com/broofa/node-mime/issues/104) +- [**closed**] Add mime type for WOFF file format 2.0 [#102](https://github.com/broofa/node-mime/issues/102) +- [**closed**] application/x-msi for .msi [#99](https://github.com/broofa/node-mime/issues/99) +- [**closed**] Add mimetype for gettext translation files [#98](https://github.com/broofa/node-mime/issues/98) +- [**closed**] collaborators [#88](https://github.com/broofa/node-mime/issues/88) +- [**closed**] getting errot in installation of mime module...any1 can help? [#87](https://github.com/broofa/node-mime/issues/87) +- [**closed**] should application/json's charset be utf8? [#86](https://github.com/broofa/node-mime/issues/86) +- [**closed**] Add "license" and "licenses" to package.json [#81](https://github.com/broofa/node-mime/issues/81) +- [**closed**] lookup with extension-less file on Windows returns wrong type [#68](https://github.com/broofa/node-mime/issues/68) + +--- + +## v1.2.11 (15/08/2013) +- [**closed**] Update mime.types [#65](https://github.com/broofa/node-mime/issues/65) +- [**closed**] Publish a new version [#63](https://github.com/broofa/node-mime/issues/63) +- [**closed**] README should state upfront that "application/octet-stream" is default for unknown extension [#55](https://github.com/broofa/node-mime/issues/55) +- [**closed**] Suggested improvement to the charset API [#52](https://github.com/broofa/node-mime/issues/52) + +--- + +## v1.2.10 (25/07/2013) +- [**closed**] Mime type for woff files should be application/font-woff and not application/x-font-woff [#62](https://github.com/broofa/node-mime/issues/62) +- [**closed**] node.types in conflict with mime.types [#51](https://github.com/broofa/node-mime/issues/51) + +--- + +## v1.2.9 (17/01/2013) +- [**closed**] Please update "mime" NPM [#49](https://github.com/broofa/node-mime/issues/49) +- [**closed**] Please add semicolon [#46](https://github.com/broofa/node-mime/issues/46) +- [**closed**] parse full mime types [#43](https://github.com/broofa/node-mime/issues/43) + +--- + +## v1.2.8 (10/01/2013) +- [**closed**] /js directory mime is application/javascript. Is it correct? [#47](https://github.com/broofa/node-mime/issues/47) +- [**closed**] Add mime types for lua code. [#45](https://github.com/broofa/node-mime/issues/45) + +--- + +## v1.2.7 (19/10/2012) +- [**closed**] cannot install 1.2.7 via npm [#41](https://github.com/broofa/node-mime/issues/41) +- [**closed**] Transfer ownership to @broofa [#36](https://github.com/broofa/node-mime/issues/36) +- [**closed**] it's wrong to set charset to UTF-8 for text [#30](https://github.com/broofa/node-mime/issues/30) +- [**closed**] Allow multiple instances of MIME types container [#27](https://github.com/broofa/node-mime/issues/27) + +--- + +## v1.2.5 (16/02/2012) +- [**closed**] When looking up a types, check hasOwnProperty [#23](https://github.com/broofa/node-mime/issues/23) +- [**closed**] Bump version to 1.2.2 [#18](https://github.com/broofa/node-mime/issues/18) +- [**closed**] No license [#16](https://github.com/broofa/node-mime/issues/16) +- [**closed**] Some types missing that are used by html5/css3 [#13](https://github.com/broofa/node-mime/issues/13) +- [**closed**] npm install fails for 1.2.1 [#12](https://github.com/broofa/node-mime/issues/12) +- [**closed**] image/pjpeg + image/x-png [#10](https://github.com/broofa/node-mime/issues/10) +- [**closed**] symlink [#8](https://github.com/broofa/node-mime/issues/8) +- [**closed**] gzip [#2](https://github.com/broofa/node-mime/issues/2) +- [**closed**] ALL CAPS filenames return incorrect mime type [#1](https://github.com/broofa/node-mime/issues/1) diff --git a/node_modules/send/node_modules/mime/LICENSE b/node_modules/send/node_modules/mime/LICENSE new file mode 100644 index 0000000..d3f46f7 --- /dev/null +++ b/node_modules/send/node_modules/mime/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2010 Benjamin Thomas, Robert Kieffer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/send/node_modules/mime/README.md b/node_modules/send/node_modules/mime/README.md new file mode 100644 index 0000000..506fbe5 --- /dev/null +++ b/node_modules/send/node_modules/mime/README.md @@ -0,0 +1,90 @@ +# mime + +Comprehensive MIME type mapping API based on mime-db module. + +## Install + +Install with [npm](http://github.com/isaacs/npm): + + npm install mime + +## Contributing / Testing + + npm run test + +## Command Line + + mime [path_string] + +E.g. + + > mime scripts/jquery.js + application/javascript + +## API - Queries + +### mime.lookup(path) +Get the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g. + +```js +var mime = require('mime'); + +mime.lookup('/path/to/file.txt'); // => 'text/plain' +mime.lookup('file.txt'); // => 'text/plain' +mime.lookup('.TXT'); // => 'text/plain' +mime.lookup('htm'); // => 'text/html' +``` + +### mime.default_type +Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.) + +### mime.extension(type) +Get the default extension for `type` + +```js +mime.extension('text/html'); // => 'html' +mime.extension('application/octet-stream'); // => 'bin' +``` + +### mime.charsets.lookup() + +Map mime-type to charset + +```js +mime.charsets.lookup('text/plain'); // => 'UTF-8' +``` + +(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.) + +## API - Defining Custom Types + +Custom type mappings can be added on a per-project basis via the following APIs. + +### mime.define() + +Add custom mime/extension mappings + +```js +mime.define({ + 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'], + 'application/x-my-type': ['x-mt', 'x-mtt'], + // etc ... +}); + +mime.lookup('x-sft'); // => 'text/x-some-format' +``` + +The first entry in the extensions array is returned by `mime.extension()`. E.g. + +```js +mime.extension('text/x-some-format'); // => 'x-sf' +``` + +### mime.load(filepath) + +Load mappings from an Apache ".types" format file + +```js +mime.load('./my_project.types'); +``` +The .types file format is simple - See the `types` dir for examples. diff --git a/node_modules/send/node_modules/mime/cli.js b/node_modules/send/node_modules/mime/cli.js new file mode 100755 index 0000000..20b1ffe --- /dev/null +++ b/node_modules/send/node_modules/mime/cli.js @@ -0,0 +1,8 @@ +#!/usr/bin/env node + +var mime = require('./mime.js'); +var file = process.argv[2]; +var type = mime.lookup(file); + +process.stdout.write(type + '\n'); + diff --git a/node_modules/send/node_modules/mime/mime.js b/node_modules/send/node_modules/mime/mime.js new file mode 100644 index 0000000..d7efbde --- /dev/null +++ b/node_modules/send/node_modules/mime/mime.js @@ -0,0 +1,108 @@ +var path = require('path'); +var fs = require('fs'); + +function Mime() { + // Map of extension -> mime type + this.types = Object.create(null); + + // Map of mime type -> extension + this.extensions = Object.create(null); +} + +/** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * @param map (Object) type definitions + */ +Mime.prototype.define = function (map) { + for (var type in map) { + var exts = map[type]; + for (var i = 0; i < exts.length; i++) { + if (process.env.DEBUG_MIME && this.types[exts[i]]) { + console.warn((this._loading || "define()").replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + + this.types[exts[i]] + ' to ' + type); + } + + this.types[exts[i]] = type; + } + + // Default extension is the first one we encounter + if (!this.extensions[type]) { + this.extensions[type] = exts[0]; + } + } +}; + +/** + * Load an Apache2-style ".types" file + * + * This may be called multiple times (it's expected). Where files declare + * overlapping types/extensions, the last file wins. + * + * @param file (String) path of file to load. + */ +Mime.prototype.load = function(file) { + this._loading = file; + // Read file and split into lines + var map = {}, + content = fs.readFileSync(file, 'ascii'), + lines = content.split(/[\r\n]+/); + + lines.forEach(function(line) { + // Clean up whitespace/comments, and split into fields + var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); + map[fields.shift()] = fields; + }); + + this.define(map); + + this._loading = null; +}; + +/** + * Lookup a mime type based on extension + */ +Mime.prototype.lookup = function(path, fallback) { + var ext = path.replace(/^.*[\.\/\\]/, '').toLowerCase(); + + return this.types[ext] || fallback || this.default_type; +}; + +/** + * Return file extension associated with a mime type + */ +Mime.prototype.extension = function(mimeType) { + var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); + return this.extensions[type]; +}; + +// Default instance +var mime = new Mime(); + +// Define built-in types +mime.define(require('./types.json')); + +// Default type +mime.default_type = mime.lookup('bin'); + +// +// Additional API specific to the default instance +// + +mime.Mime = Mime; + +/** + * Lookup a charset based on mime type. + */ +mime.charsets = { + lookup: function(mimeType, fallback) { + // Assume text types are utf8 + return (/^text\/|^application\/(javascript|json)/).test(mimeType) ? 'UTF-8' : fallback; + } +}; + +module.exports = mime; diff --git a/node_modules/send/node_modules/mime/package.json b/node_modules/send/node_modules/mime/package.json new file mode 100644 index 0000000..6bd24bc --- /dev/null +++ b/node_modules/send/node_modules/mime/package.json @@ -0,0 +1,44 @@ +{ + "author": { + "name": "Robert Kieffer", + "url": "http://github.com/broofa", + "email": "robert@broofa.com" + }, + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + }, + "contributors": [ + { + "name": "Benjamin Thomas", + "url": "http://github.com/bentomas", + "email": "benjamin@benjaminthomas.org" + } + ], + "description": "A comprehensive library for mime-type mapping", + "license": "MIT", + "dependencies": {}, + "devDependencies": { + "github-release-notes": "0.13.1", + "mime-db": "1.31.0", + "mime-score": "1.1.0" + }, + "scripts": { + "prepare": "node src/build.js", + "changelog": "gren changelog --tags=all --generate --override", + "test": "node src/test.js" + }, + "keywords": [ + "util", + "mime" + ], + "main": "mime.js", + "name": "mime", + "repository": { + "url": "https://github.com/broofa/node-mime", + "type": "git" + }, + "version": "1.6.0" +} diff --git a/node_modules/send/node_modules/mime/src/build.js b/node_modules/send/node_modules/mime/src/build.js new file mode 100755 index 0000000..4928e48 --- /dev/null +++ b/node_modules/send/node_modules/mime/src/build.js @@ -0,0 +1,53 @@ +#!/usr/bin/env node + +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const mimeScore = require('mime-score'); + +let db = require('mime-db'); +let chalk = require('chalk'); + +const STANDARD_FACET_SCORE = 900; + +const byExtension = {}; + +// Clear out any conflict extensions in mime-db +for (let type in db) { + let entry = db[type]; + entry.type = type; + + if (!entry.extensions) continue; + + entry.extensions.forEach(ext => { + if (ext in byExtension) { + const e0 = entry; + const e1 = byExtension[ext]; + e0.pri = mimeScore(e0.type, e0.source); + e1.pri = mimeScore(e1.type, e1.source); + + let drop = e0.pri < e1.pri ? e0 : e1; + let keep = e0.pri >= e1.pri ? e0 : e1; + drop.extensions = drop.extensions.filter(e => e !== ext); + + console.log(`${ext}: Keeping ${chalk.green(keep.type)} (${keep.pri}), dropping ${chalk.red(drop.type)} (${drop.pri})`); + } + byExtension[ext] = entry; + }); +} + +function writeTypesFile(types, path) { + fs.writeFileSync(path, JSON.stringify(types)); +} + +// Segregate into standard and non-standard types based on facet per +// https://tools.ietf.org/html/rfc6838#section-3.1 +const types = {}; + +Object.keys(db).sort().forEach(k => { + const entry = db[k]; + types[entry.type] = entry.extensions; +}); + +writeTypesFile(types, path.join(__dirname, '..', 'types.json')); diff --git a/node_modules/send/node_modules/mime/src/test.js b/node_modules/send/node_modules/mime/src/test.js new file mode 100644 index 0000000..42958a2 --- /dev/null +++ b/node_modules/send/node_modules/mime/src/test.js @@ -0,0 +1,60 @@ +/** + * Usage: node test.js + */ + +var mime = require('../mime'); +var assert = require('assert'); +var path = require('path'); + +// +// Test mime lookups +// + +assert.equal('text/plain', mime.lookup('text.txt')); // normal file +assert.equal('text/plain', mime.lookup('TEXT.TXT')); // uppercase +assert.equal('text/plain', mime.lookup('dir/text.txt')); // dir + file +assert.equal('text/plain', mime.lookup('.text.txt')); // hidden file +assert.equal('text/plain', mime.lookup('.txt')); // nameless +assert.equal('text/plain', mime.lookup('txt')); // extension-only +assert.equal('text/plain', mime.lookup('/txt')); // extension-less () +assert.equal('text/plain', mime.lookup('\\txt')); // Windows, extension-less +assert.equal('application/octet-stream', mime.lookup('text.nope')); // unrecognized +assert.equal('fallback', mime.lookup('text.fallback', 'fallback')); // alternate default + +// +// Test extensions +// + +assert.equal('txt', mime.extension(mime.types.text)); +assert.equal('html', mime.extension(mime.types.htm)); +assert.equal('bin', mime.extension('application/octet-stream')); +assert.equal('bin', mime.extension('application/octet-stream ')); +assert.equal('html', mime.extension(' text/html; charset=UTF-8')); +assert.equal('html', mime.extension('text/html; charset=UTF-8 ')); +assert.equal('html', mime.extension('text/html; charset=UTF-8')); +assert.equal('html', mime.extension('text/html ; charset=UTF-8')); +assert.equal('html', mime.extension('text/html;charset=UTF-8')); +assert.equal('html', mime.extension('text/Html;charset=UTF-8')); +assert.equal(undefined, mime.extension('unrecognized')); + +// +// Test node.types lookups +// + +assert.equal('font/woff', mime.lookup('file.woff')); +assert.equal('application/octet-stream', mime.lookup('file.buffer')); +// TODO: Uncomment once #157 is resolved +// assert.equal('audio/mp4', mime.lookup('file.m4a')); +assert.equal('font/otf', mime.lookup('file.otf')); + +// +// Test charsets +// + +assert.equal('UTF-8', mime.charsets.lookup('text/plain')); +assert.equal('UTF-8', mime.charsets.lookup(mime.types.js)); +assert.equal('UTF-8', mime.charsets.lookup(mime.types.json)); +assert.equal(undefined, mime.charsets.lookup(mime.types.bin)); +assert.equal('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); + +console.log('\nAll tests passed'); diff --git a/node_modules/send/node_modules/mime/types.json b/node_modules/send/node_modules/mime/types.json new file mode 100644 index 0000000..bec78ab --- /dev/null +++ b/node_modules/send/node_modules/mime/types.json @@ -0,0 +1 @@ +{"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomsvc+xml":["atomsvc"],"application/bdoc":["bdoc"],"application/ccxml+xml":["ccxml"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/font-tdpfr":["pfr"],"application/font-woff":[],"application/font-woff2":[],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/prs.cww":["cww"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":[],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":[],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":[],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":[],"application/x-msdownload":["com","bat"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["wmf","emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":[],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"application/xaml+xml":["xaml"],"application/xcap-diff+xml":["xdf"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":[],"audio/adpcm":["adp"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mp3":[],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/wav":["wav"],"audio/wave":[],"audio/webm":["weba"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":[],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":[],"audio/x-wav":[],"audio/xm":["xm"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/apng":["apng"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/g3fax":["g3"],"image/gif":["gif"],"image/ief":["ief"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/ktx":["ktx"],"image/png":["png"],"image/prs.btif":["btif"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/tiff":["tiff","tif"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":[],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/webp":["webp"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":[],"image/x-pcx":["pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/rfc822":["eml","mime"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.vtu":["vtu"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["x3db","x3dbz"],"model/x3d+vrml":["x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/hjson":["hjson"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/prs.lines.tag":["dsc"],"text/richtext":["rtx"],"text/rtf":[],"text/sgml":["sgml","sgm"],"text/slim":["slim","slm"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/vtt":["vtt"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":[],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"text/xml":[],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/jpeg":["jpgv"],"video/jpm":["jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/webm":["webm"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]} \ No newline at end of file diff --git a/node_modules/send/package.json b/node_modules/send/package.json new file mode 100644 index 0000000..acd3fa1 --- /dev/null +++ b/node_modules/send/package.json @@ -0,0 +1,62 @@ +{ + "name": "send", + "description": "Better streaming static file server with Range and conditional-GET support", + "version": "0.19.1", + "author": "TJ Holowaychuk ", + "contributors": [ + "Douglas Christopher Wilson ", + "James Wyatt Cready ", + "Jesús Leganés Combarro " + ], + "license": "MIT", + "repository": "pillarjs/send", + "keywords": [ + "static", + "file", + "server" + ], + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "devDependencies": { + "after": "0.8.2", + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.2", + "nyc": "15.1.0", + "supertest": "6.2.2" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "SECURITY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --check-leaks --reporter spec --bail", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/set-function-length/.eslintrc b/node_modules/set-function-length/.eslintrc new file mode 100644 index 0000000..7cff507 --- /dev/null +++ b/node_modules/set-function-length/.eslintrc @@ -0,0 +1,27 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": "off", + "new-cap": ["error", { + "capIsNewExceptions": [ + "GetIntrinsic" + ], + }], + "no-extra-parens": "off", + }, + + "overrides": [ + { + "files": ["test/**/*.js"], + "rules": { + "id-length": "off", + "max-lines-per-function": "off", + "multiline-comment-style": "off", + "no-empty-function": "off", + }, + }, + ], +} diff --git a/node_modules/set-function-length/.github/FUNDING.yml b/node_modules/set-function-length/.github/FUNDING.yml new file mode 100644 index 0000000..92feb6f --- /dev/null +++ b/node_modules/set-function-length/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/set-function-name +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/set-function-length/.nycrc b/node_modules/set-function-length/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/set-function-length/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/set-function-length/CHANGELOG.md b/node_modules/set-function-length/CHANGELOG.md new file mode 100644 index 0000000..bac439d --- /dev/null +++ b/node_modules/set-function-length/CHANGELOG.md @@ -0,0 +1,70 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.2.2](https://github.com/ljharb/set-function-length/compare/v1.2.1...v1.2.2) - 2024-03-09 + +### Commits + +- [types] use shared config [`027032f`](https://github.com/ljharb/set-function-length/commit/027032fe9cc439644a07248ea6a8d813fcc767cb) +- [actions] remove redundant finisher; use reusable workflow [`1fd4fb1`](https://github.com/ljharb/set-function-length/commit/1fd4fb1c58bd5170f0dcff7e320077c0aa2ffdeb) +- [types] use a handwritten d.ts file instead of emit [`01b9761`](https://github.com/ljharb/set-function-length/commit/01b9761742c95e1118e8c2d153ce2ae43d9731aa) +- [Deps] update `define-data-property`, `get-intrinsic`, `has-property-descriptors` [`bee8eaf`](https://github.com/ljharb/set-function-length/commit/bee8eaf7749f325357ade85cffeaeef679e513d4) +- [Dev Deps] update `call-bind`, `tape` [`5dae579`](https://github.com/ljharb/set-function-length/commit/5dae579fdc3aab91b14ebb58f9c19ee3f509d434) +- [Tests] use `@arethetypeswrong/cli` [`7e22425`](https://github.com/ljharb/set-function-length/commit/7e22425d15957fd3d6da0b6bca4afc0c8d255d2d) + +## [v1.2.1](https://github.com/ljharb/set-function-length/compare/v1.2.0...v1.2.1) - 2024-02-06 + +### Commits + +- [Dev Deps] update `call-bind`, `tape`, `typescript` [`d9a4601`](https://github.com/ljharb/set-function-length/commit/d9a460199c4c1fa37da9ebe055e2c884128f0738) +- [Deps] update `define-data-property`, `get-intrinsic` [`38d39ae`](https://github.com/ljharb/set-function-length/commit/38d39aed13a757ed36211d5b0437b88485090c6b) +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`b4bfe5a`](https://github.com/ljharb/set-function-length/commit/b4bfe5ae0953b906d55b85f867eca5e7f673ebf4) + +## [v1.2.0](https://github.com/ljharb/set-function-length/compare/v1.1.1...v1.2.0) - 2024-01-14 + +### Commits + +- [New] add types [`f6d9088`](https://github.com/ljharb/set-function-length/commit/f6d9088b9283a3112b21c6776e8bef6d1f30558a) +- [Fix] ensure `env` properties are always booleans [`0c42f84`](https://github.com/ljharb/set-function-length/commit/0c42f84979086389b3229e1b4272697fd352275a) +- [Dev Deps] update `aud`, `call-bind`, `npmignore`, `tape` [`2b75f75`](https://github.com/ljharb/set-function-length/commit/2b75f75468093a4bb8ce8ca989b2edd2e80d95d1) +- [Deps] update `get-intrinsic`, `has-property-descriptors` [`19bf0fc`](https://github.com/ljharb/set-function-length/commit/19bf0fc4ffaa5ad425acbfa150516be9f3b6263a) +- [meta] add `sideEffects` flag [`8bb9b78`](https://github.com/ljharb/set-function-length/commit/8bb9b78c11c621123f725c9470222f43466c01d0) + +## [v1.1.1](https://github.com/ljharb/set-function-length/compare/v1.1.0...v1.1.1) - 2023-10-19 + +### Fixed + +- [Fix] move `define-data-property` to runtime deps [`#2`](https://github.com/ljharb/set-function-length/issues/2) + +### Commits + +- [Dev Deps] update `object-inspect`; add missing `call-bind` [`5aecf79`](https://github.com/ljharb/set-function-length/commit/5aecf79e7d6400957a5d9bd9ac20d4528908ca18) + +## [v1.1.0](https://github.com/ljharb/set-function-length/compare/v1.0.1...v1.1.0) - 2023-10-13 + +### Commits + +- [New] add `env` entry point [`475c87a`](https://github.com/ljharb/set-function-length/commit/475c87aa2f59b700aaed589d980624ec596acdcb) +- [Tests] add coverage with `nyc` [`14f0bf8`](https://github.com/ljharb/set-function-length/commit/14f0bf8c145ae60bf14a026420a06bb7be132c36) +- [eslint] fix linting failure [`fb516f9`](https://github.com/ljharb/set-function-length/commit/fb516f93c664057138c53559ef63c8622a093335) +- [Deps] update `define-data-property` [`d727e7c`](https://github.com/ljharb/set-function-length/commit/d727e7c6c9a40d7bf26797694e500ea68741feea) + +## [v1.0.1](https://github.com/ljharb/set-function-length/compare/v1.0.0...v1.0.1) - 2023-10-12 + +### Commits + +- [Refactor] use `get-intrinsic`, since it‘s in the dep graph anyways [`278a954`](https://github.com/ljharb/set-function-length/commit/278a954a06cd849051c569ff7aee56df6798933e) +- [meta] add `exports` [`72acfe5`](https://github.com/ljharb/set-function-length/commit/72acfe5a0310071fb205a72caba5ecbab24336a0) + +## v1.0.0 - 2023-10-12 + +### Commits + +- Initial implementation, tests, readme [`fce14e1`](https://github.com/ljharb/set-function-length/commit/fce14e17586460e4f294405173be72b6ffdf7e5f) +- Initial commit [`ca7ba85`](https://github.com/ljharb/set-function-length/commit/ca7ba857c7c283f9d26e21f14e71cd388f2cb722) +- npm init [`6a7e493`](https://github.com/ljharb/set-function-length/commit/6a7e493927736cebcaf5c1a84e69b8e6b7b744d8) +- Only apps should have lockfiles [`d2bf6c4`](https://github.com/ljharb/set-function-length/commit/d2bf6c43de8a51b02a0aa53e8d62cb50c4a2b0da) diff --git a/node_modules/set-function-length/LICENSE b/node_modules/set-function-length/LICENSE new file mode 100644 index 0000000..0314929 --- /dev/null +++ b/node_modules/set-function-length/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Jordan Harband and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/set-function-length/README.md b/node_modules/set-function-length/README.md new file mode 100644 index 0000000..15e3ac4 --- /dev/null +++ b/node_modules/set-function-length/README.md @@ -0,0 +1,56 @@ +# set-function-length [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Set a function’s length. + +Arguments: + - `fn`: the function + - `length`: the new length. Must be an integer between 0 and 2**32. + - `loose`: Optional. If true, and the length fails to be set, do not throw. Default false. + +Returns `fn`. + +## Usage + +```javascript +var setFunctionLength = require('set-function-length'); +var assert = require('assert'); + +function zero() {} +function one(_) {} +function two(_, __) {} + +assert.equal(zero.length, 0); +assert.equal(one.length, 1); +assert.equal(two.length, 2); + +assert.equal(setFunctionLength(zero, 10), zero); +assert.equal(setFunctionLength(one, 11), one); +assert.equal(setFunctionLength(two, 12), two); + +assert.equal(zero.length, 10); +assert.equal(one.length, 11); +assert.equal(two.length, 12); +``` + +[package-url]: https://npmjs.org/package/set-function-length +[npm-version-svg]: https://versionbadg.es/ljharb/set-function-length.svg +[deps-svg]: https://david-dm.org/ljharb/set-function-length.svg +[deps-url]: https://david-dm.org/ljharb/set-function-length +[dev-deps-svg]: https://david-dm.org/ljharb/set-function-length/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/set-function-length#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/set-function-length.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/set-function-length.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/set-function-length.svg +[downloads-url]: https://npm-stat.com/charts.html?package=set-function-length +[codecov-image]: https://codecov.io/gh/ljharb/set-function-length/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/set-function-length/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/set-function-length +[actions-url]: https://github.com/ljharb/set-function-length/actions diff --git a/node_modules/set-function-length/env.d.ts b/node_modules/set-function-length/env.d.ts new file mode 100644 index 0000000..970ea53 --- /dev/null +++ b/node_modules/set-function-length/env.d.ts @@ -0,0 +1,9 @@ +declare const env: { + __proto__: null, + boundFnsHaveConfigurableLengths: boolean; + boundFnsHaveWritableLengths: boolean; + functionsHaveConfigurableLengths: boolean; + functionsHaveWritableLengths: boolean; +}; + +export = env; \ No newline at end of file diff --git a/node_modules/set-function-length/env.js b/node_modules/set-function-length/env.js new file mode 100644 index 0000000..d9b0a29 --- /dev/null +++ b/node_modules/set-function-length/env.js @@ -0,0 +1,25 @@ +'use strict'; + +var gOPD = require('gopd'); +var bind = require('function-bind'); + +var unbound = gOPD && gOPD(function () {}, 'length'); +// @ts-expect-error ts(2555) TS is overly strict with .call +var bound = gOPD && gOPD(bind.call(function () {}), 'length'); + +var functionsHaveConfigurableLengths = !!(unbound && unbound.configurable); + +var functionsHaveWritableLengths = !!(unbound && unbound.writable); + +var boundFnsHaveConfigurableLengths = !!(bound && bound.configurable); + +var boundFnsHaveWritableLengths = !!(bound && bound.writable); + +/** @type {import('./env')} */ +module.exports = { + __proto__: null, + boundFnsHaveConfigurableLengths: boundFnsHaveConfigurableLengths, + boundFnsHaveWritableLengths: boundFnsHaveWritableLengths, + functionsHaveConfigurableLengths: functionsHaveConfigurableLengths, + functionsHaveWritableLengths: functionsHaveWritableLengths +}; diff --git a/node_modules/set-function-length/index.d.ts b/node_modules/set-function-length/index.d.ts new file mode 100644 index 0000000..0451ecd --- /dev/null +++ b/node_modules/set-function-length/index.d.ts @@ -0,0 +1,7 @@ +declare namespace setFunctionLength { + type Func = (...args: unknown[]) => unknown; +} + +declare function setFunctionLength(fn: T, length: number, loose?: boolean): T; + +export = setFunctionLength; \ No newline at end of file diff --git a/node_modules/set-function-length/index.js b/node_modules/set-function-length/index.js new file mode 100644 index 0000000..14ce74d --- /dev/null +++ b/node_modules/set-function-length/index.js @@ -0,0 +1,42 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var define = require('define-data-property'); +var hasDescriptors = require('has-property-descriptors')(); +var gOPD = require('gopd'); + +var $TypeError = require('es-errors/type'); +var $floor = GetIntrinsic('%Math.floor%'); + +/** @type {import('.')} */ +module.exports = function setFunctionLength(fn, length) { + if (typeof fn !== 'function') { + throw new $TypeError('`fn` is not a function'); + } + if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) { + throw new $TypeError('`length` must be a positive 32-bit integer'); + } + + var loose = arguments.length > 2 && !!arguments[2]; + + var functionLengthIsConfigurable = true; + var functionLengthIsWritable = true; + if ('length' in fn && gOPD) { + var desc = gOPD(fn, 'length'); + if (desc && !desc.configurable) { + functionLengthIsConfigurable = false; + } + if (desc && !desc.writable) { + functionLengthIsWritable = false; + } + } + + if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { + if (hasDescriptors) { + define(/** @type {Parameters[0]} */ (fn), 'length', length, true, true); + } else { + define(/** @type {Parameters[0]} */ (fn), 'length', length); + } + } + return fn; +}; diff --git a/node_modules/set-function-length/package.json b/node_modules/set-function-length/package.json new file mode 100644 index 0000000..f6b8881 --- /dev/null +++ b/node_modules/set-function-length/package.json @@ -0,0 +1,102 @@ +{ + "name": "set-function-length", + "version": "1.2.2", + "description": "Set a function's length property", + "main": "index.js", + "exports": { + ".": "./index.js", + "./env": "./env.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "directories": { + "test": "test" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "tsc": "tsc -p .", + "posttsc": "attw -P", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "npm run tsc", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/set-function-length.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "set", + "function", + "length", + "function.length" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/set-function-length/issues" + }, + "homepage": "https://github.com/ljharb/set-function-length#readme", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.15.1", + "@ljharb/eslint-config": "^21.1.0", + "@ljharb/tsconfig": "^0.1.1", + "@types/call-bind": "^1.0.5", + "@types/define-properties": "^1.1.5", + "@types/es-value-fixtures": "^1.4.4", + "@types/for-each": "^0.3.3", + "@types/function-bind": "^1.1.10", + "@types/gopd": "^1.0.3", + "@types/has-property-descriptors": "^1.0.3", + "@types/object-inspect": "^1.8.4", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "call-bind": "^1.0.7", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.5", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "test" + ] + } +} diff --git a/node_modules/set-function-length/tsconfig.json b/node_modules/set-function-length/tsconfig.json new file mode 100644 index 0000000..d9a6668 --- /dev/null +++ b/node_modules/set-function-length/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/set-function-name/.eslintrc b/node_modules/set-function-name/.eslintrc new file mode 100644 index 0000000..ceed918 --- /dev/null +++ b/node_modules/set-function-name/.eslintrc @@ -0,0 +1,21 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": "off", + "no-extra-parens": "off", + }, + + "overrides": [ + { + "files": ["test/**/*.js"], + "rules": { + "id-length": "off", + "multiline-comment-style": "off", + "no-empty-function": "off", + }, + }, + ], +} diff --git a/node_modules/set-function-name/.github/FUNDING.yml b/node_modules/set-function-name/.github/FUNDING.yml new file mode 100644 index 0000000..92feb6f --- /dev/null +++ b/node_modules/set-function-name/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/set-function-name +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/set-function-name/CHANGELOG.md b/node_modules/set-function-name/CHANGELOG.md new file mode 100644 index 0000000..d3719c3 --- /dev/null +++ b/node_modules/set-function-name/CHANGELOG.md @@ -0,0 +1,48 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v2.0.2](https://github.com/jfsiii/set-function-name/compare/v2.0.1...v2.0.2) - 2024-02-19 + +### Commits + +- [meta] add types [`ae747cd`](https://github.com/jfsiii/set-function-name/commit/ae747cdcf4a986e6974a375be8ec04dd7565f0bd) +- [Dev Deps] update `aud`, `npmignore`, `object-inspect`, `tape` [`01aafcb`](https://github.com/jfsiii/set-function-name/commit/01aafcb82e4df653fcbd666ce4f256c06f70d94e) +- [Deps] update `define-data-property`, `has-property-descriptors` [`0ef6338`](https://github.com/jfsiii/set-function-name/commit/0ef6338fac84f63c2445855778bfd9271ae048cb) +- [Refactor] use `es-errors` [`0b23e87`](https://github.com/jfsiii/set-function-name/commit/0b23e878a16c959bd8b1aa7152d65818dd90578c) + +## [v2.0.1](https://github.com/jfsiii/set-function-name/compare/v2.0.0...v2.0.1) - 2023-09-13 + +### Commits + +- [Fix] move `functions-have-names` to runtime deps [`db2eda8`](https://github.com/jfsiii/set-function-name/commit/db2eda8da4c8aecfad01739000bbd63d04a8e8cf) + +## [v2.0.0](https://github.com/jfsiii/set-function-name/compare/v1.0.0...v2.0.0) - 2023-09-12 + +### Commits + +- [eslint] add `npm run lint` [`23e1fcd`](https://github.com/jfsiii/set-function-name/commit/23e1fcd85b64b864cb8f7e894da78d540e72923a) +- [actions] add reused GHA [`525127e`](https://github.com/jfsiii/set-function-name/commit/525127e08bdb35b0d44f565492456c7d1d5923fc) +- [meta] add `.gitignore` [`aa3abdf`](https://github.com/jfsiii/set-function-name/commit/aa3abdfa6af18adf70281352905dd69ef8b2c66f) +- [Tests] switch tests to use tape; add posttest [`8ad6d30`](https://github.com/jfsiii/set-function-name/commit/8ad6d30c61f78d2f9beec156ba7f1c4c3741c593) +- [readme] add readme [`732c46c`](https://github.com/jfsiii/set-function-name/commit/732c46c05e0fa6843dbc85b3af1e9c9bf22e7bf9) +- [New] add optional `loose` argument [`f5e4771`](https://github.com/jfsiii/set-function-name/commit/f5e4771266c95567d87f6dc2cff94c986bc7e074) +- [meta] relicense package to MIT; fix repo URLs [`13948f8`](https://github.com/jfsiii/set-function-name/commit/13948f8bb4ec8a25b67332d8de232ad0c0dc4e6d) +- [meta] add `auto-changelog` [`7ab201c`](https://github.com/jfsiii/set-function-name/commit/7ab201c0d83d464664cc4588acad0d0f75926679) +- [Breaking] throw if a non-function is provided [`cf6fc8f`](https://github.com/jfsiii/set-function-name/commit/cf6fc8f3396d58aa8c32a83375cbf57d933d7e79) +- [Breaking] drop UMD, just use CJS [`47abfe8`](https://github.com/jfsiii/set-function-name/commit/47abfe89abfaa72f71e0a77a52a5ff2b7377e11a) +- [Refactor] use `define-data-property` and `has-property-descriptors` [`9921c2b`](https://github.com/jfsiii/set-function-name/commit/9921c2b64c571255084aefaa02660314609e8ea0) +- [meta] use `npmignore` to autogenerate an npmignore file [`c5dbe4f`](https://github.com/jfsiii/set-function-name/commit/c5dbe4f4c44298596338432e2ac9946a10c98edd) +- Only apps should have lockfiles [`98bbfa1`](https://github.com/jfsiii/set-function-name/commit/98bbfa145387f318152a6b792bd69aca3c544813) +- [meta] add `safe-publish-latest` [`8916cd8`](https://github.com/jfsiii/set-function-name/commit/8916cd8f5549dceee31f06d35a76e2f9d4933a8b) +- [meta] add `engines` [`2427c8e`](https://github.com/jfsiii/set-function-name/commit/2427c8e2499f378c9ff3d92c7d544c771ca810df) + +## v1.0.0 - 2017-09-14 + +### Commits + +- Initial commit. Including tests. [`f26a1f2`](https://github.com/jfsiii/set-function-name/commit/f26a1f2c69a70dad5049b1daa08eae5f6acd9a1e) +- add .npmignore to ignore test directory [`9cac96f`](https://github.com/jfsiii/set-function-name/commit/9cac96fd9e98f25883be6e727ac32356522a5d69) diff --git a/node_modules/set-function-name/LICENSE b/node_modules/set-function-name/LICENSE new file mode 100644 index 0000000..0314929 --- /dev/null +++ b/node_modules/set-function-name/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Jordan Harband and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/set-function-name/README.md b/node_modules/set-function-name/README.md new file mode 100644 index 0000000..b1612dd --- /dev/null +++ b/node_modules/set-function-name/README.md @@ -0,0 +1,61 @@ +# set-function-name [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Set a function’s name. + +Arguments: + - `fn`: the function + - `name`: the new name + - `loose`: Optional. If true, and the name fails to be set, do not throw. Default false. + +Returns `fn`. + +## Usage + +```javascript +var setFunctionName = require('set-function-name'); +var assert = require('assert'); + +const obj = { + concise() {}, + arrow: () => {}, + named: function named() {}, + anon: function () {}, +}; +assert.equal(obj.concise.name, 'concise'); +assert.equal(obj.arrow.name, 'arrow'); +assert.equal(obj.named.name, 'named'); +assert.equal(obj.anon.name, 'anon'); + +assert.equal(setFunctionName(obj.concise, 'brief'), obj.concise); +assert.equal(setFunctionName(obj.arrow, 'pointy'), obj.arrow); +assert.equal(setFunctionName(obj.named, ''), obj.named); +assert.equal(setFunctionName(obj.anon, 'anonymous'), obj.anon); + +assert.equal(obj.concise.name, 'brief'); +assert.equal(obj.arrow.name, 'pointy'); +assert.equal(obj.named.name, ''); +assert.equal(obj.anon.name, 'anonymous'); +``` + +[package-url]: https://npmjs.org/package/set-function-name +[npm-version-svg]: https://versionbadg.es/ljharb/set-function-name.svg +[deps-svg]: https://david-dm.org/ljharb/set-function-name.svg +[deps-url]: https://david-dm.org/ljharb/set-function-name +[dev-deps-svg]: https://david-dm.org/ljharb/set-function-name/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/set-function-name#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/set-function-name.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/set-function-name.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/set-function-name.svg +[downloads-url]: https://npm-stat.com/charts.html?package=set-function-name +[codecov-image]: https://codecov.io/gh/ljharb/set-function-name/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/set-function-name/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/set-function-name +[actions-url]: https://github.com/ljharb/set-function-name/actions diff --git a/node_modules/set-function-name/index.d.ts b/node_modules/set-function-name/index.d.ts new file mode 100644 index 0000000..a3f6114 --- /dev/null +++ b/node_modules/set-function-name/index.d.ts @@ -0,0 +1,5 @@ +type Func = (...args: unknown[]) => unknown; + +declare function setFunctionName(fn: T, name: string, loose?: boolean): T; + +export = setFunctionName; \ No newline at end of file diff --git a/node_modules/set-function-name/index.js b/node_modules/set-function-name/index.js new file mode 100644 index 0000000..8c18238 --- /dev/null +++ b/node_modules/set-function-name/index.js @@ -0,0 +1,23 @@ +'use strict'; + +var define = require('define-data-property'); +var hasDescriptors = require('has-property-descriptors')(); +var functionsHaveConfigurableNames = require('functions-have-names').functionsHaveConfigurableNames(); + +var $TypeError = require('es-errors/type'); + +/** @type {import('.')} */ +module.exports = function setFunctionName(fn, name) { + if (typeof fn !== 'function') { + throw new $TypeError('`fn` is not a function'); + } + var loose = arguments.length > 2 && !!arguments[2]; + if (!loose || functionsHaveConfigurableNames) { + if (hasDescriptors) { + define(/** @type {Parameters[0]} */ (fn), 'name', name, true, true); + } else { + define(/** @type {Parameters[0]} */ (fn), 'name', name); + } + } + return fn; +}; diff --git a/node_modules/set-function-name/package.json b/node_modules/set-function-name/package.json new file mode 100644 index 0000000..df47de0 --- /dev/null +++ b/node_modules/set-function-name/package.json @@ -0,0 +1,99 @@ +{ + "name": "set-function-name", + "version": "2.0.2", + "description": "Set a function's name property", + "main": "index.js", + "types": "./index.d.ts", + "directories": { + "test": "test" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p .", + "pretest": "npm run lint", + "tests-only": "tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/set-function-name.git" + }, + "keywords": [ + "set", + "assign", + "function", + "name", + "function.name" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/set-function-name/issues" + }, + "homepage": "https://github.com/ljharb/set-function-name#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/call-bind": "^1.0.5", + "@types/define-properties": "^1.1.5", + "@types/es-value-fixtures": "^1.4.4", + "@types/for-each": "^0.3.3", + "@types/function.prototype.name": "^1.1.3", + "@types/functions-have-names": "^1.2.2", + "@types/has-property-descriptors": "^1.0.3", + "@types/make-arrow-function": "^1.2.2", + "@types/make-async-function": "^1.0.2", + "@types/make-async-generator-function": "^1.0.3", + "@types/make-generator-function": "^2.0.3", + "@types/object-inspect": "^1.8.4", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "function.prototype.name": "^1.1.6", + "in-publish": "^2.0.1", + "make-arrow-function": "^1.2.0", + "make-async-function": "^1.0.0", + "make-async-generator-function": "^1.0.0", + "make-generator-function": "^2.0.0", + "npmignore": "^0.3.1", + "object-inspect": "^1.13.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.5", + "typescript": "next" + }, + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "test", + "!*.d.ts", + "!*.d.ts.map" + ] + } +} diff --git a/node_modules/set-function-name/tsconfig.json b/node_modules/set-function-name/tsconfig.json new file mode 100644 index 0000000..6d5dc00 --- /dev/null +++ b/node_modules/set-function-name/tsconfig.json @@ -0,0 +1,59 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "es2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + "typeRoots": ["types"], /* Specify multiple folders that act like './node_modules/@types'. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + + /* Completeness */ + // "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage" + ] +} diff --git a/node_modules/setprototypeof/LICENSE b/node_modules/setprototypeof/LICENSE new file mode 100644 index 0000000..61afa2f --- /dev/null +++ b/node_modules/setprototypeof/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2015, Wes Todd + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/setprototypeof/README.md b/node_modules/setprototypeof/README.md new file mode 100644 index 0000000..791eeff --- /dev/null +++ b/node_modules/setprototypeof/README.md @@ -0,0 +1,31 @@ +# Polyfill for `Object.setPrototypeOf` + +[![NPM Version](https://img.shields.io/npm/v/setprototypeof.svg)](https://npmjs.org/package/setprototypeof) +[![NPM Downloads](https://img.shields.io/npm/dm/setprototypeof.svg)](https://npmjs.org/package/setprototypeof) +[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](https://github.com/standard/standard) + +A simple cross platform implementation to set the prototype of an instianted object. Supports all modern browsers and at least back to IE8. + +## Usage: + +``` +$ npm install --save setprototypeof +``` + +```javascript +var setPrototypeOf = require('setprototypeof') + +var obj = {} +setPrototypeOf(obj, { + foo: function () { + return 'bar' + } +}) +obj.foo() // bar +``` + +TypeScript is also supported: + +```typescript +import setPrototypeOf from 'setprototypeof' +``` diff --git a/node_modules/setprototypeof/index.d.ts b/node_modules/setprototypeof/index.d.ts new file mode 100644 index 0000000..f108ecd --- /dev/null +++ b/node_modules/setprototypeof/index.d.ts @@ -0,0 +1,2 @@ +declare function setPrototypeOf(o: any, proto: object | null): any; +export = setPrototypeOf; diff --git a/node_modules/setprototypeof/index.js b/node_modules/setprototypeof/index.js new file mode 100644 index 0000000..c527055 --- /dev/null +++ b/node_modules/setprototypeof/index.js @@ -0,0 +1,17 @@ +'use strict' +/* eslint no-proto: 0 */ +module.exports = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties) + +function setProtoOf (obj, proto) { + obj.__proto__ = proto + return obj +} + +function mixinProperties (obj, proto) { + for (var prop in proto) { + if (!Object.prototype.hasOwnProperty.call(obj, prop)) { + obj[prop] = proto[prop] + } + } + return obj +} diff --git a/node_modules/setprototypeof/package.json b/node_modules/setprototypeof/package.json new file mode 100644 index 0000000..f20915b --- /dev/null +++ b/node_modules/setprototypeof/package.json @@ -0,0 +1,38 @@ +{ + "name": "setprototypeof", + "version": "1.2.0", + "description": "A small polyfill for Object.setprototypeof", + "main": "index.js", + "typings": "index.d.ts", + "scripts": { + "test": "standard && mocha", + "testallversions": "npm run node010 && npm run node4 && npm run node6 && npm run node9 && npm run node11", + "testversion": "docker run -it --rm -v $(PWD):/usr/src/app -w /usr/src/app node:${NODE_VER} npm install mocha@${MOCHA_VER:-latest} && npm t", + "node010": "NODE_VER=0.10 MOCHA_VER=3 npm run testversion", + "node4": "NODE_VER=4 npm run testversion", + "node6": "NODE_VER=6 npm run testversion", + "node9": "NODE_VER=9 npm run testversion", + "node11": "NODE_VER=11 npm run testversion", + "prepublishOnly": "npm t", + "postpublish": "git push origin && git push origin --tags" + }, + "repository": { + "type": "git", + "url": "https://github.com/wesleytodd/setprototypeof.git" + }, + "keywords": [ + "polyfill", + "object", + "setprototypeof" + ], + "author": "Wes Todd", + "license": "ISC", + "bugs": { + "url": "https://github.com/wesleytodd/setprototypeof/issues" + }, + "homepage": "https://github.com/wesleytodd/setprototypeof", + "devDependencies": { + "mocha": "^6.1.4", + "standard": "^13.0.2" + } +} diff --git a/node_modules/setprototypeof/test/index.js b/node_modules/setprototypeof/test/index.js new file mode 100644 index 0000000..afeb4dd --- /dev/null +++ b/node_modules/setprototypeof/test/index.js @@ -0,0 +1,24 @@ +'use strict' +/* eslint-env mocha */ +/* eslint no-proto: 0 */ +var assert = require('assert') +var setPrototypeOf = require('..') + +describe('setProtoOf(obj, proto)', function () { + it('should merge objects', function () { + var obj = { a: 1, b: 2 } + var proto = { b: 3, c: 4 } + var mergeObj = setPrototypeOf(obj, proto) + + if (Object.getPrototypeOf) { + assert.strictEqual(Object.getPrototypeOf(obj), proto) + } else if ({ __proto__: [] } instanceof Array) { + assert.strictEqual(obj.__proto__, proto) + } else { + assert.strictEqual(obj.a, 1) + assert.strictEqual(obj.b, 2) + assert.strictEqual(obj.c, 4) + } + assert.strictEqual(mergeObj, obj) + }) +}) diff --git a/node_modules/shebang-command/index.js b/node_modules/shebang-command/index.js new file mode 100644 index 0000000..f35db30 --- /dev/null +++ b/node_modules/shebang-command/index.js @@ -0,0 +1,19 @@ +'use strict'; +const shebangRegex = require('shebang-regex'); + +module.exports = (string = '') => { + const match = string.match(shebangRegex); + + if (!match) { + return null; + } + + const [path, argument] = match[0].replace(/#! ?/, '').split(' '); + const binary = path.split('/').pop(); + + if (binary === 'env') { + return argument; + } + + return argument ? `${binary} ${argument}` : binary; +}; diff --git a/node_modules/shebang-command/license b/node_modules/shebang-command/license new file mode 100644 index 0000000..db6bc32 --- /dev/null +++ b/node_modules/shebang-command/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Kevin Mårtensson (github.com/kevva) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/shebang-command/package.json b/node_modules/shebang-command/package.json new file mode 100644 index 0000000..18e3c04 --- /dev/null +++ b/node_modules/shebang-command/package.json @@ -0,0 +1,34 @@ +{ + "name": "shebang-command", + "version": "2.0.0", + "description": "Get the command from a shebang", + "license": "MIT", + "repository": "kevva/shebang-command", + "author": { + "name": "Kevin Mårtensson", + "email": "kevinmartensson@gmail.com", + "url": "github.com/kevva" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "cmd", + "command", + "parse", + "shebang" + ], + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "devDependencies": { + "ava": "^2.3.0", + "xo": "^0.24.0" + } +} diff --git a/node_modules/shebang-command/readme.md b/node_modules/shebang-command/readme.md new file mode 100644 index 0000000..84feb44 --- /dev/null +++ b/node_modules/shebang-command/readme.md @@ -0,0 +1,34 @@ +# shebang-command [![Build Status](https://travis-ci.org/kevva/shebang-command.svg?branch=master)](https://travis-ci.org/kevva/shebang-command) + +> Get the command from a shebang + + +## Install + +``` +$ npm install shebang-command +``` + + +## Usage + +```js +const shebangCommand = require('shebang-command'); + +shebangCommand('#!/usr/bin/env node'); +//=> 'node' + +shebangCommand('#!/bin/bash'); +//=> 'bash' +``` + + +## API + +### shebangCommand(string) + +#### string + +Type: `string` + +String containing a shebang. diff --git a/node_modules/shebang-regex/index.d.ts b/node_modules/shebang-regex/index.d.ts new file mode 100644 index 0000000..61d034b --- /dev/null +++ b/node_modules/shebang-regex/index.d.ts @@ -0,0 +1,22 @@ +/** +Regular expression for matching a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) line. + +@example +``` +import shebangRegex = require('shebang-regex'); + +const string = '#!/usr/bin/env node\nconsole.log("unicorns");'; + +shebangRegex.test(string); +//=> true + +shebangRegex.exec(string)[0]; +//=> '#!/usr/bin/env node' + +shebangRegex.exec(string)[1]; +//=> '/usr/bin/env node' +``` +*/ +declare const shebangRegex: RegExp; + +export = shebangRegex; diff --git a/node_modules/shebang-regex/index.js b/node_modules/shebang-regex/index.js new file mode 100644 index 0000000..63fc4a0 --- /dev/null +++ b/node_modules/shebang-regex/index.js @@ -0,0 +1,2 @@ +'use strict'; +module.exports = /^#!(.*)/; diff --git a/node_modules/shebang-regex/license b/node_modules/shebang-regex/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/shebang-regex/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/shebang-regex/package.json b/node_modules/shebang-regex/package.json new file mode 100644 index 0000000..00ab30f --- /dev/null +++ b/node_modules/shebang-regex/package.json @@ -0,0 +1,35 @@ +{ + "name": "shebang-regex", + "version": "3.0.0", + "description": "Regular expression for matching a shebang line", + "license": "MIT", + "repository": "sindresorhus/shebang-regex", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "regex", + "regexp", + "shebang", + "match", + "test", + "line" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/shebang-regex/readme.md b/node_modules/shebang-regex/readme.md new file mode 100644 index 0000000..5ecf863 --- /dev/null +++ b/node_modules/shebang-regex/readme.md @@ -0,0 +1,33 @@ +# shebang-regex [![Build Status](https://travis-ci.org/sindresorhus/shebang-regex.svg?branch=master)](https://travis-ci.org/sindresorhus/shebang-regex) + +> Regular expression for matching a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) line + + +## Install + +``` +$ npm install shebang-regex +``` + + +## Usage + +```js +const shebangRegex = require('shebang-regex'); + +const string = '#!/usr/bin/env node\nconsole.log("unicorns");'; + +shebangRegex.test(string); +//=> true + +shebangRegex.exec(string)[0]; +//=> '#!/usr/bin/env node' + +shebangRegex.exec(string)[1]; +//=> '/usr/bin/env node' +``` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/shell-quote/.eslintrc b/node_modules/shell-quote/.eslintrc new file mode 100644 index 0000000..9569d51 --- /dev/null +++ b/node_modules/shell-quote/.eslintrc @@ -0,0 +1,30 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "array-bracket-newline": 0, + "complexity": 0, + "eqeqeq": 1, + "func-style": [2, "declaration"], + "max-depth": 0, + "max-lines-per-function": 0, + "max-statements": 0, + "multiline-comment-style": 0, + "no-negated-condition": 1, + "no-param-reassign": 1, + "no-lonely-if": 1, + "no-shadow": 1, + "no-template-curly-in-string": 0, + }, + + "overrides": [ + { + "files": "example/**", + "rules": { + "no-console": 0, + }, + }, + ], +} diff --git a/node_modules/shell-quote/.github/FUNDING.yml b/node_modules/shell-quote/.github/FUNDING.yml new file mode 100644 index 0000000..0b6b6b4 --- /dev/null +++ b/node_modules/shell-quote/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/shell-quote +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/shell-quote/.nycrc b/node_modules/shell-quote/.nycrc new file mode 100644 index 0000000..55c3d29 --- /dev/null +++ b/node_modules/shell-quote/.nycrc @@ -0,0 +1,14 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "example", + "test" + ] +} diff --git a/node_modules/shell-quote/CHANGELOG.md b/node_modules/shell-quote/CHANGELOG.md new file mode 100644 index 0000000..324c195 --- /dev/null +++ b/node_modules/shell-quote/CHANGELOG.md @@ -0,0 +1,279 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.8.1](https://github.com/ljharb/shell-quote/compare/v1.8.0...v1.8.1) - 2023-04-07 + +### Fixed + +- [Fix] `parse`: preserve whitespace in comments [`#6`](https://github.com/ljharb/shell-quote/issues/6) +- [Fix] properly support the `escape` option [`#5`](https://github.com/ljharb/shell-quote/issues/5) + +### Commits + +- [Refactor] `parse`: hoist `getVar` to module level [`b42ac73`](https://github.com/ljharb/shell-quote/commit/b42ac73e39e566cfc355a4addc4bd2df2652556c) +- [Refactor] hoist some vars to module level [`8f0c5c3`](https://github.com/ljharb/shell-quote/commit/8f0c5c3c9df3a10e32f1972636675af6fffef998) +- [Refactor] `parse`: use `slice` over `substr`, cache some values [`fcb2e1a`](https://github.com/ljharb/shell-quote/commit/fcb2e1acd5312a1a1a4e6c66ec688aab383023b5) +- [Refactor] `parse`: a bit of cleanup [`6780ec5`](https://github.com/ljharb/shell-quote/commit/6780ec5194e36e2a696bfbaaf85169682a333321) +- [Refactor] `parse`: tweak the regex to not match nothing [`227d474`](https://github.com/ljharb/shell-quote/commit/227d4742a006e81ec3fde1eee103731a6f7ea920) +- [Tests] increase coverage [`a66de94`](https://github.com/ljharb/shell-quote/commit/a66de943555e49fbb1b657cbe3c5b2c703ae507d) +- [Refactor] `parse`: avoid shadowing a function arg [`1d58679`](https://github.com/ljharb/shell-quote/commit/1d5867907ecbf553556fe6ad790b6d6658aedba3) + +## [v1.8.0](https://github.com/ljharb/shell-quote/compare/v1.7.4...v1.8.0) - 2023-01-30 + +### Commits + +- [New] extract `parse` and `quote` to their own deep imports [`553fdfc`](https://github.com/ljharb/shell-quote/commit/553fdfc32cc41b4c2f77e061b6957703958ca575) +- [Tests] add `nyc` coverage [`fd7ddcd`](https://github.com/ljharb/shell-quote/commit/fd7ddcdd84bfef064c6d9a06b055a95531b26897) +- [New] Add support for here strings (`<<<`) [`9802fb3`](https://github.com/ljharb/shell-quote/commit/9802fb37c7946e18c672b81122520dc296bde271) +- [New] `parse`: Add syntax support for duplicating input file descriptors [`216b198`](https://github.com/ljharb/shell-quote/commit/216b19894f76b14d164c4c5a68f05a51b06336c4) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`85f8e31`](https://github.com/ljharb/shell-quote/commit/85f8e31dd80e1dde63d58204b653e497a53857e6) +- [Tests] add `evalmd` [`c5549fc`](https://github.com/ljharb/shell-quote/commit/c5549fcd82d70046bdc2b1c34184ae9f9d0191f9) +- [actions] update checkout action [`62e9b49`](https://github.com/ljharb/shell-quote/commit/62e9b4958cfa2f9009b7069076612fe33528c1fb) + +## [v1.7.4](https://github.com/ljharb/shell-quote/compare/1.7.3...v1.7.4) - 2022-10-12 + +### Merged + +- Add node_modules to .gitignore [`#48`](https://github.com/ljharb/shell-quote/pull/48) + +### Commits + +- [eslint] fix indentation and whitespace [`aaa9d1f`](https://github.com/ljharb/shell-quote/commit/aaa9d1f65bf3445e6af1efaa4a8f8c13a21aa593) +- [eslint] additional cleanup [`397cb62`](https://github.com/ljharb/shell-quote/commit/397cb628f3d96e4e47763147c0d6074997a13880) +- [meta] add `auto-changelog` [`497fca5`](https://github.com/ljharb/shell-quote/commit/497fca509af3b7d6daaba459bad1f45ac0af3ff1) +- [actions] add reusable workflows [`4763c36`](https://github.com/ljharb/shell-quote/commit/4763c36274c5881a2d141ce9f2b17b7d1d95e8cd) +- [eslint] add eslint [`6ee1437`](https://github.com/ljharb/shell-quote/commit/6ee1437df1b10a79bdf2aaa04f2bacc9f420dc15) +- [readme] rename, add badges [`7eb5134`](https://github.com/ljharb/shell-quote/commit/7eb513483d931602452ec572ed456714148acd2b) +- [meta] update URLs [`67381b6`](https://github.com/ljharb/shell-quote/commit/67381b61fa95e57819333463f491428747893186) +- [meta] create FUNDING.yml; add `funding` in package.json [`8641572`](https://github.com/ljharb/shell-quote/commit/86415722d875578adf1f95f9e649ba42c805bc32) +- [meta] use `npmignore` to autogenerate an npmignore file [`2e2007a`](https://github.com/ljharb/shell-quote/commit/2e2007a393f90bf079fc556a921120b3508c4fc3) +- Only apps should have lockfiles [`f97411e`](https://github.com/ljharb/shell-quote/commit/f97411ef4d2f183200fc8a28beca9faf9b08a640) +- [Dev Deps] update `tape` [`051f608`](https://github.com/ljharb/shell-quote/commit/051f60857ad5035280208abdc348bf5ba42a6254) +- [meta] add `safe-publish-latest` [`18cadf9`](https://github.com/ljharb/shell-quote/commit/18cadf95357392fcd78ea8619956fd41eed62649) +- [Tests] add `aud` in `posttest` [`dc1cc12`](https://github.com/ljharb/shell-quote/commit/dc1cc12b956ccd93d58aaaad263bee7d50576d27) + + + +## 1.7.3 +* Fix a security issue where the regex for windows drive letters allowed some shell meta-characters +to escape the quoting rules. (CVE-2021-42740) + +## 1.7.2 +* Fix a regression introduced in 1.6.3. This reverts the Windows path quoting fix. ([144e1c2](https://github.com/ljharb/shell-quote/commit/144e1c20cd57549a414c827fb3032e60b7b8721c)) + +## 1.7.1 +* Fix `$` being removed when not part of an environment variable name. ([@Adman](https://github.com/Admin) in [#32](https://github.com/ljharb/shell-quote/pull/32)) + +## 1.7.0 +* Add support for parsing `>>` and `>&` redirection operators. ([@forivall](https://github.com/forivall) in [#16](https://github.com/ljharb/shell-quote/pull/16)) +* Add support for parsing `<(` process substitution operator. ([@cuonglm](https://github.com/cuonglm) in [#15](https://github.com/ljharb/shell-quote/pull/15)) + +## 1.6.3 +* Fix Windows path quoting problems. ([@dy](https://github.com/dy) in [#34](https://github.com/ljharb/shell-quote/pull/34)) + +## [v1.6.2](https://github.com/ljharb/shell-quote/compare/1.6.1...v1.6.2) - 2019-08-13 + +### Merged + +- Use native JSON and Array methods [`#21`](https://github.com/ljharb/shell-quote/pull/21) + +### Commits + +- fix whitespace [`72fb5a8`](https://github.com/ljharb/shell-quote/commit/72fb5a8ce29b4f67f28302af33c217b58f92e260) +- Disable package-lock.json [`d450577`](https://github.com/ljharb/shell-quote/commit/d4505770b2a4251af2da8e177385c5e0456a83b6) + +## [1.6.1](https://github.com/ljharb/shell-quote/compare/1.6.0...1.6.1) - 2016-06-17 + +### Commits + +- Fix some more escaping for .quote() [`ace52f4`](https://github.com/ljharb/shell-quote/commit/ace52f4c8717b370b301a3db3a4727db26e309ad) +- Fix escaping for greater than and less than [`70e9eb2`](https://github.com/ljharb/shell-quote/commit/70e9eb2a854eb56a3dfa255be12610a722bbe080) + +## [1.6.0](https://github.com/ljharb/shell-quote/compare/1.5.0...1.6.0) - 2016-04-23 + +### Commits + +- add comment parsing feature [`b8b5c31`](https://github.com/ljharb/shell-quote/commit/b8b5c31c16a15aa4ab26c8f23d362a24b9fa57c4) + +## [1.5.0](https://github.com/ljharb/shell-quote/compare/1.4.3...1.5.0) - 2016-03-16 + +### Commits + +- add escape option to .parse [`4d400e7`](https://github.com/ljharb/shell-quote/commit/4d400e773be448c320b6dc9b2eb1323d7a3461ca) + +## [1.4.3](https://github.com/ljharb/shell-quote/compare/1.4.2...1.4.3) - 2015-03-07 + +### Commits + +- Fix quote() with special chars [`811b5a0`](https://github.com/ljharb/shell-quote/commit/811b5a0aff79f347db245edcf88750977c111844) + +## [1.4.2](https://github.com/ljharb/shell-quote/compare/1.4.1...1.4.2) - 2014-07-20 + +### Commits + +- Handle non-strings when quoting [`d435827`](https://github.com/ljharb/shell-quote/commit/d43582741c5599807249c28722487aa86bb16f06) +- falseys ok [`22dbd94`](https://github.com/ljharb/shell-quote/commit/22dbd9492c372038d439d6ec08c6288ca5fa3c10) +- all the falseys test [`c99dca5`](https://github.com/ljharb/shell-quote/commit/c99dca59dca64743877a0411d299ce669f0a2d1d) + +## [1.4.1](https://github.com/ljharb/shell-quote/compare/1.4.0...1.4.1) - 2013-12-24 + +### Commits + +- es5 shims [`00dc6ab`](https://github.com/ljharb/shell-quote/commit/00dc6abfdd2f3ff2908616dbe7b6584bbf1b0e24) +- separate shim file to get the coverage up [`e29a216`](https://github.com/ljharb/shell-quote/commit/e29a2167319913af3f26603bc33938bb9be1d74d) +- use array-{filter,map,reduce} [`97a2fc9`](https://github.com/ljharb/shell-quote/commit/97a2fc9c92917343a33662b3705860e4f2044730) +- add testling badge [`44c98b1`](https://github.com/ljharb/shell-quote/commit/44c98b1e341d348ce9b5b4d78bb4d26345e868ea) +- upgrade tape [`3fc22d3`](https://github.com/ljharb/shell-quote/commit/3fc22d3d38592e6fc3b3308cc73a282d641bad34) + +## [1.4.0](https://github.com/ljharb/shell-quote/compare/1.3.3...1.4.0) - 2013-10-17 + +### Merged + +- Add MIT LICENSE file [`#6`](https://github.com/ljharb/shell-quote/pull/6) + +### Commits + +- Rewrite parser as a character based scanner [`c7ca9a2`](https://github.com/ljharb/shell-quote/commit/c7ca9a200350c02fb86c4222b63f15b54a0a0226) +- Add tests for glob patterns [`3418892`](https://github.com/ljharb/shell-quote/commit/3418892031b126197302eb57cc92a729b740fac6) +- Update algo description [`e1442cf`](https://github.com/ljharb/shell-quote/commit/e1442cfe0521497b59a8204eb1e4d6c4202d42b9) +- Fix test case for backslash in double quotes [`89bc550`](https://github.com/ljharb/shell-quote/commit/89bc5500711643e87fe93dd1bde0e8745c34d733) +- Add failing tests for crazy quoting tricks [`58a5e48`](https://github.com/ljharb/shell-quote/commit/58a5e4800a62fdc3e980feae1e6c6b15c812f0cb) + +## [1.3.3](https://github.com/ljharb/shell-quote/compare/1.3.2...1.3.3) - 2013-06-24 + +### Commits + +- failing set test with an env cb [`9fb2096`](https://github.com/ljharb/shell-quote/commit/9fb20968b407c590745a982d2a562960e952142d) +- remove the broken special case [`f9a0ee5`](https://github.com/ljharb/shell-quote/commit/f9a0ee574f9d5e5d5b382f55da960c23eb7d44c5) + +## [1.3.2](https://github.com/ljharb/shell-quote/compare/1.3.1...1.3.2) - 2013-06-24 + +### Commits + +- tests for setting env vars [`f44b039`](https://github.com/ljharb/shell-quote/commit/f44b03906c60598470676edcabea79c4f7488407) +- fixed the parse test, broke the op tests [`74d6686`](https://github.com/ljharb/shell-quote/commit/74d66863615a60fcb222d2279991cff3a89ff015) +- factored out single and double quote regex [`de9e0a5`](https://github.com/ljharb/shell-quote/commit/de9e0a5081156e5483b5df24878c7414f90ec67e) +- updated set env test, already passes [`7d5636b`](https://github.com/ljharb/shell-quote/commit/7d5636bec5e76ff542712e07643b09c597d20b21) +- ops fixed [`2b4e1b1`](https://github.com/ljharb/shell-quote/commit/2b4e1b1fb63519456c7850d365e1ffe5fa5972b2) +- passing all tests [`44177e3`](https://github.com/ljharb/shell-quote/commit/44177e3dcbd96dfa331483eba0abbfb0291c130f) +- backreferences in negated capture groups don't actually work [`e189d9d`](https://github.com/ljharb/shell-quote/commit/e189d9d5910c6ecc7d564309ca9e110062f9589e) +- another crazy ridiculous passing parse test [`d1beb6b`](https://github.com/ljharb/shell-quote/commit/d1beb6b32ec7ad8752b305834a21c800cae74a95) +- failing test for quoted whitespace and nested quotes [`9a4c11c`](https://github.com/ljharb/shell-quote/commit/9a4c11cba0f61762aaa7887591d78fe7e965cf65) +- failing test for quotes embedded inside barewords [`d997384`](https://github.com/ljharb/shell-quote/commit/d997384018ce107ab8e12aa5b8d8359c2f77128b) + +## [1.3.1](https://github.com/ljharb/shell-quote/compare/1.3.0...1.3.1) - 2013-05-13 + +### Commits + +- pass objects through [`f9c0514`](https://github.com/ljharb/shell-quote/commit/f9c0514abbdf8ba16fafb68736863d14b39015ef) + +## [1.3.0](https://github.com/ljharb/shell-quote/compare/1.2.0...1.3.0) - 2013-05-13 + +### Commits + +- hacky tokenizer is much simpler [`7e91b18`](https://github.com/ljharb/shell-quote/commit/7e91b18d1cf3fffd6a9c5f69d785f200c0c81b66) +- nearly passing with a clunky state env parser, array issues [`d6d6416`](https://github.com/ljharb/shell-quote/commit/d6d64160f2fc8a23018410ffe84ab7f1b0c4fa02) +- test for functional env expansion [`666395f`](https://github.com/ljharb/shell-quote/commit/666395f9f195241c6077f242dc4f2851bed95f8d) +- upgrade travis versions, tape [`f6f8bd6`](https://github.com/ljharb/shell-quote/commit/f6f8bd6026375d44d40c7f2e1fead43d006be211) +- 1.3.0, document env() lookups [`041c5da`](https://github.com/ljharb/shell-quote/commit/041c5da88800b4e15f0ed023049050b11b623a23) +- first half of functional env() works [`7a0cf79`](https://github.com/ljharb/shell-quote/commit/7a0cf79987fbdcc00d8f36c6dc164d22db963d23) +- env() objects even work inside quote strings [`16139f5`](https://github.com/ljharb/shell-quote/commit/16139f52bf7a2beb7e1ca9b61b93a9ea598b0f1a) +- another check just to make sure env() works [`914a1a9`](https://github.com/ljharb/shell-quote/commit/914a1a9ec55cd76bedfed4086c35866733128036) + +## [1.2.0](https://github.com/ljharb/shell-quote/compare/1.1.0...1.2.0) - 2013-05-13 + +### Commits + +- failing test for special shell parameter env vars [`728862a`](https://github.com/ljharb/shell-quote/commit/728862a6ff246754083da5cf22322caf914ae990) +- add the special vars to the replace regex but the chunker breaks on them [`d1ff82a`](https://github.com/ljharb/shell-quote/commit/d1ff82a07c44cb53ab909b61833296f38257eabd) +- fixed the env test, everything is fine [`a45897f`](https://github.com/ljharb/shell-quote/commit/a45897f53ba184a77bc762c63777b95590a83962) + +## [1.1.0](https://github.com/ljharb/shell-quote/compare/1.0.0...1.1.0) - 2013-05-13 + +### Commits + +- quote all ops objects [`ac7be63`](https://github.com/ljharb/shell-quote/commit/ac7be63574e1da48bc6f495aee363d31863222c3) +- test for parsed ops objects in quote() [`59fb71b`](https://github.com/ljharb/shell-quote/commit/59fb71b39c53b83306d015bec62fc93667745f75) +- another test for op object quoting [`5819a31`](https://github.com/ljharb/shell-quote/commit/5819a31a19c34967dcb7bd1719250ed2aa480583) + +## [1.0.0](https://github.com/ljharb/shell-quote/compare/0.1.1...1.0.0) - 2013-05-13 + +### Commits + +- document ops, op example [`a6381e6`](https://github.com/ljharb/shell-quote/commit/a6381e612361148a8433c6ec4891aabc4649cb40) +- some more passing double-char op tests [`fbc6e5c`](https://github.com/ljharb/shell-quote/commit/fbc6e5c40858ef4ea4d69651ac8fdf6c0c780eed) +- failing test for | and & ops [`d817736`](https://github.com/ljharb/shell-quote/commit/d81773643cbc2e25576884d606165dc87e8bbfac) +- labeled regex states [`8c008b2`](https://github.com/ljharb/shell-quote/commit/8c008b223e6174d6bec098251527053e5cc1f30c) +- refactored the chunker regex into a string [`0331c7f`](https://github.com/ljharb/shell-quote/commit/0331c7f63077fda116b3c73540b71880538a4391) +- simple failing double-char op test [`e51fa90`](https://github.com/ljharb/shell-quote/commit/e51fa90f854063a408e8c1645b385c1ed42c72c6) +- failing expanded single-op tests for ; and () [`710bb24`](https://github.com/ljharb/shell-quote/commit/710bb243f23d4a55158688b71cb56b67f66ea99f) +- now passing all the single-char op tests [`e3e9ac1`](https://github.com/ljharb/shell-quote/commit/e3e9ac17ef02300bad7f4faefee5c7a993b3bc97) +- using the control ops directly from the docs [`f535987`](https://github.com/ljharb/shell-quote/commit/f53598732ba606c7bca66fd7d55d809544c452cf) +- first part of op parsing works [`e6f9199`](https://github.com/ljharb/shell-quote/commit/e6f91991fe437eae6b7e4f571843b3d48c746aeb) +- failing redirect tests [`cb94c10`](https://github.com/ljharb/shell-quote/commit/cb94c105a4e32fac2d356b956f53aff999ae88e8) +- another double-char op test just to be sure [`5cf1bf2`](https://github.com/ljharb/shell-quote/commit/5cf1bf29e3324a6cc1e40c01c4529b28ca0b47a5) +- 1.0.0 for ops [`17a40ed`](https://github.com/ljharb/shell-quote/commit/17a40edb3cd7a0f1c44be2be5ddd412c8ca2b7ca) +- adding redirect <> ops to CONTROL makes the tests pass [`48b1eb9`](https://github.com/ljharb/shell-quote/commit/48b1eb97cfa306659de66bd29615051a3644b9ce) +- double-char op test now passing [`3998b0f`](https://github.com/ljharb/shell-quote/commit/3998b0f9ecb32883f8eb3be31110a84d276ac764) +- using the meta chars directly from the docs [`b009ef6`](https://github.com/ljharb/shell-quote/commit/b009ef6d04eb1cc57d66cf3670d24e03fa0fc6bd) +- the spec says tabs are also allowed [`2adb373`](https://github.com/ljharb/shell-quote/commit/2adb37366bdfae198ce61e4658e513d3e0bc98fa) +- op test completely passing [`20a0147`](https://github.com/ljharb/shell-quote/commit/20a01475741d9fba801bbd2b0c1a5f215dc9cec4) + +## [0.1.1](https://github.com/ljharb/shell-quote/compare/0.1.0...0.1.1) - 2013-04-17 + +### Commits + +- Return empty list when parsing an empty (or whitespace-only) string [`1475717`](https://github.com/ljharb/shell-quote/commit/14757177ead209f5ae3c9d4a3020fba9f522725f) + +## [0.1.0](https://github.com/ljharb/shell-quote/compare/0.0.1...0.1.0) - 2013-04-14 + +### Commits + +- externalize the regex declaration [`37d6058`](https://github.com/ljharb/shell-quote/commit/37d60580a4a4656ff836c4a2ecdd7282705ffd27) +- modernize the readme [`24106f5`](https://github.com/ljharb/shell-quote/commit/24106f5c81ab83bddb2bf735cad60e99e1494dcf) +- factor out interpolation [`1b21b01`](https://github.com/ljharb/shell-quote/commit/1b21b018e01392d2c74e53136f8fa0ca838d7643) +- half the env tests are working with basic interpolation [`5891471`](https://github.com/ljharb/shell-quote/commit/589147176be93834bad7fcee83bd255e35c14adc) +- env parse example [`5757c42`](https://github.com/ljharb/shell-quote/commit/5757c4256a4cbaeaabd3d8cd91c7e19109329067) +- failing tests for unimplemented env interpolation [`590534a`](https://github.com/ljharb/shell-quote/commit/590534ae8eced91974a4be8f2b6bc7dcb53e3211) +- denormalize the interpolate logic to make room for special cases [`c669d2e`](https://github.com/ljharb/shell-quote/commit/c669d2e8b84e0eb0dde1798eae7c37a21dc5b7a1) +- cleaner implementation recursing on the double quote case [`adae66f`](https://github.com/ljharb/shell-quote/commit/adae66f47cf11bb7a686c98059436f496d881955) +- one test was wrong, checking for pre escapes [`42b5f83`](https://github.com/ljharb/shell-quote/commit/42b5f8355196d5f2a2c40178576a5d37167e8cb2) +- finally passing all the tests [`efa4084`](https://github.com/ljharb/shell-quote/commit/efa408481db33993fce2a1dd3c15ffac0203fe4c) +- one more test passing with quote recursion [`e9537b9`](https://github.com/ljharb/shell-quote/commit/e9537b943d89535b38c0777c210b5aa9780349b2) +- use tape everywhere [`ed0c1c6`](https://github.com/ljharb/shell-quote/commit/ed0c1c6ae383998874002ae9aa452505c266d630) +- some extra metacharacter tests just to be sure [`a6782ae`](https://github.com/ljharb/shell-quote/commit/a6782aeb931221a459f9cebc371c2311ad680992) +- minor fix to an env test [`601b340`](https://github.com/ljharb/shell-quote/commit/601b3406e7012da97771b0ed538288ddb12d9af8) +- document parse env [`cc0efba`](https://github.com/ljharb/shell-quote/commit/cc0efba0bce75aaab1ead72e81470154a71ec525) +- better parse recursion to capture the containing quotes [`8467961`](https://github.com/ljharb/shell-quote/commit/84679611fd5843777d3d94f157a7b6efe11097ca) +- now just 2 tests failing with a subtle regex reordering [`5448a02`](https://github.com/ljharb/shell-quote/commit/5448a02d356722ec8ef57db2e075e10566e2dcdb) +- pass another test by using "" as the undefined [`46e6cf4`](https://github.com/ljharb/shell-quote/commit/46e6cf4b974e1cec0601e81a0dc2820dc849f775) +- fixed a failing env test [`17d1fda`](https://github.com/ljharb/shell-quote/commit/17d1fdac759e7a94ffc6edc26af27769d30e53bb) +- actually the test was wrong, module works fine [`9d7b727`](https://github.com/ljharb/shell-quote/commit/9d7b727f2911692cffe03e7792b5defad3dd75d2) +- another test to be even more sure [`5afd47b`](https://github.com/ljharb/shell-quote/commit/5afd47ba563d4c1bb7966695e100f63da4b65915) +- failing test for: echo "foo = \"foo\"" [`8dbb280`](https://github.com/ljharb/shell-quote/commit/8dbb2803136a2f7643e7e66b2d6b95f9adfbfd41) + +## [0.0.1](https://github.com/ljharb/shell-quote/compare/0.0.0...0.0.1) - 2012-05-18 + +### Commits + +- fixed unescaped metachars and bump [`5ce339f`](https://github.com/ljharb/shell-quote/commit/5ce339feeaf971a5172fe58faa3ac5f90bdfe8b5) +- failing test for unescaped metachars [`a315125`](https://github.com/ljharb/shell-quote/commit/a315125a0742b01799c89469efd20821540694f6) +- fix for escaped spaces [`669b616`](https://github.com/ljharb/shell-quote/commit/669b61610aad3e6f47e8c043e1635dcc4b5ce375) +- failing test for escaped space [`c6ff3dc`](https://github.com/ljharb/shell-quote/commit/c6ff3dc6811816a667e55a69ec09bffa52f5ee0a) + +## 0.0.0 - 2012-05-18 + +### Commits + +- readme with examples [`6373c0f`](https://github.com/ljharb/shell-quote/commit/6373c0f56de87702a61063ffae354e2bb989de91) +- package.json [`bc27efa`](https://github.com/ljharb/shell-quote/commit/bc27efa033709ede8483bb6ec0f182dcb2b87061) +- passing the parse test [`69c0f85`](https://github.com/ljharb/shell-quote/commit/69c0f8529825d3fdc700e81d32b75378cef47994) +- crazy initial thing [`d6469c9`](https://github.com/ljharb/shell-quote/commit/d6469c95adf0172adc65c4adab04910486368ee7) +- passing quote tests [`e1d6695`](https://github.com/ljharb/shell-quote/commit/e1d669503f0f159068deb45f14ba3a4bf77e90f0) +- failing parse test [`980aa58`](https://github.com/ljharb/shell-quote/commit/980aa585937d049b152b5e7b08c1e068faaaf378) +- using travis [`1c72261`](https://github.com/ljharb/shell-quote/commit/1c72261f45002744fac3fecec3f0395924d66717) +- expand more escape sequences in parse() [`8b2224c`](https://github.com/ljharb/shell-quote/commit/8b2224c465ef70d2320985c57dc0b8ee1c0a3664) diff --git a/node_modules/shell-quote/LICENSE b/node_modules/shell-quote/LICENSE new file mode 100644 index 0000000..3d59c73 --- /dev/null +++ b/node_modules/shell-quote/LICENSE @@ -0,0 +1,24 @@ +The MIT License + +Copyright (c) 2013 James Halliday (mail@substack.net) + +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software and +associated documentation files (the "Software"), to +deal in the Software without restriction, including +without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom +the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR +ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/shell-quote/README.md b/node_modules/shell-quote/README.md new file mode 100644 index 0000000..6b545c5 --- /dev/null +++ b/node_modules/shell-quote/README.md @@ -0,0 +1,161 @@ +# shell-quote [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Parse and quote shell commands. + +# example + +## quote + +``` js +var quote = require('shell-quote/quote'); +var s = quote([ 'a', 'b c d', '$f', '"g"' ]); +console.log(s); +``` + +output + +``` +a 'b c d' \$f '"g"' +``` + +## parse + +``` js +var parse = require('shell-quote/parse'); +var xs = parse('a "b c" \\$def \'it\\\'s great\''); +console.dir(xs); +``` + +output + +``` +[ 'a', 'b c', '\\$def', 'it\'s great' ] +``` + +## parse with an environment variable + +``` js +var parse = require('shell-quote/parse'); +var xs = parse('beep --boop="$PWD"', { PWD: '/home/robot' }); +console.dir(xs); +``` + +output + +``` +[ 'beep', '--boop=/home/robot' ] +``` + +## parse with custom escape character + +``` js +var parse = require('shell-quote/parse'); +var xs = parse('beep ^--boop="$PWD"', { PWD: '/home/robot' }, { escape: '^' }); +console.dir(xs); +``` + +output + +``` +[ 'beep --boop=/home/robot' ] +``` + +## parsing shell operators + +``` js +var parse = require('shell-quote/parse'); +var xs = parse('beep || boop > /byte'); +console.dir(xs); +``` + +output: + +``` +[ 'beep', { op: '||' }, 'boop', { op: '>' }, '/byte' ] +``` + +## parsing shell comment + +``` js +var parse = require('shell-quote/parse'); +var xs = parse('beep > boop # > kaboom'); +console.dir(xs); +``` + +output: + +``` +[ 'beep', { op: '>' }, 'boop', { comment: '> kaboom' } ] +``` + +# methods + +``` js +var quote = require('shell-quote/quote'); +var parse = require('shell-quote/parse'); +``` + +## quote(args) + +Return a quoted string for the array `args` suitable for using in shell +commands. + +## parse(cmd, env={}) + +Return an array of arguments from the quoted string `cmd`. + +Interpolate embedded bash-style `$VARNAME` and `${VARNAME}` variables with +the `env` object which like bash will replace undefined variables with `""`. + +`env` is usually an object but it can also be a function to perform lookups. +When `env(key)` returns a string, its result will be output just like `env[key]` +would. When `env(key)` returns an object, it will be inserted into the result +array like the operator objects. + +When a bash operator is encountered, the element in the array with be an object +with an `"op"` key set to the operator string. For example: + +``` +'beep || boop > /byte' +``` + +parses as: + +``` +[ 'beep', { op: '||' }, 'boop', { op: '>' }, '/byte' ] +``` + +# install + +With [npm](http://npmjs.org) do: + +``` +npm install shell-quote +``` + +# license + +MIT + +[package-url]: https://npmjs.org/package/shell-quote +[npm-version-svg]: https://versionbadg.es/ljharb/shell-quote.svg +[deps-svg]: https://david-dm.org/ljharb/shell-quote.svg +[deps-url]: https://david-dm.org/ljharb/shell-quote +[dev-deps-svg]: https://david-dm.org/ljharb/shell-quote/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/shell-quote#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/shell-quote.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/shell-quote.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/shell-quote.svg +[downloads-url]: https://npm-stat.com/charts.html?package=shell-quote +[codecov-image]: https://codecov.io/gh/ljharb/shell-quote/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/shell-quote/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/shell-quote +[actions-url]: https://github.com/ljharb/shell-quote/actions diff --git a/node_modules/shell-quote/example/env.js b/node_modules/shell-quote/example/env.js new file mode 100644 index 0000000..1493afc --- /dev/null +++ b/node_modules/shell-quote/example/env.js @@ -0,0 +1,5 @@ +'use strict'; + +var parse = require('../').parse; +var xs = parse('beep --boop="$PWD"', { PWD: '/home/robot' }); +console.dir(xs); diff --git a/node_modules/shell-quote/example/op.js b/node_modules/shell-quote/example/op.js new file mode 100644 index 0000000..82ebf65 --- /dev/null +++ b/node_modules/shell-quote/example/op.js @@ -0,0 +1,5 @@ +'use strict'; + +var parse = require('../').parse; +var xs = parse('beep || boop > /byte'); +console.dir(xs); diff --git a/node_modules/shell-quote/example/parse.js b/node_modules/shell-quote/example/parse.js new file mode 100644 index 0000000..36e6758 --- /dev/null +++ b/node_modules/shell-quote/example/parse.js @@ -0,0 +1,5 @@ +'use strict'; + +var parse = require('../').parse; +var xs = parse('a "b c" \\$def \'it\\\'s great\''); +console.dir(xs); diff --git a/node_modules/shell-quote/example/quote.js b/node_modules/shell-quote/example/quote.js new file mode 100644 index 0000000..91c3d20 --- /dev/null +++ b/node_modules/shell-quote/example/quote.js @@ -0,0 +1,5 @@ +'use strict'; + +var quote = require('../').quote; +var s = quote(['a', 'b c d', '$f', '"g"']); +console.log(s); diff --git a/node_modules/shell-quote/index.js b/node_modules/shell-quote/index.js new file mode 100644 index 0000000..28fb42d --- /dev/null +++ b/node_modules/shell-quote/index.js @@ -0,0 +1,4 @@ +'use strict'; + +exports.quote = require('./quote'); +exports.parse = require('./parse'); diff --git a/node_modules/shell-quote/package.json b/node_modules/shell-quote/package.json new file mode 100644 index 0000000..641127e --- /dev/null +++ b/node_modules/shell-quote/package.json @@ -0,0 +1,66 @@ +{ + "name": "shell-quote", + "description": "quote and parse shell commands", + "version": "1.8.1", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "bugs": "https://github.com/ljharb/shell-quote/issues", + "devDependencies": { + "@ljharb/eslint-config": "^21.0.1", + "aud": "^2.0.2", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.3" + }, + "homepage": "https://github.com/ljharb/shell-quote", + "keywords": [ + "command", + "parse", + "quote", + "shell" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "http://github.com/ljharb/shell-quote.git" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true, + "startingVersion": "1.7.4" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/shell-quote/parse.js b/node_modules/shell-quote/parse.js new file mode 100644 index 0000000..71d2eea --- /dev/null +++ b/node_modules/shell-quote/parse.js @@ -0,0 +1,226 @@ +'use strict'; + +// '<(' is process substitution operator and +// can be parsed the same as control operator +var CONTROL = '(?:' + [ + '\\|\\|', + '\\&\\&', + ';;', + '\\|\\&', + '\\<\\(', + '\\<\\<\\<', + '>>', + '>\\&', + '<\\&', + '[&;()|<>]' +].join('|') + ')'; +var controlRE = new RegExp('^' + CONTROL + '$'); +var META = '|&;()<> \\t'; +var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"'; +var DOUBLE_QUOTE = '\'((\\\\\'|[^\'])*?)\''; +var hash = /^#$/; + +var SQ = "'"; +var DQ = '"'; +var DS = '$'; + +var TOKEN = ''; +var mult = 0x100000000; // Math.pow(16, 8); +for (var i = 0; i < 4; i++) { + TOKEN += (mult * Math.random()).toString(16); +} +var startsWithToken = new RegExp('^' + TOKEN); + +function matchAll(s, r) { + var origIndex = r.lastIndex; + + var matches = []; + var matchObj; + + while ((matchObj = r.exec(s))) { + matches.push(matchObj); + if (r.lastIndex === matchObj.index) { + r.lastIndex += 1; + } + } + + r.lastIndex = origIndex; + + return matches; +} + +function getVar(env, pre, key) { + var r = typeof env === 'function' ? env(key) : env[key]; + if (typeof r === 'undefined' && key != '') { + r = ''; + } else if (typeof r === 'undefined') { + r = '$'; + } + + if (typeof r === 'object') { + return pre + TOKEN + JSON.stringify(r) + TOKEN; + } + return pre + r; +} + +function parseInternal(string, env, opts) { + if (!opts) { + opts = {}; + } + var BS = opts.escape || '\\'; + var BAREWORD = '(\\' + BS + '[\'"' + META + ']|[^\\s\'"' + META + '])+'; + + var chunker = new RegExp([ + '(' + CONTROL + ')', // control chars + '(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')+' + ].join('|'), 'g'); + + var matches = matchAll(string, chunker); + + if (matches.length === 0) { + return []; + } + if (!env) { + env = {}; + } + + var commented = false; + + return matches.map(function (match) { + var s = match[0]; + if (!s || commented) { + return void undefined; + } + if (controlRE.test(s)) { + return { op: s }; + } + + // Hand-written scanner/parser for Bash quoting rules: + // + // 1. inside single quotes, all characters are printed literally. + // 2. inside double quotes, all characters are printed literally + // except variables prefixed by '$' and backslashes followed by + // either a double quote or another backslash. + // 3. outside of any quotes, backslashes are treated as escape + // characters and not printed (unless they are themselves escaped) + // 4. quote context can switch mid-token if there is no whitespace + // between the two quote contexts (e.g. all'one'"token" parses as + // "allonetoken") + var quote = false; + var esc = false; + var out = ''; + var isGlob = false; + var i; + + function parseEnvVar() { + i += 1; + var varend; + var varname; + var char = s.charAt(i); + + if (char === '{') { + i += 1; + if (s.charAt(i) === '}') { + throw new Error('Bad substitution: ' + s.slice(i - 2, i + 1)); + } + varend = s.indexOf('}', i); + if (varend < 0) { + throw new Error('Bad substitution: ' + s.slice(i)); + } + varname = s.slice(i, varend); + i = varend; + } else if ((/[*@#?$!_-]/).test(char)) { + varname = char; + i += 1; + } else { + var slicedFromI = s.slice(i); + varend = slicedFromI.match(/[^\w\d_]/); + if (!varend) { + varname = slicedFromI; + i = s.length; + } else { + varname = slicedFromI.slice(0, varend.index); + i += varend.index - 1; + } + } + return getVar(env, '', varname); + } + + for (i = 0; i < s.length; i++) { + var c = s.charAt(i); + isGlob = isGlob || (!quote && (c === '*' || c === '?')); + if (esc) { + out += c; + esc = false; + } else if (quote) { + if (c === quote) { + quote = false; + } else if (quote == SQ) { + out += c; + } else { // Double quote + if (c === BS) { + i += 1; + c = s.charAt(i); + if (c === DQ || c === BS || c === DS) { + out += c; + } else { + out += BS + c; + } + } else if (c === DS) { + out += parseEnvVar(); + } else { + out += c; + } + } + } else if (c === DQ || c === SQ) { + quote = c; + } else if (controlRE.test(c)) { + return { op: s }; + } else if (hash.test(c)) { + commented = true; + var commentObj = { comment: string.slice(match.index + i + 1) }; + if (out.length) { + return [out, commentObj]; + } + return [commentObj]; + } else if (c === BS) { + esc = true; + } else if (c === DS) { + out += parseEnvVar(); + } else { + out += c; + } + } + + if (isGlob) { + return { op: 'glob', pattern: out }; + } + + return out; + }).reduce(function (prev, arg) { // finalize parsed arguments + // TODO: replace this whole reduce with a concat + return typeof arg === 'undefined' ? prev : prev.concat(arg); + }, []); +} + +module.exports = function parse(s, env, opts) { + var mapped = parseInternal(s, env, opts); + if (typeof env !== 'function') { + return mapped; + } + return mapped.reduce(function (acc, s) { + if (typeof s === 'object') { + return acc.concat(s); + } + var xs = s.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g')); + if (xs.length === 1) { + return acc.concat(xs[0]); + } + return acc.concat(xs.filter(Boolean).map(function (x) { + if (startsWithToken.test(x)) { + return JSON.parse(x.split(TOKEN)[1]); + } + return x; + })); + }, []); +}; diff --git a/node_modules/shell-quote/quote.js b/node_modules/shell-quote/quote.js new file mode 100644 index 0000000..afbccf0 --- /dev/null +++ b/node_modules/shell-quote/quote.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = function quote(xs) { + return xs.map(function (s) { + if (s && typeof s === 'object') { + return s.op.replace(/(.)/g, '\\$1'); + } + if ((/["\s]/).test(s) && !(/'/).test(s)) { + return "'" + s.replace(/(['\\])/g, '\\$1') + "'"; + } + if ((/["'\s]/).test(s)) { + return '"' + s.replace(/(["\\$`!])/g, '\\$1') + '"'; + } + return String(s).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g, '$1\\$2'); + }).join(' '); +}; diff --git a/node_modules/shell-quote/security.md b/node_modules/shell-quote/security.md new file mode 100644 index 0000000..dc86413 --- /dev/null +++ b/node_modules/shell-quote/security.md @@ -0,0 +1,11 @@ +# Security Policy + +## Supported Versions + +Only the latest major version is supported at any given time. + +## Reporting a Vulnerability + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. diff --git a/node_modules/shell-quote/test/comment.js b/node_modules/shell-quote/test/comment.js new file mode 100644 index 0000000..fb15d5c --- /dev/null +++ b/node_modules/shell-quote/test/comment.js @@ -0,0 +1,16 @@ +'use strict'; + +var test = require('tape'); +var parse = require('../').parse; + +test('comment', function (t) { + t.same(parse('beep#boop'), ['beep', { comment: 'boop' }]); + t.same(parse('beep #boop'), ['beep', { comment: 'boop' }]); + t.same(parse('beep # boop'), ['beep', { comment: ' boop' }]); + t.same(parse('beep # > boop'), ['beep', { comment: ' > boop' }]); + t.same(parse('beep # "> boop"'), ['beep', { comment: ' "> boop"' }]); + t.same(parse('beep "#"'), ['beep', '#']); + t.same(parse('beep #"#"#'), ['beep', { comment: '"#"#' }]); + t.same(parse('beep > boop # > foo'), ['beep', { op: '>' }, 'boop', { comment: ' > foo' }]); + t.end(); +}); diff --git a/node_modules/shell-quote/test/env.js b/node_modules/shell-quote/test/env.js new file mode 100644 index 0000000..4cc0a51 --- /dev/null +++ b/node_modules/shell-quote/test/env.js @@ -0,0 +1,52 @@ +'use strict'; + +var test = require('tape'); +var parse = require('../').parse; + +test('expand environment variables', function (t) { + t.same(parse('a $XYZ c', { XYZ: 'b' }), ['a', 'b', 'c']); + t.same(parse('a${XYZ}c', { XYZ: 'b' }), ['abc']); + t.same(parse('a${XYZ}c $XYZ', { XYZ: 'b' }), ['abc', 'b']); + t.same(parse('"-$X-$Y-"', { X: 'a', Y: 'b' }), ['-a-b-']); + t.same(parse("'-$X-$Y-'", { X: 'a', Y: 'b' }), ['-$X-$Y-']); + t.same(parse('qrs"$zzz"wxy', { zzz: 'tuv' }), ['qrstuvwxy']); + t.same(parse("qrs'$zzz'wxy", { zzz: 'tuv' }), ['qrs$zzzwxy']); + t.same(parse('qrs${zzz}wxy'), ['qrswxy']); + t.same(parse('qrs$wxy $'), ['qrs', '$']); + t.same(parse('grep "xy$"'), ['grep', 'xy$']); + t.same(parse('ab$x', { x: 'c' }), ['abc']); + t.same(parse('ab\\$x', { x: 'c' }), ['ab$x']); + t.same(parse('ab${x}def', { x: 'c' }), ['abcdef']); + t.same(parse('ab\\${x}def', { x: 'c' }), ['ab${x}def']); + t.same(parse('"ab\\${x}def"', { x: 'c' }), ['ab${x}def']); + + t.end(); +}); + +test('expand environment variables within here-strings', function (t) { + t.same(parse('a <<< $x', { x: 'Joe' }), ['a', { op: '<<<' }, 'Joe']); + t.same(parse('a <<< ${x}', { x: 'Joe' }), ['a', { op: '<<<' }, 'Joe']); + t.same(parse('a <<< "$x"', { x: 'Joe' }), ['a', { op: '<<<' }, 'Joe']); + t.same(parse('a <<< "${x}"', { x: 'Joe' }), ['a', { op: '<<<' }, 'Joe']); + + t.end(); +}); + +test('environment variables with metacharacters', function (t) { + t.same(parse('a $XYZ c', { XYZ: '"b"' }), ['a', '"b"', 'c']); + t.same(parse('a $XYZ c', { XYZ: '$X', X: 5 }), ['a', '$X', 'c']); + t.same(parse('a"$XYZ"c', { XYZ: "'xyz'" }), ["a'xyz'c"]); + + t.end(); +}); + +test('special shell parameters', function (t) { + var chars = '*@#?-$!0_'.split(''); + t.plan(chars.length); + + chars.forEach(function (c) { + var env = {}; + env[c] = 'xxx'; + t.same(parse('a $' + c + ' c', env), ['a', 'xxx', 'c']); + }); +}); diff --git a/node_modules/shell-quote/test/env_fn.js b/node_modules/shell-quote/test/env_fn.js new file mode 100644 index 0000000..968e912 --- /dev/null +++ b/node_modules/shell-quote/test/env_fn.js @@ -0,0 +1,21 @@ +'use strict'; + +var test = require('tape'); +var parse = require('../').parse; + +function getEnv() { + return 'xxx'; +} + +function getEnvObj() { + return { op: '@@' }; +} + +test('functional env expansion', function (t) { + t.plan(4); + + t.same(parse('a $XYZ c', getEnv), ['a', 'xxx', 'c']); + t.same(parse('a $XYZ c', getEnvObj), ['a', { op: '@@' }, 'c']); + t.same(parse('a${XYZ}c', getEnvObj), ['a', { op: '@@' }, 'c']); + t.same(parse('"a $XYZ c"', getEnvObj), ['a ', { op: '@@' }, ' c']); +}); diff --git a/node_modules/shell-quote/test/op.js b/node_modules/shell-quote/test/op.js new file mode 100644 index 0000000..38d3757 --- /dev/null +++ b/node_modules/shell-quote/test/op.js @@ -0,0 +1,102 @@ +'use strict'; + +var test = require('tape'); +var parse = require('../').parse; + +test('single operators', function (t) { + t.same(parse('beep | boop'), ['beep', { op: '|' }, 'boop']); + t.same(parse('beep|boop'), ['beep', { op: '|' }, 'boop']); + t.same(parse('beep \\| boop'), ['beep', '|', 'boop']); + t.same(parse('beep "|boop"'), ['beep', '|boop']); + + t.same(parse('echo zing &'), ['echo', 'zing', { op: '&' }]); + t.same(parse('echo zing&'), ['echo', 'zing', { op: '&' }]); + t.same(parse('echo zing\\&'), ['echo', 'zing&']); + t.same(parse('echo "zing\\&"'), ['echo', 'zing\\&']); + + t.same(parse('beep;boop'), ['beep', { op: ';' }, 'boop']); + t.same(parse('(beep;boop)'), [ + { op: '(' }, 'beep', { op: ';' }, 'boop', { op: ')' } + ]); + + t.same(parse('beep>boop'), ['beep', { op: '>' }, 'boop']); + t.same(parse('beep 2>boop'), ['beep', '2', { op: '>' }, 'boop']); + t.same(parse('beep>blip'), + ['beep', { op: ';;' }, 'boop', { op: '|&' }, 'byte', { op: '>>' }, 'blip'] + ); + + t.same(parse('beep 2>&1'), ['beep', '2', { op: '>&' }, '1']); + + t.same( + parse('beep<(boop)'), + ['beep', { op: '<(' }, 'boop', { op: ')' }] + ); + t.same( + parse('beep<<(boop)'), + ['beep', { op: '<' }, { op: '<(' }, 'boop', { op: ')' }] + ); + + t.end(); +}); + +test('duplicating input file descriptors', function (t) { + // duplicating stdout to file descriptor 3 + t.same(parse('beep 3<&1'), ['beep', '3', { op: '<&' }, '1']); + + // duplicating stdout to file descriptor 0, i.e. stdin + t.same(parse('beep <&1'), ['beep', { op: '<&' }, '1']); + + // closes stdin + t.same(parse('beep <&-'), ['beep', { op: '<&' }, '-']); + + t.end(); +}); + +test('here strings', function (t) { + t.same(parse('cat <<< "hello world"'), ['cat', { op: '<<<' }, 'hello world']); + t.same(parse('cat <<< hello'), ['cat', { op: '<<<' }, 'hello']); + t.same(parse('cat<<<;{}']), '\\>\\<\\;\\{\\}'); + t.equal(quote(['a', 1, true, false]), 'a 1 true false'); + t.equal(quote(['a', 1, null, undefined]), 'a 1 null undefined'); + t.equal(quote(['a\\x']), 'a\\\\x'); + t.end(); +}); + +test('quote ops', function (t) { + t.equal(quote(['a', { op: '|' }, 'b']), 'a \\| b'); + t.equal( + quote(['a', { op: '&&' }, 'b', { op: ';' }, 'c']), + 'a \\&\\& b \\; c' + ); + t.end(); +}); + +test('quote windows paths', { skip: 'breaking change, disabled until 2.x' }, function (t) { + var path = 'C:\\projects\\node-shell-quote\\index.js'; + + t.equal(quote([path, 'b', 'c d']), 'C:\\projects\\node-shell-quote\\index.js b \'c d\''); + + t.end(); +}); + +test("chars for windows paths don't break out", function (t) { + var x = '`:\\a\\b'; + t.equal(quote([x]), '\\`\\:\\\\a\\\\b'); + t.end(); +}); diff --git a/node_modules/shell-quote/test/set.js b/node_modules/shell-quote/test/set.js new file mode 100644 index 0000000..9694538 --- /dev/null +++ b/node_modules/shell-quote/test/set.js @@ -0,0 +1,31 @@ +'use strict'; + +var test = require('tape'); +var parse = require('../').parse; + +test('set env vars', function (t) { + t.same( + parse('ABC=444 x y z'), + ['ABC=444', 'x', 'y', 'z'] + ); + t.same( + parse('ABC=3\\ 4\\ 5 x y z'), + ['ABC=3 4 5', 'x', 'y', 'z'] + ); + t.same( + parse('X="7 8 9" printx'), + ['X=7 8 9', 'printx'] + ); + t.same( + parse('X="7 8 9"; printx'), + ['X=7 8 9', { op: ';' }, 'printx'] + ); + t.same( + parse('X="7 8 9"; printx', function () { + t.fail('should not have matched any keys'); + }), + ['X=7 8 9', { op: ';' }, 'printx'] + ); + + t.end(); +}); diff --git a/node_modules/side-channel/.editorconfig b/node_modules/side-channel/.editorconfig new file mode 100644 index 0000000..72e0eba --- /dev/null +++ b/node_modules/side-channel/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab +indent_size = 2 +trim_trailing_whitespace = true diff --git a/node_modules/side-channel/.eslintrc b/node_modules/side-channel/.eslintrc new file mode 100644 index 0000000..93978e7 --- /dev/null +++ b/node_modules/side-channel/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-lines-per-function": 0, + "multiline-comment-style": 1, + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + }, +} diff --git a/node_modules/side-channel/.github/FUNDING.yml b/node_modules/side-channel/.github/FUNDING.yml new file mode 100644 index 0000000..2a94840 --- /dev/null +++ b/node_modules/side-channel/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/side-channel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/side-channel/.nycrc b/node_modules/side-channel/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/side-channel/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/side-channel/CHANGELOG.md b/node_modules/side-channel/CHANGELOG.md new file mode 100644 index 0000000..25369c5 --- /dev/null +++ b/node_modules/side-channel/CHANGELOG.md @@ -0,0 +1,95 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.6](https://github.com/ljharb/side-channel/compare/v1.0.5...v1.0.6) - 2024-02-29 + +### Commits + +- add types [`9beef66`](https://github.com/ljharb/side-channel/commit/9beef6643e6d717ea57bedabf86448123a7dd9e9) +- [meta] simplify `exports` [`4334cf9`](https://github.com/ljharb/side-channel/commit/4334cf9df654151504c383b62a2f9ebdc8d9d5ac) +- [Deps] update `call-bind` [`d6043c4`](https://github.com/ljharb/side-channel/commit/d6043c4d8f4d7be9037dd0f0419c7a2e0e39ec6a) +- [Dev Deps] update `tape` [`6aca376`](https://github.com/ljharb/side-channel/commit/6aca3761868dc8cd5ff7fd9799bf6b95e09a6eb0) + +## [v1.0.5](https://github.com/ljharb/side-channel/compare/v1.0.4...v1.0.5) - 2024-02-06 + +### Commits + +- [actions] reuse common workflows [`3d2e1ff`](https://github.com/ljharb/side-channel/commit/3d2e1ffd16dd6eaaf3e40ff57951f840d2d63c04) +- [meta] use `npmignore` to autogenerate an npmignore file [`04296ea`](https://github.com/ljharb/side-channel/commit/04296ea17d1544b0a5d20fd5bfb31aa4f6513eb9) +- [meta] add `.editorconfig`; add `eclint` [`130f0a6`](https://github.com/ljharb/side-channel/commit/130f0a6adbc04d385c7456a601d38344dce3d6a9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `safe-publish-latest`, `tape` [`d480c2f`](https://github.com/ljharb/side-channel/commit/d480c2fbe757489ae9b4275491ffbcc3ac4725e9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`ecbe70e`](https://github.com/ljharb/side-channel/commit/ecbe70e53a418234081a77971fec1fdfae20c841) +- [actions] update rebase action [`75240b9`](https://github.com/ljharb/side-channel/commit/75240b9963b816e8846400d2287cb68f88c7fba7) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `npmignore`, `tape` [`ae8d281`](https://github.com/ljharb/side-channel/commit/ae8d281572430099109870fd9430d2ca3f320b8d) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`7125b88`](https://github.com/ljharb/side-channel/commit/7125b885fd0eacad4fee9b073b72d14065ece278) +- [Deps] update `call-bind`, `get-intrinsic`, `object-inspect` [`82577c9`](https://github.com/ljharb/side-channel/commit/82577c9796304519139a570f82a317211b5f3b86) +- [Deps] update `call-bind`, `get-intrinsic`, `object-inspect` [`550aadf`](https://github.com/ljharb/side-channel/commit/550aadf20475a6081fd70304cc54f77259a5c8a8) +- [Tests] increase coverage [`5130877`](https://github.com/ljharb/side-channel/commit/5130877a7b27c862e64e6d1c12a178b28808859d) +- [Deps] update `get-intrinsic`, `object-inspect` [`ba0194c`](https://github.com/ljharb/side-channel/commit/ba0194c505b1a8a0427be14cadd5b8a46d4d01b8) +- [meta] add missing `engines.node` [`985fd24`](https://github.com/ljharb/side-channel/commit/985fd249663cb06617a693a94fe08cad12f5cb70) +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`40227a8`](https://github.com/ljharb/side-channel/commit/40227a87b01709ad2c0eebf87eb4223a800099b9) +- [Deps] update `get-intrinsic` [`a989b40`](https://github.com/ljharb/side-channel/commit/a989b4024958737ae7be9fbffdeff2078f33a0fd) +- [Deps] update `object-inspect` [`aec42d2`](https://github.com/ljharb/side-channel/commit/aec42d2ec541a31aaa02475692c87d489237d9a3) + +## [v1.0.4](https://github.com/ljharb/side-channel/compare/v1.0.3...v1.0.4) - 2020-12-29 + +### Commits + +- [Tests] migrate tests to Github Actions [`10909cb`](https://github.com/ljharb/side-channel/commit/10909cbf8ce9c0bf96f604cf13d7ffd5a22c2d40) +- [Refactor] Use a linked list rather than an array, and move accessed nodes to the beginning [`195613f`](https://github.com/ljharb/side-channel/commit/195613f28b5c1e6072ef0b61b5beebaf2b6a304e) +- [meta] do not publish github action workflow files [`290ec29`](https://github.com/ljharb/side-channel/commit/290ec29cd21a60585145b4a7237ec55228c52c27) +- [Tests] run `nyc` on all tests; use `tape` runner [`ea6d030`](https://github.com/ljharb/side-channel/commit/ea6d030ff3fe6be2eca39e859d644c51ecd88869) +- [actions] add "Allow Edits" workflow [`d464d8f`](https://github.com/ljharb/side-channel/commit/d464d8fe52b5eddf1504a0ed97f0941a90f32c15) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog` [`02daca8`](https://github.com/ljharb/side-channel/commit/02daca87c6809821c97be468d1afa2f5ef447383) +- [Refactor] use `call-bind` and `get-intrinsic` instead of `es-abstract` [`e09d481`](https://github.com/ljharb/side-channel/commit/e09d481528452ebafa5cdeae1af665c35aa2deee) +- [Deps] update `object.assign` [`ee83aa8`](https://github.com/ljharb/side-channel/commit/ee83aa81df313b5e46319a63adb05cf0c179079a) +- [actions] update rebase action to use checkout v2 [`7726b0b`](https://github.com/ljharb/side-channel/commit/7726b0b058b632fccea709f58960871defaaa9d7) + +## [v1.0.3](https://github.com/ljharb/side-channel/compare/v1.0.2...v1.0.3) - 2020-08-23 + +### Commits + +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`1f10561`](https://github.com/ljharb/side-channel/commit/1f105611ef3acf32dec8032ae5c0baa5e56bb868) +- [Deps] update `es-abstract`, `object-inspect` [`bc20159`](https://github.com/ljharb/side-channel/commit/bc201597949a505e37cef9eaf24c7010831e6f03) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`b9b2b22`](https://github.com/ljharb/side-channel/commit/b9b2b225f9e0ea72a6ec2b89348f0bd690bc9ed1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`7055ab4`](https://github.com/ljharb/side-channel/commit/7055ab4de0860606efd2003674a74f1fe6ebc07e) +- [Dev Deps] update `auto-changelog`; add `aud` [`d278c37`](https://github.com/ljharb/side-channel/commit/d278c37d08227be4f84aa769fcd919e73feeba40) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`3bcf982`](https://github.com/ljharb/side-channel/commit/3bcf982faa122745b39c33ce83d32fdf003741c6) +- [Tests] only audit prod deps [`18d01c4`](https://github.com/ljharb/side-channel/commit/18d01c4015b82a3d75044c4d5ba7917b2eac01ec) +- [Deps] update `es-abstract` [`6ab096d`](https://github.com/ljharb/side-channel/commit/6ab096d9de2b482cf5e0717e34e212f5b2b9bc9a) +- [Dev Deps] update `tape` [`9dc174c`](https://github.com/ljharb/side-channel/commit/9dc174cc651dfd300b4b72da936a0a7eda5f9452) +- [Deps] update `es-abstract` [`431d0f0`](https://github.com/ljharb/side-channel/commit/431d0f0ff11fbd2ae6f3115582a356d3a1cfce82) +- [Deps] update `es-abstract` [`49869fd`](https://github.com/ljharb/side-channel/commit/49869fd323bf4453f0ba515c0fb265cf5ab7b932) +- [meta] Add package.json to package's exports [`77d9cdc`](https://github.com/ljharb/side-channel/commit/77d9cdceb2a9e47700074f2ae0c0a202e7dac0d4) + +## [v1.0.2](https://github.com/ljharb/side-channel/compare/v1.0.1...v1.0.2) - 2019-12-20 + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`4a526df`](https://github.com/ljharb/side-channel/commit/4a526df44e4701566ed001ec78546193f818b082) +- [Deps] update `es-abstract` [`d4f6e62`](https://github.com/ljharb/side-channel/commit/d4f6e629b6fb93a07415db7f30d3c90fd7f264fe) + +## [v1.0.1](https://github.com/ljharb/side-channel/compare/v1.0.0...v1.0.1) - 2019-12-01 + +### Commits + +- [Fix] add missing "exports" [`d212907`](https://github.com/ljharb/side-channel/commit/d2129073abf0701a5343bf28aa2145617604dc2e) + +## v1.0.0 - 2019-12-01 + +### Commits + +- Initial implementation [`dbebd3a`](https://github.com/ljharb/side-channel/commit/dbebd3a4b5ed64242f9a6810efe7c4214cd8cde4) +- Initial tests [`73bdefe`](https://github.com/ljharb/side-channel/commit/73bdefe568c9076cf8c0b8719bc2141aec0e19b8) +- Initial commit [`43c03e1`](https://github.com/ljharb/side-channel/commit/43c03e1c2849ec50a87b7a5cd76238a62b0b8770) +- npm init [`5c090a7`](https://github.com/ljharb/side-channel/commit/5c090a765d66a5527d9889b89aeff78dee91348c) +- [meta] add `auto-changelog` [`a5c4e56`](https://github.com/ljharb/side-channel/commit/a5c4e5675ec02d5eb4d84b4243aeea2a1d38fbec) +- [actions] add automatic rebasing / merge commit blocking [`bab1683`](https://github.com/ljharb/side-channel/commit/bab1683d8f9754b086e94397699fdc645e0d7077) +- [meta] add `funding` field; create FUNDING.yml [`63d7aea`](https://github.com/ljharb/side-channel/commit/63d7aeaf34f5650650ae97ca4b9fae685bd0937c) +- [Tests] add `npm run lint` [`46a5a81`](https://github.com/ljharb/side-channel/commit/46a5a81705cd2664f83df232c01dbbf2ee952885) +- Only apps should have lockfiles [`8b16b03`](https://github.com/ljharb/side-channel/commit/8b16b0305f00895d90c4e2e5773c854cfea0e448) +- [meta] add `safe-publish-latest` [`2f098ef`](https://github.com/ljharb/side-channel/commit/2f098ef092a39399cfe548b19a1fc03c2fd2f490) diff --git a/node_modules/side-channel/LICENSE b/node_modules/side-channel/LICENSE new file mode 100644 index 0000000..3900dd7 --- /dev/null +++ b/node_modules/side-channel/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/side-channel/README.md b/node_modules/side-channel/README.md new file mode 100644 index 0000000..7fa4f06 --- /dev/null +++ b/node_modules/side-channel/README.md @@ -0,0 +1,2 @@ +# side-channel +Store information about any JS value in a side channel. Uses WeakMap if available. diff --git a/node_modules/side-channel/index.d.ts b/node_modules/side-channel/index.d.ts new file mode 100644 index 0000000..7cb112b --- /dev/null +++ b/node_modules/side-channel/index.d.ts @@ -0,0 +1,27 @@ +declare namespace getSideChannel { + type Key = unknown; + type ListNode = { + key: Key; + next: ListNode; + value: T; + }; + type RootNode = { + key: object; + next: null | ListNode; + }; + function listGetNode(list: RootNode, key: ListNode['key']): ListNode | void; + function listGet(objects: RootNode, key: ListNode['key']): T | void; + function listSet(objects: RootNode, key: ListNode['key'], value: T): void; + function listHas(objects: RootNode, key: ListNode['key']): boolean; + + type Channel = { + assert: (key: Key) => void; + has: (key: Key) => boolean; + get: (key: Key) => T; + set: (key: Key, value: T) => void; + } +} + +declare function getSideChannel(): getSideChannel.Channel; + +export = getSideChannel; diff --git a/node_modules/side-channel/index.js b/node_modules/side-channel/index.js new file mode 100644 index 0000000..6b6926e --- /dev/null +++ b/node_modules/side-channel/index.js @@ -0,0 +1,129 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var callBound = require('call-bind/callBound'); +var inspect = require('object-inspect'); + +var $TypeError = require('es-errors/type'); +var $WeakMap = GetIntrinsic('%WeakMap%', true); +var $Map = GetIntrinsic('%Map%', true); + +var $weakMapGet = callBound('WeakMap.prototype.get', true); +var $weakMapSet = callBound('WeakMap.prototype.set', true); +var $weakMapHas = callBound('WeakMap.prototype.has', true); +var $mapGet = callBound('Map.prototype.get', true); +var $mapSet = callBound('Map.prototype.set', true); +var $mapHas = callBound('Map.prototype.has', true); + +/* +* This function traverses the list returning the node corresponding to the given key. +* +* That node is also moved to the head of the list, so that if it's accessed again we don't need to traverse the whole list. By doing so, all the recently used nodes can be accessed relatively quickly. +*/ +/** @type {import('.').listGetNode} */ +var listGetNode = function (list, key) { // eslint-disable-line consistent-return + /** @type {typeof list | NonNullable<(typeof list)['next']>} */ + var prev = list; + /** @type {(typeof list)['next']} */ + var curr; + for (; (curr = prev.next) !== null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + // eslint-disable-next-line no-extra-parens + curr.next = /** @type {NonNullable} */ (list.next); + list.next = curr; // eslint-disable-line no-param-reassign + return curr; + } + } +}; + +/** @type {import('.').listGet} */ +var listGet = function (objects, key) { + var node = listGetNode(objects, key); + return node && node.value; +}; +/** @type {import('.').listSet} */ +var listSet = function (objects, key, value) { + var node = listGetNode(objects, key); + if (node) { + node.value = value; + } else { + // Prepend the new node to the beginning of the list + objects.next = /** @type {import('.').ListNode} */ ({ // eslint-disable-line no-param-reassign, no-extra-parens + key: key, + next: objects.next, + value: value + }); + } +}; +/** @type {import('.').listHas} */ +var listHas = function (objects, key) { + return !!listGetNode(objects, key); +}; + +/** @type {import('.')} */ +module.exports = function getSideChannel() { + /** @type {WeakMap} */ var $wm; + /** @type {Map} */ var $m; + /** @type {import('.').RootNode} */ var $o; + + /** @type {import('.').Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + get: function (key) { // eslint-disable-line consistent-return + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapGet($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapGet($m, key); + } + } else { + if ($o) { // eslint-disable-line no-lonely-if + return listGet($o, key); + } + } + }, + has: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapHas($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapHas($m, key); + } + } else { + if ($o) { // eslint-disable-line no-lonely-if + return listHas($o, key); + } + } + return false; + }, + set: function (key, value) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if ($Map) { + if (!$m) { + $m = new $Map(); + } + $mapSet($m, key, value); + } else { + if (!$o) { + // Initialize the linked list as an empty node, so that we don't have to special-case handling of the first node: we can always refer to it as (previous node).next, instead of something like (list).head + $o = { key: {}, next: null }; + } + listSet($o, key, value); + } + } + }; + return channel; +}; diff --git a/node_modules/side-channel/package.json b/node_modules/side-channel/package.json new file mode 100644 index 0000000..02cffca --- /dev/null +++ b/node_modules/side-channel/package.json @@ -0,0 +1,84 @@ +{ + "name": "side-channel", + "version": "1.0.6", + "description": "Store information about any JS value in a side channel. Uses WeakMap if available.", + "main": "index.js", + "exports": { + "./package.json": "./package.json", + ".": "./index.js" + }, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/side-channel.git" + }, + "keywords": [ + "weakmap", + "map", + "side", + "channel", + "metadata" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/side-channel/issues" + }, + "homepage": "https://github.com/ljharb/side-channel#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/call-bind": "^1.0.5", + "@types/get-intrinsic": "^1.2.2", + "@types/object-inspect": "^1.8.4", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eclint": "^2.8.1", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.5", + "typescript": "next" + }, + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/side-channel/test/index.js b/node_modules/side-channel/test/index.js new file mode 100644 index 0000000..8da3200 --- /dev/null +++ b/node_modules/side-channel/test/index.js @@ -0,0 +1,83 @@ +'use strict'; + +var test = require('tape'); + +var getSideChannel = require('../'); + +test('export', function (t) { + t.equal(typeof getSideChannel, 'function', 'is a function'); + t.equal(getSideChannel.length, 0, 'takes no arguments'); + + var channel = getSideChannel(); + t.ok(channel, 'is truthy'); + t.equal(typeof channel, 'object', 'is an object'); + + t.end(); +}); + +test('assert', function (t) { + var channel = getSideChannel(); + t['throws']( + function () { channel.assert({}); }, + TypeError, + 'nonexistent value throws' + ); + + var o = {}; + channel.set(o, 'data'); + t.doesNotThrow(function () { channel.assert(o); }, 'existent value noops'); + + t.end(); +}); + +test('has', function (t) { + var channel = getSideChannel(); + /** @type {unknown[]} */ var o = []; + + t.equal(channel.has(o), false, 'nonexistent value yields false'); + + channel.set(o, 'foo'); + t.equal(channel.has(o), true, 'existent value yields true'); + + t.equal(channel.has('abc'), false, 'non object value non existent yields false'); + + channel.set('abc', 'foo'); + t.equal(channel.has('abc'), true, 'non object value that exists yields true'); + + t.end(); +}); + +test('get', function (t) { + var channel = getSideChannel(); + var o = {}; + t.equal(channel.get(o), undefined, 'nonexistent value yields undefined'); + + var data = {}; + channel.set(o, data); + t.equal(channel.get(o), data, '"get" yields data set by "set"'); + + t.end(); +}); + +test('set', function (t) { + var channel = getSideChannel(); + var o = function () {}; + t.equal(channel.get(o), undefined, 'value not set'); + + channel.set(o, 42); + t.equal(channel.get(o), 42, 'value was set'); + + channel.set(o, Infinity); + t.equal(channel.get(o), Infinity, 'value was set again'); + + var o2 = {}; + channel.set(o2, 17); + t.equal(channel.get(o), Infinity, 'o is not modified'); + t.equal(channel.get(o2), 17, 'o2 is set'); + + channel.set(o, 14); + t.equal(channel.get(o), 14, 'o is modified'); + t.equal(channel.get(o2), 17, 'o2 is not modified'); + + t.end(); +}); diff --git a/node_modules/side-channel/tsconfig.json b/node_modules/side-channel/tsconfig.json new file mode 100644 index 0000000..fdfa155 --- /dev/null +++ b/node_modules/side-channel/tsconfig.json @@ -0,0 +1,50 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "es2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": ["types"], /* Specify multiple folders that act like `./node_modules/@types`. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow `import x from y` when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + + /* Completeness */ + // "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage", + "test/list-exports" + ], +} diff --git a/node_modules/signal-exit/LICENSE.txt b/node_modules/signal-exit/LICENSE.txt new file mode 100644 index 0000000..954f2fa --- /dev/null +++ b/node_modules/signal-exit/LICENSE.txt @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) 2015-2023 Benjamin Coe, Isaac Z. Schlueter, and Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/signal-exit/README.md b/node_modules/signal-exit/README.md new file mode 100644 index 0000000..c55cd45 --- /dev/null +++ b/node_modules/signal-exit/README.md @@ -0,0 +1,74 @@ +# signal-exit + +When you want to fire an event no matter how a process exits: + +- reaching the end of execution. +- explicitly having `process.exit(code)` called. +- having `process.kill(pid, sig)` called. +- receiving a fatal signal from outside the process + +Use `signal-exit`. + +```js +// Hybrid module, either works +import { onExit } from 'signal-exit' +// or: +// const { onExit } = require('signal-exit') + +onExit((code, signal) => { + console.log('process exited!', code, signal) +}) +``` + +## API + +`remove = onExit((code, signal) => {}, options)` + +The return value of the function is a function that will remove +the handler. + +Note that the function _only_ fires for signals if the signal +would cause the process to exit. That is, there are no other +listeners, and it is a fatal signal. + +If the global `process` object is not suitable for this purpose +(ie, it's unset, or doesn't have an `emit` method, etc.) then the +`onExit` function is a no-op that returns a no-op `remove` method. + +### Options + +- `alwaysLast`: Run this handler after any other signal or exit + handlers. This causes `process.emit` to be monkeypatched. + +### Capturing Signal Exits + +If the handler returns an exact boolean `true`, and the exit is a +due to signal, then the signal will be considered handled, and +will _not_ trigger a synthetic `process.kill(process.pid, +signal)` after firing the `onExit` handlers. + +In this case, it your responsibility as the caller to exit with a +signal (for example, by calling `process.kill()`) if you wish to +preserve the same exit status that would otherwise have occurred. +If you do not, then the process will likely exit gracefully with +status 0 at some point, assuming that no other terminating signal +or other exit trigger occurs. + +Prior to calling handlers, the `onExit` machinery is unloaded, so +any subsequent exits or signals will not be handled, even if the +signal is captured and the exit is thus prevented. + +Note that numeric code exits may indicate that the process is +already committed to exiting, for example due to a fatal +exception or unhandled promise rejection, and so there is no way to +prevent it safely. + +### Browser Fallback + +The `'signal-exit/browser'` module is the same fallback shim that +just doesn't do anything, but presents the same function +interface. + +Patches welcome to add something that hooks onto +`window.onbeforeunload` or similar, but it might just not be a +thing that makes sense there. diff --git a/node_modules/signal-exit/dist/cjs/browser.d.ts b/node_modules/signal-exit/dist/cjs/browser.d.ts new file mode 100644 index 0000000..90f2e3f --- /dev/null +++ b/node_modules/signal-exit/dist/cjs/browser.d.ts @@ -0,0 +1,12 @@ +/** + * This is a browser shim that provides the same functional interface + * as the main node export, but it does nothing. + * @module + */ +import type { Handler } from './index.js'; +export declare const onExit: (cb: Handler, opts: { + alwaysLast?: boolean; +}) => () => void; +export declare const load: () => void; +export declare const unload: () => void; +//# sourceMappingURL=browser.d.ts.map \ No newline at end of file diff --git a/node_modules/signal-exit/dist/cjs/browser.d.ts.map b/node_modules/signal-exit/dist/cjs/browser.d.ts.map new file mode 100644 index 0000000..aacc1d3 --- /dev/null +++ b/node_modules/signal-exit/dist/cjs/browser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../../src/browser.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AACzC,eAAO,MAAM,MAAM,EAAE,CACnB,EAAE,EAAE,OAAO,EACX,IAAI,EAAE;IAAE,UAAU,CAAC,EAAE,OAAO,CAAA;CAAE,KAC3B,MAAM,IAAqB,CAAA;AAChC,eAAO,MAAM,IAAI,YAAW,CAAA;AAC5B,eAAO,MAAM,MAAM,YAAW,CAAA"} \ No newline at end of file diff --git a/node_modules/signal-exit/dist/cjs/browser.js b/node_modules/signal-exit/dist/cjs/browser.js new file mode 100644 index 0000000..614fbf0 --- /dev/null +++ b/node_modules/signal-exit/dist/cjs/browser.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.unload = exports.load = exports.onExit = void 0; +const onExit = () => () => { }; +exports.onExit = onExit; +const load = () => { }; +exports.load = load; +const unload = () => { }; +exports.unload = unload; +//# sourceMappingURL=browser.js.map \ No newline at end of file diff --git a/node_modules/signal-exit/dist/cjs/browser.js.map b/node_modules/signal-exit/dist/cjs/browser.js.map new file mode 100644 index 0000000..342cf2e --- /dev/null +++ b/node_modules/signal-exit/dist/cjs/browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"browser.js","sourceRoot":"","sources":["../../src/browser.ts"],"names":[],"mappings":";;;AAMO,MAAM,MAAM,GAGD,GAAG,EAAE,CAAC,GAAG,EAAE,GAAE,CAAC,CAAA;AAHnB,QAAA,MAAM,UAGa;AACzB,MAAM,IAAI,GAAG,GAAG,EAAE,GAAE,CAAC,CAAA;AAAf,QAAA,IAAI,QAAW;AACrB,MAAM,MAAM,GAAG,GAAG,EAAE,GAAE,CAAC,CAAA;AAAjB,QAAA,MAAM,UAAW","sourcesContent":["/**\n * This is a browser shim that provides the same functional interface\n * as the main node export, but it does nothing.\n * @module\n */\nimport type { Handler } from './index.js'\nexport const onExit: (\n cb: Handler,\n opts: { alwaysLast?: boolean }\n) => () => void = () => () => {}\nexport const load = () => {}\nexport const unload = () => {}\n"]} \ No newline at end of file diff --git a/node_modules/signal-exit/dist/cjs/index.d.ts b/node_modules/signal-exit/dist/cjs/index.d.ts new file mode 100644 index 0000000..cabe9cf --- /dev/null +++ b/node_modules/signal-exit/dist/cjs/index.d.ts @@ -0,0 +1,48 @@ +/// +import { signals } from './signals.js'; +export { signals }; +/** + * A function that takes an exit code and signal as arguments + * + * In the case of signal exits *only*, a return value of true + * will indicate that the signal is being handled, and we should + * not synthetically exit with the signal we received. Regardless + * of the handler return value, the handler is unloaded when an + * otherwise fatal signal is received, so you get exactly 1 shot + * at it, unless you add another onExit handler at that point. + * + * In the case of numeric code exits, we may already have committed + * to exiting the process, for example via a fatal exception or + * unhandled promise rejection, so it is impossible to stop safely. + */ +export type Handler = (code: number | null | undefined, signal: NodeJS.Signals | null) => true | void; +export declare const +/** + * Called when the process is exiting, whether via signal, explicit + * exit, or running out of stuff to do. + * + * If the global process object is not suitable for instrumentation, + * then this will be a no-op. + * + * Returns a function that may be used to unload signal-exit. + */ +onExit: (cb: Handler, opts?: { + alwaysLast?: boolean | undefined; +} | undefined) => () => void, +/** + * Load the listeners. Likely you never need to call this, unless + * doing a rather deep integration with signal-exit functionality. + * Mostly exposed for the benefit of testing. + * + * @internal + */ +load: () => void, +/** + * Unload the listeners. Likely you never need to call this, unless + * doing a rather deep integration with signal-exit functionality. + * Mostly exposed for the benefit of testing. + * + * @internal + */ +unload: () => void; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/signal-exit/dist/cjs/index.d.ts.map b/node_modules/signal-exit/dist/cjs/index.d.ts.map new file mode 100644 index 0000000..f84594e --- /dev/null +++ b/node_modules/signal-exit/dist/cjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAIA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,OAAO,EAAE,CAAA;AAuBlB;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,OAAO,GAAG,CACpB,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAC/B,MAAM,EAAE,MAAM,CAAC,OAAO,GAAG,IAAI,KAC1B,IAAI,GAAG,IAAI,CAAA;AA8QhB,eAAO;AACL;;;;;;;;GAQG;AACH,MAAM,OAzMO,OAAO;;wBAPiD,IAAI;AAkNzE;;;;;;GAMG;AACH,IAAI;AAEJ;;;;;;GAMG;AACH,MAAM,YAGP,CAAA"} \ No newline at end of file diff --git a/node_modules/signal-exit/dist/cjs/index.js b/node_modules/signal-exit/dist/cjs/index.js new file mode 100644 index 0000000..797e674 --- /dev/null +++ b/node_modules/signal-exit/dist/cjs/index.js @@ -0,0 +1,279 @@ +"use strict"; +var _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.unload = exports.load = exports.onExit = exports.signals = void 0; +// Note: since nyc uses this module to output coverage, any lines +// that are in the direct sync flow of nyc's outputCoverage are +// ignored, since we can never get coverage for them. +// grab a reference to node's real process object right away +const signals_js_1 = require("./signals.js"); +Object.defineProperty(exports, "signals", { enumerable: true, get: function () { return signals_js_1.signals; } }); +const processOk = (process) => !!process && + typeof process === 'object' && + typeof process.removeListener === 'function' && + typeof process.emit === 'function' && + typeof process.reallyExit === 'function' && + typeof process.listeners === 'function' && + typeof process.kill === 'function' && + typeof process.pid === 'number' && + typeof process.on === 'function'; +const kExitEmitter = Symbol.for('signal-exit emitter'); +const global = globalThis; +const ObjectDefineProperty = Object.defineProperty.bind(Object); +// teeny special purpose ee +class Emitter { + emitted = { + afterExit: false, + exit: false, + }; + listeners = { + afterExit: [], + exit: [], + }; + count = 0; + id = Math.random(); + constructor() { + if (global[kExitEmitter]) { + return global[kExitEmitter]; + } + ObjectDefineProperty(global, kExitEmitter, { + value: this, + writable: false, + enumerable: false, + configurable: false, + }); + } + on(ev, fn) { + this.listeners[ev].push(fn); + } + removeListener(ev, fn) { + const list = this.listeners[ev]; + const i = list.indexOf(fn); + /* c8 ignore start */ + if (i === -1) { + return; + } + /* c8 ignore stop */ + if (i === 0 && list.length === 1) { + list.length = 0; + } + else { + list.splice(i, 1); + } + } + emit(ev, code, signal) { + if (this.emitted[ev]) { + return false; + } + this.emitted[ev] = true; + let ret = false; + for (const fn of this.listeners[ev]) { + ret = fn(code, signal) === true || ret; + } + if (ev === 'exit') { + ret = this.emit('afterExit', code, signal) || ret; + } + return ret; + } +} +class SignalExitBase { +} +const signalExitWrap = (handler) => { + return { + onExit(cb, opts) { + return handler.onExit(cb, opts); + }, + load() { + return handler.load(); + }, + unload() { + return handler.unload(); + }, + }; +}; +class SignalExitFallback extends SignalExitBase { + onExit() { + return () => { }; + } + load() { } + unload() { } +} +class SignalExit extends SignalExitBase { + // "SIGHUP" throws an `ENOSYS` error on Windows, + // so use a supported signal instead + /* c8 ignore start */ + #hupSig = process.platform === 'win32' ? 'SIGINT' : 'SIGHUP'; + /* c8 ignore stop */ + #emitter = new Emitter(); + #process; + #originalProcessEmit; + #originalProcessReallyExit; + #sigListeners = {}; + #loaded = false; + constructor(process) { + super(); + this.#process = process; + // { : , ... } + this.#sigListeners = {}; + for (const sig of signals_js_1.signals) { + this.#sigListeners[sig] = () => { + // If there are no other listeners, an exit is coming! + // Simplest way: remove us and then re-send the signal. + // We know that this will kill the process, so we can + // safely emit now. + const listeners = this.#process.listeners(sig); + let { count } = this.#emitter; + // This is a workaround for the fact that signal-exit v3 and signal + // exit v4 are not aware of each other, and each will attempt to let + // the other handle it, so neither of them do. To correct this, we + // detect if we're the only handler *except* for previous versions + // of signal-exit, and increment by the count of listeners it has + // created. + /* c8 ignore start */ + const p = process; + if (typeof p.__signal_exit_emitter__ === 'object' && + typeof p.__signal_exit_emitter__.count === 'number') { + count += p.__signal_exit_emitter__.count; + } + /* c8 ignore stop */ + if (listeners.length === count) { + this.unload(); + const ret = this.#emitter.emit('exit', null, sig); + /* c8 ignore start */ + const s = sig === 'SIGHUP' ? this.#hupSig : sig; + if (!ret) + process.kill(process.pid, s); + /* c8 ignore stop */ + } + }; + } + this.#originalProcessReallyExit = process.reallyExit; + this.#originalProcessEmit = process.emit; + } + onExit(cb, opts) { + /* c8 ignore start */ + if (!processOk(this.#process)) { + return () => { }; + } + /* c8 ignore stop */ + if (this.#loaded === false) { + this.load(); + } + const ev = opts?.alwaysLast ? 'afterExit' : 'exit'; + this.#emitter.on(ev, cb); + return () => { + this.#emitter.removeListener(ev, cb); + if (this.#emitter.listeners['exit'].length === 0 && + this.#emitter.listeners['afterExit'].length === 0) { + this.unload(); + } + }; + } + load() { + if (this.#loaded) { + return; + } + this.#loaded = true; + // This is the number of onSignalExit's that are in play. + // It's important so that we can count the correct number of + // listeners on signals, and don't wait for the other one to + // handle it instead of us. + this.#emitter.count += 1; + for (const sig of signals_js_1.signals) { + try { + const fn = this.#sigListeners[sig]; + if (fn) + this.#process.on(sig, fn); + } + catch (_) { } + } + this.#process.emit = (ev, ...a) => { + return this.#processEmit(ev, ...a); + }; + this.#process.reallyExit = (code) => { + return this.#processReallyExit(code); + }; + } + unload() { + if (!this.#loaded) { + return; + } + this.#loaded = false; + signals_js_1.signals.forEach(sig => { + const listener = this.#sigListeners[sig]; + /* c8 ignore start */ + if (!listener) { + throw new Error('Listener not defined for signal: ' + sig); + } + /* c8 ignore stop */ + try { + this.#process.removeListener(sig, listener); + /* c8 ignore start */ + } + catch (_) { } + /* c8 ignore stop */ + }); + this.#process.emit = this.#originalProcessEmit; + this.#process.reallyExit = this.#originalProcessReallyExit; + this.#emitter.count -= 1; + } + #processReallyExit(code) { + /* c8 ignore start */ + if (!processOk(this.#process)) { + return 0; + } + this.#process.exitCode = code || 0; + /* c8 ignore stop */ + this.#emitter.emit('exit', this.#process.exitCode, null); + return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode); + } + #processEmit(ev, ...args) { + const og = this.#originalProcessEmit; + if (ev === 'exit' && processOk(this.#process)) { + if (typeof args[0] === 'number') { + this.#process.exitCode = args[0]; + /* c8 ignore start */ + } + /* c8 ignore start */ + const ret = og.call(this.#process, ev, ...args); + /* c8 ignore start */ + this.#emitter.emit('exit', this.#process.exitCode, null); + /* c8 ignore stop */ + return ret; + } + else { + return og.call(this.#process, ev, ...args); + } + } +} +const process = globalThis.process; +// wrap so that we call the method on the actual handler, without +// exporting it directly. +_a = signalExitWrap(processOk(process) ? new SignalExit(process) : new SignalExitFallback()), +/** + * Called when the process is exiting, whether via signal, explicit + * exit, or running out of stuff to do. + * + * If the global process object is not suitable for instrumentation, + * then this will be a no-op. + * + * Returns a function that may be used to unload signal-exit. + */ +exports.onExit = _a.onExit, +/** + * Load the listeners. Likely you never need to call this, unless + * doing a rather deep integration with signal-exit functionality. + * Mostly exposed for the benefit of testing. + * + * @internal + */ +exports.load = _a.load, +/** + * Unload the listeners. Likely you never need to call this, unless + * doing a rather deep integration with signal-exit functionality. + * Mostly exposed for the benefit of testing. + * + * @internal + */ +exports.unload = _a.unload; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/signal-exit/dist/cjs/index.js.map b/node_modules/signal-exit/dist/cjs/index.js.map new file mode 100644 index 0000000..528e3cc --- /dev/null +++ b/node_modules/signal-exit/dist/cjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;AAAA,iEAAiE;AACjE,+DAA+D;AAC/D,qDAAqD;AACrD,4DAA4D;AAC5D,6CAAsC;AAC7B,wFADA,oBAAO,OACA;AAQhB,MAAM,SAAS,GAAG,CAAC,OAAY,EAAwB,EAAE,CACvD,CAAC,CAAC,OAAO;IACT,OAAO,OAAO,KAAK,QAAQ;IAC3B,OAAO,OAAO,CAAC,cAAc,KAAK,UAAU;IAC5C,OAAO,OAAO,CAAC,IAAI,KAAK,UAAU;IAClC,OAAO,OAAO,CAAC,UAAU,KAAK,UAAU;IACxC,OAAO,OAAO,CAAC,SAAS,KAAK,UAAU;IACvC,OAAO,OAAO,CAAC,IAAI,KAAK,UAAU;IAClC,OAAO,OAAO,CAAC,GAAG,KAAK,QAAQ;IAC/B,OAAO,OAAO,CAAC,EAAE,KAAK,UAAU,CAAA;AAElC,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAA;AACtD,MAAM,MAAM,GAAqD,UAAU,CAAA;AAC3E,MAAM,oBAAoB,GAAG,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;AAwB/D,2BAA2B;AAC3B,MAAM,OAAO;IACX,OAAO,GAAY;QACjB,SAAS,EAAE,KAAK;QAChB,IAAI,EAAE,KAAK;KACZ,CAAA;IAED,SAAS,GAAc;QACrB,SAAS,EAAE,EAAE;QACb,IAAI,EAAE,EAAE;KACT,CAAA;IAED,KAAK,GAAW,CAAC,CAAA;IACjB,EAAE,GAAW,IAAI,CAAC,MAAM,EAAE,CAAA;IAE1B;QACE,IAAI,MAAM,CAAC,YAAY,CAAC,EAAE;YACxB,OAAO,MAAM,CAAC,YAAY,CAAC,CAAA;SAC5B;QACD,oBAAoB,CAAC,MAAM,EAAE,YAAY,EAAE;YACzC,KAAK,EAAE,IAAI;YACX,QAAQ,EAAE,KAAK;YACf,UAAU,EAAE,KAAK;YACjB,YAAY,EAAE,KAAK;SACpB,CAAC,CAAA;IACJ,CAAC;IAED,EAAE,CAAC,EAAa,EAAE,EAAW;QAC3B,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;IAC7B,CAAC;IAED,cAAc,CAAC,EAAa,EAAE,EAAW;QACvC,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,CAAA;QAC/B,MAAM,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;QAC1B,qBAAqB;QACrB,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE;YACZ,OAAM;SACP;QACD,oBAAoB;QACpB,IAAI,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE;YAChC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAA;SAChB;aAAM;YACL,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;SAClB;IACH,CAAC;IAED,IAAI,CACF,EAAa,EACb,IAA+B,EAC/B,MAA6B;QAE7B,IAAI,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE;YACpB,OAAO,KAAK,CAAA;SACb;QACD,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,GAAG,IAAI,CAAA;QACvB,IAAI,GAAG,GAAY,KAAK,CAAA;QACxB,KAAK,MAAM,EAAE,IAAI,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,EAAE;YACnC,GAAG,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,KAAK,IAAI,IAAI,GAAG,CAAA;SACvC;QACD,IAAI,EAAE,KAAK,MAAM,EAAE;YACjB,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,GAAG,CAAA;SAClD;QACD,OAAO,GAAG,CAAA;IACZ,CAAC;CACF;AAED,MAAe,cAAc;CAI5B;AAED,MAAM,cAAc,GAAG,CAA2B,OAAU,EAAE,EAAE;IAC9D,OAAO;QACL,MAAM,CAAC,EAAW,EAAE,IAA+B;YACjD,OAAO,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;QACjC,CAAC;QACD,IAAI;YACF,OAAO,OAAO,CAAC,IAAI,EAAE,CAAA;QACvB,CAAC;QACD,MAAM;YACJ,OAAO,OAAO,CAAC,MAAM,EAAE,CAAA;QACzB,CAAC;KACF,CAAA;AACH,CAAC,CAAA;AAED,MAAM,kBAAmB,SAAQ,cAAc;IAC7C,MAAM;QACJ,OAAO,GAAG,EAAE,GAAE,CAAC,CAAA;IACjB,CAAC;IACD,IAAI,KAAI,CAAC;IACT,MAAM,KAAI,CAAC;CACZ;AAED,MAAM,UAAW,SAAQ,cAAc;IACrC,gDAAgD;IAChD,oCAAoC;IACpC,qBAAqB;IACrB,OAAO,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAA;IAC5D,oBAAoB;IACpB,QAAQ,GAAG,IAAI,OAAO,EAAE,CAAA;IACxB,QAAQ,CAAW;IACnB,oBAAoB,CAAmB;IACvC,0BAA0B,CAAyB;IAEnD,aAAa,GAA2C,EAAE,CAAA;IAC1D,OAAO,GAAY,KAAK,CAAA;IAExB,YAAY,OAAkB;QAC5B,KAAK,EAAE,CAAA;QACP,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAA;QACvB,mCAAmC;QACnC,IAAI,CAAC,aAAa,GAAG,EAAE,CAAA;QACvB,KAAK,MAAM,GAAG,IAAI,oBAAO,EAAE;YACzB,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,GAAG,GAAG,EAAE;gBAC7B,sDAAsD;gBACtD,uDAAuD;gBACvD,qDAAqD;gBACrD,mBAAmB;gBACnB,MAAM,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,GAAG,CAAC,CAAA;gBAC9C,IAAI,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC,QAAQ,CAAA;gBAC7B,mEAAmE;gBACnE,oEAAoE;gBACpE,kEAAkE;gBAClE,kEAAkE;gBAClE,iEAAiE;gBACjE,WAAW;gBACX,qBAAqB;gBACrB,MAAM,CAAC,GAAG,OAET,CAAA;gBACD,IACE,OAAO,CAAC,CAAC,uBAAuB,KAAK,QAAQ;oBAC7C,OAAO,CAAC,CAAC,uBAAuB,CAAC,KAAK,KAAK,QAAQ,EACnD;oBACA,KAAK,IAAI,CAAC,CAAC,uBAAuB,CAAC,KAAK,CAAA;iBACzC;gBACD,oBAAoB;gBACpB,IAAI,SAAS,CAAC,MAAM,KAAK,KAAK,EAAE;oBAC9B,IAAI,CAAC,MAAM,EAAE,CAAA;oBACb,MAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,CAAC,CAAA;oBACjD,qBAAqB;oBACrB,MAAM,CAAC,GAAG,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAA;oBAC/C,IAAI,CAAC,GAAG;wBAAE,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,CAAA;oBACtC,oBAAoB;iBACrB;YACH,CAAC,CAAA;SACF;QAED,IAAI,CAAC,0BAA0B,GAAG,OAAO,CAAC,UAAU,CAAA;QACpD,IAAI,CAAC,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAA;IAC1C,CAAC;IAED,MAAM,CAAC,EAAW,EAAE,IAA+B;QACjD,qBAAqB;QACrB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE;YAC7B,OAAO,GAAG,EAAE,GAAE,CAAC,CAAA;SAChB;QACD,oBAAoB;QAEpB,IAAI,IAAI,CAAC,OAAO,KAAK,KAAK,EAAE;YAC1B,IAAI,CAAC,IAAI,EAAE,CAAA;SACZ;QAED,MAAM,EAAE,GAAG,IAAI,EAAE,UAAU,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM,CAAA;QAClD,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,CAAA;QACxB,OAAO,GAAG,EAAE;YACV,IAAI,CAAC,QAAQ,CAAC,cAAc,CAAC,EAAE,EAAE,EAAE,CAAC,CAAA;YACpC,IACE,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,MAAM,KAAK,CAAC;gBAC5C,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC,MAAM,KAAK,CAAC,EACjD;gBACA,IAAI,CAAC,MAAM,EAAE,CAAA;aACd;QACH,CAAC,CAAA;IACH,CAAC;IAED,IAAI;QACF,IAAI,IAAI,CAAC,OAAO,EAAE;YAChB,OAAM;SACP;QACD,IAAI,CAAC,OAAO,GAAG,IAAI,CAAA;QAEnB,yDAAyD;QACzD,4DAA4D;QAC5D,4DAA4D;QAC5D,2BAA2B;QAC3B,IAAI,CAAC,QAAQ,CAAC,KAAK,IAAI,CAAC,CAAA;QAExB,KAAK,MAAM,GAAG,IAAI,oBAAO,EAAE;YACzB,IAAI;gBACF,MAAM,EAAE,GAAG,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAA;gBAClC,IAAI,EAAE;oBAAE,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,CAAA;aAClC;YAAC,OAAO,CAAC,EAAE,GAAE;SACf;QAED,IAAI,CAAC,QAAQ,CAAC,IAAI,GAAG,CAAC,EAAU,EAAE,GAAG,CAAQ,EAAE,EAAE;YAC/C,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAA;QACpC,CAAC,CAAA;QACD,IAAI,CAAC,QAAQ,CAAC,UAAU,GAAG,CAAC,IAAgC,EAAE,EAAE;YAC9D,OAAO,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAA;QACtC,CAAC,CAAA;IACH,CAAC;IAED,MAAM;QACJ,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE;YACjB,OAAM;SACP;QACD,IAAI,CAAC,OAAO,GAAG,KAAK,CAAA;QAEpB,oBAAO,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;YACpB,MAAM,QAAQ,GAAG,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAA;YACxC,qBAAqB;YACrB,IAAI,CAAC,QAAQ,EAAE;gBACb,MAAM,IAAI,KAAK,CAAC,mCAAmC,GAAG,GAAG,CAAC,CAAA;aAC3D;YACD,oBAAoB;YACpB,IAAI;gBACF,IAAI,CAAC,QAAQ,CAAC,cAAc,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;gBAC3C,qBAAqB;aACtB;YAAC,OAAO,CAAC,EAAE,GAAE;YACd,oBAAoB;QACtB,CAAC,CAAC,CAAA;QACF,IAAI,CAAC,QAAQ,CAAC,IAAI,GAAG,IAAI,CAAC,oBAAoB,CAAA;QAC9C,IAAI,CAAC,QAAQ,CAAC,UAAU,GAAG,IAAI,CAAC,0BAA0B,CAAA;QAC1D,IAAI,CAAC,QAAQ,CAAC,KAAK,IAAI,CAAC,CAAA;IAC1B,CAAC;IAED,kBAAkB,CAAC,IAAgC;QACjD,qBAAqB;QACrB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE;YAC7B,OAAO,CAAC,CAAA;SACT;QACD,IAAI,CAAC,QAAQ,CAAC,QAAQ,GAAG,IAAI,IAAI,CAAC,CAAA;QAClC,oBAAoB;QAEpB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;QACxD,OAAO,IAAI,CAAC,0BAA0B,CAAC,IAAI,CACzC,IAAI,CAAC,QAAQ,EACb,IAAI,CAAC,QAAQ,CAAC,QAAQ,CACvB,CAAA;IACH,CAAC;IAED,YAAY,CAAC,EAAU,EAAE,GAAG,IAAW;QACrC,MAAM,EAAE,GAAG,IAAI,CAAC,oBAAoB,CAAA;QACpC,IAAI,EAAE,KAAK,MAAM,IAAI,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE;YAC7C,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ,EAAE;gBAC/B,IAAI,CAAC,QAAQ,CAAC,QAAQ,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;gBAChC,qBAAqB;aACtB;YACD,qBAAqB;YACrB,MAAM,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC,CAAA;YAC/C,qBAAqB;YACrB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;YACxD,oBAAoB;YACpB,OAAO,GAAG,CAAA;SACX;aAAM;YACL,OAAO,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC,CAAA;SAC3C;IACH,CAAC;CACF;AAED,MAAM,OAAO,GAAG,UAAU,CAAC,OAAO,CAAA;AAClC,iEAAiE;AACjE,yBAAyB;AACZ,KA6BT,cAAc,CAChB,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,kBAAkB,EAAE,CACxE;AA9BC;;;;;;;;GAQG;AACH,cAAM;AAEN;;;;;;GAMG;AACH,YAAI;AAEJ;;;;;;GAMG;AACH,cAAM,aAGP","sourcesContent":["// Note: since nyc uses this module to output coverage, any lines\n// that are in the direct sync flow of nyc's outputCoverage are\n// ignored, since we can never get coverage for them.\n// grab a reference to node's real process object right away\nimport { signals } from './signals.js'\nexport { signals }\n\n// just a loosened process type so we can do some evil things\ntype ProcessRE = NodeJS.Process & {\n reallyExit: (code?: number | undefined | null) => any\n emit: (ev: string, ...a: any[]) => any\n}\n\nconst processOk = (process: any): process is ProcessRE =>\n !!process &&\n typeof process === 'object' &&\n typeof process.removeListener === 'function' &&\n typeof process.emit === 'function' &&\n typeof process.reallyExit === 'function' &&\n typeof process.listeners === 'function' &&\n typeof process.kill === 'function' &&\n typeof process.pid === 'number' &&\n typeof process.on === 'function'\n\nconst kExitEmitter = Symbol.for('signal-exit emitter')\nconst global: typeof globalThis & { [kExitEmitter]?: Emitter } = globalThis\nconst ObjectDefineProperty = Object.defineProperty.bind(Object)\n\n/**\n * A function that takes an exit code and signal as arguments\n *\n * In the case of signal exits *only*, a return value of true\n * will indicate that the signal is being handled, and we should\n * not synthetically exit with the signal we received. Regardless\n * of the handler return value, the handler is unloaded when an\n * otherwise fatal signal is received, so you get exactly 1 shot\n * at it, unless you add another onExit handler at that point.\n *\n * In the case of numeric code exits, we may already have committed\n * to exiting the process, for example via a fatal exception or\n * unhandled promise rejection, so it is impossible to stop safely.\n */\nexport type Handler = (\n code: number | null | undefined,\n signal: NodeJS.Signals | null\n) => true | void\ntype ExitEvent = 'afterExit' | 'exit'\ntype Emitted = { [k in ExitEvent]: boolean }\ntype Listeners = { [k in ExitEvent]: Handler[] }\n\n// teeny special purpose ee\nclass Emitter {\n emitted: Emitted = {\n afterExit: false,\n exit: false,\n }\n\n listeners: Listeners = {\n afterExit: [],\n exit: [],\n }\n\n count: number = 0\n id: number = Math.random()\n\n constructor() {\n if (global[kExitEmitter]) {\n return global[kExitEmitter]\n }\n ObjectDefineProperty(global, kExitEmitter, {\n value: this,\n writable: false,\n enumerable: false,\n configurable: false,\n })\n }\n\n on(ev: ExitEvent, fn: Handler) {\n this.listeners[ev].push(fn)\n }\n\n removeListener(ev: ExitEvent, fn: Handler) {\n const list = this.listeners[ev]\n const i = list.indexOf(fn)\n /* c8 ignore start */\n if (i === -1) {\n return\n }\n /* c8 ignore stop */\n if (i === 0 && list.length === 1) {\n list.length = 0\n } else {\n list.splice(i, 1)\n }\n }\n\n emit(\n ev: ExitEvent,\n code: number | null | undefined,\n signal: NodeJS.Signals | null\n ): boolean {\n if (this.emitted[ev]) {\n return false\n }\n this.emitted[ev] = true\n let ret: boolean = false\n for (const fn of this.listeners[ev]) {\n ret = fn(code, signal) === true || ret\n }\n if (ev === 'exit') {\n ret = this.emit('afterExit', code, signal) || ret\n }\n return ret\n }\n}\n\nabstract class SignalExitBase {\n abstract onExit(cb: Handler, opts?: { alwaysLast?: boolean }): () => void\n abstract load(): void\n abstract unload(): void\n}\n\nconst signalExitWrap = (handler: T) => {\n return {\n onExit(cb: Handler, opts?: { alwaysLast?: boolean }) {\n return handler.onExit(cb, opts)\n },\n load() {\n return handler.load()\n },\n unload() {\n return handler.unload()\n },\n }\n}\n\nclass SignalExitFallback extends SignalExitBase {\n onExit() {\n return () => {}\n }\n load() {}\n unload() {}\n}\n\nclass SignalExit extends SignalExitBase {\n // \"SIGHUP\" throws an `ENOSYS` error on Windows,\n // so use a supported signal instead\n /* c8 ignore start */\n #hupSig = process.platform === 'win32' ? 'SIGINT' : 'SIGHUP'\n /* c8 ignore stop */\n #emitter = new Emitter()\n #process: ProcessRE\n #originalProcessEmit: ProcessRE['emit']\n #originalProcessReallyExit: ProcessRE['reallyExit']\n\n #sigListeners: { [k in NodeJS.Signals]?: () => void } = {}\n #loaded: boolean = false\n\n constructor(process: ProcessRE) {\n super()\n this.#process = process\n // { : , ... }\n this.#sigListeners = {}\n for (const sig of signals) {\n this.#sigListeners[sig] = () => {\n // If there are no other listeners, an exit is coming!\n // Simplest way: remove us and then re-send the signal.\n // We know that this will kill the process, so we can\n // safely emit now.\n const listeners = this.#process.listeners(sig)\n let { count } = this.#emitter\n // This is a workaround for the fact that signal-exit v3 and signal\n // exit v4 are not aware of each other, and each will attempt to let\n // the other handle it, so neither of them do. To correct this, we\n // detect if we're the only handler *except* for previous versions\n // of signal-exit, and increment by the count of listeners it has\n // created.\n /* c8 ignore start */\n const p = process as unknown as {\n __signal_exit_emitter__?: { count: number }\n }\n if (\n typeof p.__signal_exit_emitter__ === 'object' &&\n typeof p.__signal_exit_emitter__.count === 'number'\n ) {\n count += p.__signal_exit_emitter__.count\n }\n /* c8 ignore stop */\n if (listeners.length === count) {\n this.unload()\n const ret = this.#emitter.emit('exit', null, sig)\n /* c8 ignore start */\n const s = sig === 'SIGHUP' ? this.#hupSig : sig\n if (!ret) process.kill(process.pid, s)\n /* c8 ignore stop */\n }\n }\n }\n\n this.#originalProcessReallyExit = process.reallyExit\n this.#originalProcessEmit = process.emit\n }\n\n onExit(cb: Handler, opts?: { alwaysLast?: boolean }) {\n /* c8 ignore start */\n if (!processOk(this.#process)) {\n return () => {}\n }\n /* c8 ignore stop */\n\n if (this.#loaded === false) {\n this.load()\n }\n\n const ev = opts?.alwaysLast ? 'afterExit' : 'exit'\n this.#emitter.on(ev, cb)\n return () => {\n this.#emitter.removeListener(ev, cb)\n if (\n this.#emitter.listeners['exit'].length === 0 &&\n this.#emitter.listeners['afterExit'].length === 0\n ) {\n this.unload()\n }\n }\n }\n\n load() {\n if (this.#loaded) {\n return\n }\n this.#loaded = true\n\n // This is the number of onSignalExit's that are in play.\n // It's important so that we can count the correct number of\n // listeners on signals, and don't wait for the other one to\n // handle it instead of us.\n this.#emitter.count += 1\n\n for (const sig of signals) {\n try {\n const fn = this.#sigListeners[sig]\n if (fn) this.#process.on(sig, fn)\n } catch (_) {}\n }\n\n this.#process.emit = (ev: string, ...a: any[]) => {\n return this.#processEmit(ev, ...a)\n }\n this.#process.reallyExit = (code?: number | null | undefined) => {\n return this.#processReallyExit(code)\n }\n }\n\n unload() {\n if (!this.#loaded) {\n return\n }\n this.#loaded = false\n\n signals.forEach(sig => {\n const listener = this.#sigListeners[sig]\n /* c8 ignore start */\n if (!listener) {\n throw new Error('Listener not defined for signal: ' + sig)\n }\n /* c8 ignore stop */\n try {\n this.#process.removeListener(sig, listener)\n /* c8 ignore start */\n } catch (_) {}\n /* c8 ignore stop */\n })\n this.#process.emit = this.#originalProcessEmit\n this.#process.reallyExit = this.#originalProcessReallyExit\n this.#emitter.count -= 1\n }\n\n #processReallyExit(code?: number | null | undefined) {\n /* c8 ignore start */\n if (!processOk(this.#process)) {\n return 0\n }\n this.#process.exitCode = code || 0\n /* c8 ignore stop */\n\n this.#emitter.emit('exit', this.#process.exitCode, null)\n return this.#originalProcessReallyExit.call(\n this.#process,\n this.#process.exitCode\n )\n }\n\n #processEmit(ev: string, ...args: any[]): any {\n const og = this.#originalProcessEmit\n if (ev === 'exit' && processOk(this.#process)) {\n if (typeof args[0] === 'number') {\n this.#process.exitCode = args[0]\n /* c8 ignore start */\n }\n /* c8 ignore start */\n const ret = og.call(this.#process, ev, ...args)\n /* c8 ignore start */\n this.#emitter.emit('exit', this.#process.exitCode, null)\n /* c8 ignore stop */\n return ret\n } else {\n return og.call(this.#process, ev, ...args)\n }\n }\n}\n\nconst process = globalThis.process\n// wrap so that we call the method on the actual handler, without\n// exporting it directly.\nexport const {\n /**\n * Called when the process is exiting, whether via signal, explicit\n * exit, or running out of stuff to do.\n *\n * If the global process object is not suitable for instrumentation,\n * then this will be a no-op.\n *\n * Returns a function that may be used to unload signal-exit.\n */\n onExit,\n\n /**\n * Load the listeners. Likely you never need to call this, unless\n * doing a rather deep integration with signal-exit functionality.\n * Mostly exposed for the benefit of testing.\n *\n * @internal\n */\n load,\n\n /**\n * Unload the listeners. Likely you never need to call this, unless\n * doing a rather deep integration with signal-exit functionality.\n * Mostly exposed for the benefit of testing.\n *\n * @internal\n */\n unload,\n} = signalExitWrap(\n processOk(process) ? new SignalExit(process) : new SignalExitFallback()\n)\n"]} \ No newline at end of file diff --git a/node_modules/signal-exit/dist/cjs/package.json b/node_modules/signal-exit/dist/cjs/package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/node_modules/signal-exit/dist/cjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/signal-exit/dist/cjs/signals.d.ts b/node_modules/signal-exit/dist/cjs/signals.d.ts new file mode 100644 index 0000000..3f01ef0 --- /dev/null +++ b/node_modules/signal-exit/dist/cjs/signals.d.ts @@ -0,0 +1,29 @@ +/// +/** + * This is not the set of all possible signals. + * + * It IS, however, the set of all signals that trigger + * an exit on either Linux or BSD systems. Linux is a + * superset of the signal names supported on BSD, and + * the unknown signals just fail to register, so we can + * catch that easily enough. + * + * Windows signals are a different set, since there are + * signals that terminate Windows processes, but don't + * terminate (or don't even exist) on Posix systems. + * + * Don't bother with SIGKILL. It's uncatchable, which + * means that we can't fire any callbacks anyway. + * + * If a user does happen to register a handler on a non- + * fatal signal like SIGWINCH or something, and then + * exit, it'll end up firing `process.emit('exit')`, so + * the handler will be fired anyway. + * + * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised + * artificially, inherently leave the process in a + * state from which it is not safe to try and enter JS + * listeners. + */ +export declare const signals: NodeJS.Signals[]; +//# sourceMappingURL=signals.d.ts.map \ No newline at end of file diff --git a/node_modules/signal-exit/dist/cjs/signals.d.ts.map b/node_modules/signal-exit/dist/cjs/signals.d.ts.map new file mode 100644 index 0000000..891fe1e --- /dev/null +++ b/node_modules/signal-exit/dist/cjs/signals.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"signals.d.ts","sourceRoot":"","sources":["../../src/signals.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,OAAO,EAAE,MAAM,CAAC,OAAO,EAAO,CAAA"} \ No newline at end of file diff --git a/node_modules/signal-exit/dist/cjs/signals.js b/node_modules/signal-exit/dist/cjs/signals.js new file mode 100644 index 0000000..28afc50 --- /dev/null +++ b/node_modules/signal-exit/dist/cjs/signals.js @@ -0,0 +1,42 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.signals = void 0; +/** + * This is not the set of all possible signals. + * + * It IS, however, the set of all signals that trigger + * an exit on either Linux or BSD systems. Linux is a + * superset of the signal names supported on BSD, and + * the unknown signals just fail to register, so we can + * catch that easily enough. + * + * Windows signals are a different set, since there are + * signals that terminate Windows processes, but don't + * terminate (or don't even exist) on Posix systems. + * + * Don't bother with SIGKILL. It's uncatchable, which + * means that we can't fire any callbacks anyway. + * + * If a user does happen to register a handler on a non- + * fatal signal like SIGWINCH or something, and then + * exit, it'll end up firing `process.emit('exit')`, so + * the handler will be fired anyway. + * + * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised + * artificially, inherently leave the process in a + * state from which it is not safe to try and enter JS + * listeners. + */ +exports.signals = []; +exports.signals.push('SIGHUP', 'SIGINT', 'SIGTERM'); +if (process.platform !== 'win32') { + exports.signals.push('SIGALRM', 'SIGABRT', 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT' + // should detect profiler and enable/disable accordingly. + // see #21 + // 'SIGPROF' + ); +} +if (process.platform === 'linux') { + exports.signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT'); +} +//# sourceMappingURL=signals.js.map \ No newline at end of file diff --git a/node_modules/signal-exit/dist/cjs/signals.js.map b/node_modules/signal-exit/dist/cjs/signals.js.map new file mode 100644 index 0000000..78c613f --- /dev/null +++ b/node_modules/signal-exit/dist/cjs/signals.js.map @@ -0,0 +1 @@ +{"version":3,"file":"signals.js","sourceRoot":"","sources":["../../src/signals.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACU,QAAA,OAAO,GAAqB,EAAE,CAAA;AAC3C,eAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAA;AAE3C,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;IAChC,eAAO,CAAC,IAAI,CACV,SAAS,EACT,SAAS,EACT,WAAW,EACX,SAAS,EACT,SAAS,EACT,SAAS,EACT,SAAS,EACT,QAAQ,EACR,SAAS,EACT,QAAQ;IACR,yDAAyD;IACzD,UAAU;IACV,YAAY;KACb,CAAA;CACF;AAED,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;IAChC,eAAO,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAA;CACxD","sourcesContent":["/**\n * This is not the set of all possible signals.\n *\n * It IS, however, the set of all signals that trigger\n * an exit on either Linux or BSD systems. Linux is a\n * superset of the signal names supported on BSD, and\n * the unknown signals just fail to register, so we can\n * catch that easily enough.\n *\n * Windows signals are a different set, since there are\n * signals that terminate Windows processes, but don't\n * terminate (or don't even exist) on Posix systems.\n *\n * Don't bother with SIGKILL. It's uncatchable, which\n * means that we can't fire any callbacks anyway.\n *\n * If a user does happen to register a handler on a non-\n * fatal signal like SIGWINCH or something, and then\n * exit, it'll end up firing `process.emit('exit')`, so\n * the handler will be fired anyway.\n *\n * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised\n * artificially, inherently leave the process in a\n * state from which it is not safe to try and enter JS\n * listeners.\n */\nexport const signals: NodeJS.Signals[] = []\nsignals.push('SIGHUP', 'SIGINT', 'SIGTERM')\n\nif (process.platform !== 'win32') {\n signals.push(\n 'SIGALRM',\n 'SIGABRT',\n 'SIGVTALRM',\n 'SIGXCPU',\n 'SIGXFSZ',\n 'SIGUSR2',\n 'SIGTRAP',\n 'SIGSYS',\n 'SIGQUIT',\n 'SIGIOT'\n // should detect profiler and enable/disable accordingly.\n // see #21\n // 'SIGPROF'\n )\n}\n\nif (process.platform === 'linux') {\n signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT')\n}\n"]} \ No newline at end of file diff --git a/node_modules/signal-exit/dist/mjs/browser.d.ts b/node_modules/signal-exit/dist/mjs/browser.d.ts new file mode 100644 index 0000000..90f2e3f --- /dev/null +++ b/node_modules/signal-exit/dist/mjs/browser.d.ts @@ -0,0 +1,12 @@ +/** + * This is a browser shim that provides the same functional interface + * as the main node export, but it does nothing. + * @module + */ +import type { Handler } from './index.js'; +export declare const onExit: (cb: Handler, opts: { + alwaysLast?: boolean; +}) => () => void; +export declare const load: () => void; +export declare const unload: () => void; +//# sourceMappingURL=browser.d.ts.map \ No newline at end of file diff --git a/node_modules/signal-exit/dist/mjs/browser.d.ts.map b/node_modules/signal-exit/dist/mjs/browser.d.ts.map new file mode 100644 index 0000000..aacc1d3 --- /dev/null +++ b/node_modules/signal-exit/dist/mjs/browser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../../src/browser.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AACzC,eAAO,MAAM,MAAM,EAAE,CACnB,EAAE,EAAE,OAAO,EACX,IAAI,EAAE;IAAE,UAAU,CAAC,EAAE,OAAO,CAAA;CAAE,KAC3B,MAAM,IAAqB,CAAA;AAChC,eAAO,MAAM,IAAI,YAAW,CAAA;AAC5B,eAAO,MAAM,MAAM,YAAW,CAAA"} \ No newline at end of file diff --git a/node_modules/signal-exit/dist/mjs/browser.js b/node_modules/signal-exit/dist/mjs/browser.js new file mode 100644 index 0000000..9c5f9b9 --- /dev/null +++ b/node_modules/signal-exit/dist/mjs/browser.js @@ -0,0 +1,4 @@ +export const onExit = () => () => { }; +export const load = () => { }; +export const unload = () => { }; +//# sourceMappingURL=browser.js.map \ No newline at end of file diff --git a/node_modules/signal-exit/dist/mjs/browser.js.map b/node_modules/signal-exit/dist/mjs/browser.js.map new file mode 100644 index 0000000..b3ff303 --- /dev/null +++ b/node_modules/signal-exit/dist/mjs/browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"browser.js","sourceRoot":"","sources":["../../src/browser.ts"],"names":[],"mappings":"AAMA,MAAM,CAAC,MAAM,MAAM,GAGD,GAAG,EAAE,CAAC,GAAG,EAAE,GAAE,CAAC,CAAA;AAChC,MAAM,CAAC,MAAM,IAAI,GAAG,GAAG,EAAE,GAAE,CAAC,CAAA;AAC5B,MAAM,CAAC,MAAM,MAAM,GAAG,GAAG,EAAE,GAAE,CAAC,CAAA","sourcesContent":["/**\n * This is a browser shim that provides the same functional interface\n * as the main node export, but it does nothing.\n * @module\n */\nimport type { Handler } from './index.js'\nexport const onExit: (\n cb: Handler,\n opts: { alwaysLast?: boolean }\n) => () => void = () => () => {}\nexport const load = () => {}\nexport const unload = () => {}\n"]} \ No newline at end of file diff --git a/node_modules/signal-exit/dist/mjs/index.d.ts b/node_modules/signal-exit/dist/mjs/index.d.ts new file mode 100644 index 0000000..cabe9cf --- /dev/null +++ b/node_modules/signal-exit/dist/mjs/index.d.ts @@ -0,0 +1,48 @@ +/// +import { signals } from './signals.js'; +export { signals }; +/** + * A function that takes an exit code and signal as arguments + * + * In the case of signal exits *only*, a return value of true + * will indicate that the signal is being handled, and we should + * not synthetically exit with the signal we received. Regardless + * of the handler return value, the handler is unloaded when an + * otherwise fatal signal is received, so you get exactly 1 shot + * at it, unless you add another onExit handler at that point. + * + * In the case of numeric code exits, we may already have committed + * to exiting the process, for example via a fatal exception or + * unhandled promise rejection, so it is impossible to stop safely. + */ +export type Handler = (code: number | null | undefined, signal: NodeJS.Signals | null) => true | void; +export declare const +/** + * Called when the process is exiting, whether via signal, explicit + * exit, or running out of stuff to do. + * + * If the global process object is not suitable for instrumentation, + * then this will be a no-op. + * + * Returns a function that may be used to unload signal-exit. + */ +onExit: (cb: Handler, opts?: { + alwaysLast?: boolean | undefined; +} | undefined) => () => void, +/** + * Load the listeners. Likely you never need to call this, unless + * doing a rather deep integration with signal-exit functionality. + * Mostly exposed for the benefit of testing. + * + * @internal + */ +load: () => void, +/** + * Unload the listeners. Likely you never need to call this, unless + * doing a rather deep integration with signal-exit functionality. + * Mostly exposed for the benefit of testing. + * + * @internal + */ +unload: () => void; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/signal-exit/dist/mjs/index.d.ts.map b/node_modules/signal-exit/dist/mjs/index.d.ts.map new file mode 100644 index 0000000..f84594e --- /dev/null +++ b/node_modules/signal-exit/dist/mjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAIA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,OAAO,EAAE,CAAA;AAuBlB;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,OAAO,GAAG,CACpB,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAC/B,MAAM,EAAE,MAAM,CAAC,OAAO,GAAG,IAAI,KAC1B,IAAI,GAAG,IAAI,CAAA;AA8QhB,eAAO;AACL;;;;;;;;GAQG;AACH,MAAM,OAzMO,OAAO;;wBAPiD,IAAI;AAkNzE;;;;;;GAMG;AACH,IAAI;AAEJ;;;;;;GAMG;AACH,MAAM,YAGP,CAAA"} \ No newline at end of file diff --git a/node_modules/signal-exit/dist/mjs/index.js b/node_modules/signal-exit/dist/mjs/index.js new file mode 100644 index 0000000..4a78bad --- /dev/null +++ b/node_modules/signal-exit/dist/mjs/index.js @@ -0,0 +1,275 @@ +// Note: since nyc uses this module to output coverage, any lines +// that are in the direct sync flow of nyc's outputCoverage are +// ignored, since we can never get coverage for them. +// grab a reference to node's real process object right away +import { signals } from './signals.js'; +export { signals }; +const processOk = (process) => !!process && + typeof process === 'object' && + typeof process.removeListener === 'function' && + typeof process.emit === 'function' && + typeof process.reallyExit === 'function' && + typeof process.listeners === 'function' && + typeof process.kill === 'function' && + typeof process.pid === 'number' && + typeof process.on === 'function'; +const kExitEmitter = Symbol.for('signal-exit emitter'); +const global = globalThis; +const ObjectDefineProperty = Object.defineProperty.bind(Object); +// teeny special purpose ee +class Emitter { + emitted = { + afterExit: false, + exit: false, + }; + listeners = { + afterExit: [], + exit: [], + }; + count = 0; + id = Math.random(); + constructor() { + if (global[kExitEmitter]) { + return global[kExitEmitter]; + } + ObjectDefineProperty(global, kExitEmitter, { + value: this, + writable: false, + enumerable: false, + configurable: false, + }); + } + on(ev, fn) { + this.listeners[ev].push(fn); + } + removeListener(ev, fn) { + const list = this.listeners[ev]; + const i = list.indexOf(fn); + /* c8 ignore start */ + if (i === -1) { + return; + } + /* c8 ignore stop */ + if (i === 0 && list.length === 1) { + list.length = 0; + } + else { + list.splice(i, 1); + } + } + emit(ev, code, signal) { + if (this.emitted[ev]) { + return false; + } + this.emitted[ev] = true; + let ret = false; + for (const fn of this.listeners[ev]) { + ret = fn(code, signal) === true || ret; + } + if (ev === 'exit') { + ret = this.emit('afterExit', code, signal) || ret; + } + return ret; + } +} +class SignalExitBase { +} +const signalExitWrap = (handler) => { + return { + onExit(cb, opts) { + return handler.onExit(cb, opts); + }, + load() { + return handler.load(); + }, + unload() { + return handler.unload(); + }, + }; +}; +class SignalExitFallback extends SignalExitBase { + onExit() { + return () => { }; + } + load() { } + unload() { } +} +class SignalExit extends SignalExitBase { + // "SIGHUP" throws an `ENOSYS` error on Windows, + // so use a supported signal instead + /* c8 ignore start */ + #hupSig = process.platform === 'win32' ? 'SIGINT' : 'SIGHUP'; + /* c8 ignore stop */ + #emitter = new Emitter(); + #process; + #originalProcessEmit; + #originalProcessReallyExit; + #sigListeners = {}; + #loaded = false; + constructor(process) { + super(); + this.#process = process; + // { : , ... } + this.#sigListeners = {}; + for (const sig of signals) { + this.#sigListeners[sig] = () => { + // If there are no other listeners, an exit is coming! + // Simplest way: remove us and then re-send the signal. + // We know that this will kill the process, so we can + // safely emit now. + const listeners = this.#process.listeners(sig); + let { count } = this.#emitter; + // This is a workaround for the fact that signal-exit v3 and signal + // exit v4 are not aware of each other, and each will attempt to let + // the other handle it, so neither of them do. To correct this, we + // detect if we're the only handler *except* for previous versions + // of signal-exit, and increment by the count of listeners it has + // created. + /* c8 ignore start */ + const p = process; + if (typeof p.__signal_exit_emitter__ === 'object' && + typeof p.__signal_exit_emitter__.count === 'number') { + count += p.__signal_exit_emitter__.count; + } + /* c8 ignore stop */ + if (listeners.length === count) { + this.unload(); + const ret = this.#emitter.emit('exit', null, sig); + /* c8 ignore start */ + const s = sig === 'SIGHUP' ? this.#hupSig : sig; + if (!ret) + process.kill(process.pid, s); + /* c8 ignore stop */ + } + }; + } + this.#originalProcessReallyExit = process.reallyExit; + this.#originalProcessEmit = process.emit; + } + onExit(cb, opts) { + /* c8 ignore start */ + if (!processOk(this.#process)) { + return () => { }; + } + /* c8 ignore stop */ + if (this.#loaded === false) { + this.load(); + } + const ev = opts?.alwaysLast ? 'afterExit' : 'exit'; + this.#emitter.on(ev, cb); + return () => { + this.#emitter.removeListener(ev, cb); + if (this.#emitter.listeners['exit'].length === 0 && + this.#emitter.listeners['afterExit'].length === 0) { + this.unload(); + } + }; + } + load() { + if (this.#loaded) { + return; + } + this.#loaded = true; + // This is the number of onSignalExit's that are in play. + // It's important so that we can count the correct number of + // listeners on signals, and don't wait for the other one to + // handle it instead of us. + this.#emitter.count += 1; + for (const sig of signals) { + try { + const fn = this.#sigListeners[sig]; + if (fn) + this.#process.on(sig, fn); + } + catch (_) { } + } + this.#process.emit = (ev, ...a) => { + return this.#processEmit(ev, ...a); + }; + this.#process.reallyExit = (code) => { + return this.#processReallyExit(code); + }; + } + unload() { + if (!this.#loaded) { + return; + } + this.#loaded = false; + signals.forEach(sig => { + const listener = this.#sigListeners[sig]; + /* c8 ignore start */ + if (!listener) { + throw new Error('Listener not defined for signal: ' + sig); + } + /* c8 ignore stop */ + try { + this.#process.removeListener(sig, listener); + /* c8 ignore start */ + } + catch (_) { } + /* c8 ignore stop */ + }); + this.#process.emit = this.#originalProcessEmit; + this.#process.reallyExit = this.#originalProcessReallyExit; + this.#emitter.count -= 1; + } + #processReallyExit(code) { + /* c8 ignore start */ + if (!processOk(this.#process)) { + return 0; + } + this.#process.exitCode = code || 0; + /* c8 ignore stop */ + this.#emitter.emit('exit', this.#process.exitCode, null); + return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode); + } + #processEmit(ev, ...args) { + const og = this.#originalProcessEmit; + if (ev === 'exit' && processOk(this.#process)) { + if (typeof args[0] === 'number') { + this.#process.exitCode = args[0]; + /* c8 ignore start */ + } + /* c8 ignore start */ + const ret = og.call(this.#process, ev, ...args); + /* c8 ignore start */ + this.#emitter.emit('exit', this.#process.exitCode, null); + /* c8 ignore stop */ + return ret; + } + else { + return og.call(this.#process, ev, ...args); + } + } +} +const process = globalThis.process; +// wrap so that we call the method on the actual handler, without +// exporting it directly. +export const { +/** + * Called when the process is exiting, whether via signal, explicit + * exit, or running out of stuff to do. + * + * If the global process object is not suitable for instrumentation, + * then this will be a no-op. + * + * Returns a function that may be used to unload signal-exit. + */ +onExit, +/** + * Load the listeners. Likely you never need to call this, unless + * doing a rather deep integration with signal-exit functionality. + * Mostly exposed for the benefit of testing. + * + * @internal + */ +load, +/** + * Unload the listeners. Likely you never need to call this, unless + * doing a rather deep integration with signal-exit functionality. + * Mostly exposed for the benefit of testing. + * + * @internal + */ +unload, } = signalExitWrap(processOk(process) ? new SignalExit(process) : new SignalExitFallback()); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/signal-exit/dist/mjs/index.js.map b/node_modules/signal-exit/dist/mjs/index.js.map new file mode 100644 index 0000000..3a7b76d --- /dev/null +++ b/node_modules/signal-exit/dist/mjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,iEAAiE;AACjE,+DAA+D;AAC/D,qDAAqD;AACrD,4DAA4D;AAC5D,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,OAAO,EAAE,CAAA;AAQlB,MAAM,SAAS,GAAG,CAAC,OAAY,EAAwB,EAAE,CACvD,CAAC,CAAC,OAAO;IACT,OAAO,OAAO,KAAK,QAAQ;IAC3B,OAAO,OAAO,CAAC,cAAc,KAAK,UAAU;IAC5C,OAAO,OAAO,CAAC,IAAI,KAAK,UAAU;IAClC,OAAO,OAAO,CAAC,UAAU,KAAK,UAAU;IACxC,OAAO,OAAO,CAAC,SAAS,KAAK,UAAU;IACvC,OAAO,OAAO,CAAC,IAAI,KAAK,UAAU;IAClC,OAAO,OAAO,CAAC,GAAG,KAAK,QAAQ;IAC/B,OAAO,OAAO,CAAC,EAAE,KAAK,UAAU,CAAA;AAElC,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAA;AACtD,MAAM,MAAM,GAAqD,UAAU,CAAA;AAC3E,MAAM,oBAAoB,GAAG,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;AAwB/D,2BAA2B;AAC3B,MAAM,OAAO;IACX,OAAO,GAAY;QACjB,SAAS,EAAE,KAAK;QAChB,IAAI,EAAE,KAAK;KACZ,CAAA;IAED,SAAS,GAAc;QACrB,SAAS,EAAE,EAAE;QACb,IAAI,EAAE,EAAE;KACT,CAAA;IAED,KAAK,GAAW,CAAC,CAAA;IACjB,EAAE,GAAW,IAAI,CAAC,MAAM,EAAE,CAAA;IAE1B;QACE,IAAI,MAAM,CAAC,YAAY,CAAC,EAAE;YACxB,OAAO,MAAM,CAAC,YAAY,CAAC,CAAA;SAC5B;QACD,oBAAoB,CAAC,MAAM,EAAE,YAAY,EAAE;YACzC,KAAK,EAAE,IAAI;YACX,QAAQ,EAAE,KAAK;YACf,UAAU,EAAE,KAAK;YACjB,YAAY,EAAE,KAAK;SACpB,CAAC,CAAA;IACJ,CAAC;IAED,EAAE,CAAC,EAAa,EAAE,EAAW;QAC3B,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;IAC7B,CAAC;IAED,cAAc,CAAC,EAAa,EAAE,EAAW;QACvC,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,CAAA;QAC/B,MAAM,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;QAC1B,qBAAqB;QACrB,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE;YACZ,OAAM;SACP;QACD,oBAAoB;QACpB,IAAI,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE;YAChC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAA;SAChB;aAAM;YACL,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;SAClB;IACH,CAAC;IAED,IAAI,CACF,EAAa,EACb,IAA+B,EAC/B,MAA6B;QAE7B,IAAI,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE;YACpB,OAAO,KAAK,CAAA;SACb;QACD,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,GAAG,IAAI,CAAA;QACvB,IAAI,GAAG,GAAY,KAAK,CAAA;QACxB,KAAK,MAAM,EAAE,IAAI,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,EAAE;YACnC,GAAG,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,KAAK,IAAI,IAAI,GAAG,CAAA;SACvC;QACD,IAAI,EAAE,KAAK,MAAM,EAAE;YACjB,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,GAAG,CAAA;SAClD;QACD,OAAO,GAAG,CAAA;IACZ,CAAC;CACF;AAED,MAAe,cAAc;CAI5B;AAED,MAAM,cAAc,GAAG,CAA2B,OAAU,EAAE,EAAE;IAC9D,OAAO;QACL,MAAM,CAAC,EAAW,EAAE,IAA+B;YACjD,OAAO,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;QACjC,CAAC;QACD,IAAI;YACF,OAAO,OAAO,CAAC,IAAI,EAAE,CAAA;QACvB,CAAC;QACD,MAAM;YACJ,OAAO,OAAO,CAAC,MAAM,EAAE,CAAA;QACzB,CAAC;KACF,CAAA;AACH,CAAC,CAAA;AAED,MAAM,kBAAmB,SAAQ,cAAc;IAC7C,MAAM;QACJ,OAAO,GAAG,EAAE,GAAE,CAAC,CAAA;IACjB,CAAC;IACD,IAAI,KAAI,CAAC;IACT,MAAM,KAAI,CAAC;CACZ;AAED,MAAM,UAAW,SAAQ,cAAc;IACrC,gDAAgD;IAChD,oCAAoC;IACpC,qBAAqB;IACrB,OAAO,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAA;IAC5D,oBAAoB;IACpB,QAAQ,GAAG,IAAI,OAAO,EAAE,CAAA;IACxB,QAAQ,CAAW;IACnB,oBAAoB,CAAmB;IACvC,0BAA0B,CAAyB;IAEnD,aAAa,GAA2C,EAAE,CAAA;IAC1D,OAAO,GAAY,KAAK,CAAA;IAExB,YAAY,OAAkB;QAC5B,KAAK,EAAE,CAAA;QACP,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAA;QACvB,mCAAmC;QACnC,IAAI,CAAC,aAAa,GAAG,EAAE,CAAA;QACvB,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE;YACzB,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,GAAG,GAAG,EAAE;gBAC7B,sDAAsD;gBACtD,uDAAuD;gBACvD,qDAAqD;gBACrD,mBAAmB;gBACnB,MAAM,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,GAAG,CAAC,CAAA;gBAC9C,IAAI,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC,QAAQ,CAAA;gBAC7B,mEAAmE;gBACnE,oEAAoE;gBACpE,kEAAkE;gBAClE,kEAAkE;gBAClE,iEAAiE;gBACjE,WAAW;gBACX,qBAAqB;gBACrB,MAAM,CAAC,GAAG,OAET,CAAA;gBACD,IACE,OAAO,CAAC,CAAC,uBAAuB,KAAK,QAAQ;oBAC7C,OAAO,CAAC,CAAC,uBAAuB,CAAC,KAAK,KAAK,QAAQ,EACnD;oBACA,KAAK,IAAI,CAAC,CAAC,uBAAuB,CAAC,KAAK,CAAA;iBACzC;gBACD,oBAAoB;gBACpB,IAAI,SAAS,CAAC,MAAM,KAAK,KAAK,EAAE;oBAC9B,IAAI,CAAC,MAAM,EAAE,CAAA;oBACb,MAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,GAAG,CAAC,CAAA;oBACjD,qBAAqB;oBACrB,MAAM,CAAC,GAAG,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAA;oBAC/C,IAAI,CAAC,GAAG;wBAAE,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,CAAA;oBACtC,oBAAoB;iBACrB;YACH,CAAC,CAAA;SACF;QAED,IAAI,CAAC,0BAA0B,GAAG,OAAO,CAAC,UAAU,CAAA;QACpD,IAAI,CAAC,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAA;IAC1C,CAAC;IAED,MAAM,CAAC,EAAW,EAAE,IAA+B;QACjD,qBAAqB;QACrB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE;YAC7B,OAAO,GAAG,EAAE,GAAE,CAAC,CAAA;SAChB;QACD,oBAAoB;QAEpB,IAAI,IAAI,CAAC,OAAO,KAAK,KAAK,EAAE;YAC1B,IAAI,CAAC,IAAI,EAAE,CAAA;SACZ;QAED,MAAM,EAAE,GAAG,IAAI,EAAE,UAAU,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM,CAAA;QAClD,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,CAAA;QACxB,OAAO,GAAG,EAAE;YACV,IAAI,CAAC,QAAQ,CAAC,cAAc,CAAC,EAAE,EAAE,EAAE,CAAC,CAAA;YACpC,IACE,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,MAAM,KAAK,CAAC;gBAC5C,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC,MAAM,KAAK,CAAC,EACjD;gBACA,IAAI,CAAC,MAAM,EAAE,CAAA;aACd;QACH,CAAC,CAAA;IACH,CAAC;IAED,IAAI;QACF,IAAI,IAAI,CAAC,OAAO,EAAE;YAChB,OAAM;SACP;QACD,IAAI,CAAC,OAAO,GAAG,IAAI,CAAA;QAEnB,yDAAyD;QACzD,4DAA4D;QAC5D,4DAA4D;QAC5D,2BAA2B;QAC3B,IAAI,CAAC,QAAQ,CAAC,KAAK,IAAI,CAAC,CAAA;QAExB,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE;YACzB,IAAI;gBACF,MAAM,EAAE,GAAG,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAA;gBAClC,IAAI,EAAE;oBAAE,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,CAAA;aAClC;YAAC,OAAO,CAAC,EAAE,GAAE;SACf;QAED,IAAI,CAAC,QAAQ,CAAC,IAAI,GAAG,CAAC,EAAU,EAAE,GAAG,CAAQ,EAAE,EAAE;YAC/C,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAA;QACpC,CAAC,CAAA;QACD,IAAI,CAAC,QAAQ,CAAC,UAAU,GAAG,CAAC,IAAgC,EAAE,EAAE;YAC9D,OAAO,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAA;QACtC,CAAC,CAAA;IACH,CAAC;IAED,MAAM;QACJ,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE;YACjB,OAAM;SACP;QACD,IAAI,CAAC,OAAO,GAAG,KAAK,CAAA;QAEpB,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;YACpB,MAAM,QAAQ,GAAG,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAA;YACxC,qBAAqB;YACrB,IAAI,CAAC,QAAQ,EAAE;gBACb,MAAM,IAAI,KAAK,CAAC,mCAAmC,GAAG,GAAG,CAAC,CAAA;aAC3D;YACD,oBAAoB;YACpB,IAAI;gBACF,IAAI,CAAC,QAAQ,CAAC,cAAc,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;gBAC3C,qBAAqB;aACtB;YAAC,OAAO,CAAC,EAAE,GAAE;YACd,oBAAoB;QACtB,CAAC,CAAC,CAAA;QACF,IAAI,CAAC,QAAQ,CAAC,IAAI,GAAG,IAAI,CAAC,oBAAoB,CAAA;QAC9C,IAAI,CAAC,QAAQ,CAAC,UAAU,GAAG,IAAI,CAAC,0BAA0B,CAAA;QAC1D,IAAI,CAAC,QAAQ,CAAC,KAAK,IAAI,CAAC,CAAA;IAC1B,CAAC;IAED,kBAAkB,CAAC,IAAgC;QACjD,qBAAqB;QACrB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE;YAC7B,OAAO,CAAC,CAAA;SACT;QACD,IAAI,CAAC,QAAQ,CAAC,QAAQ,GAAG,IAAI,IAAI,CAAC,CAAA;QAClC,oBAAoB;QAEpB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;QACxD,OAAO,IAAI,CAAC,0BAA0B,CAAC,IAAI,CACzC,IAAI,CAAC,QAAQ,EACb,IAAI,CAAC,QAAQ,CAAC,QAAQ,CACvB,CAAA;IACH,CAAC;IAED,YAAY,CAAC,EAAU,EAAE,GAAG,IAAW;QACrC,MAAM,EAAE,GAAG,IAAI,CAAC,oBAAoB,CAAA;QACpC,IAAI,EAAE,KAAK,MAAM,IAAI,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE;YAC7C,IAAI,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ,EAAE;gBAC/B,IAAI,CAAC,QAAQ,CAAC,QAAQ,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;gBAChC,qBAAqB;aACtB;YACD,qBAAqB;YACrB,MAAM,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC,CAAA;YAC/C,qBAAqB;YACrB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;YACxD,oBAAoB;YACpB,OAAO,GAAG,CAAA;SACX;aAAM;YACL,OAAO,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC,CAAA;SAC3C;IACH,CAAC;CACF;AAED,MAAM,OAAO,GAAG,UAAU,CAAC,OAAO,CAAA;AAClC,iEAAiE;AACjE,yBAAyB;AACzB,MAAM,CAAC,MAAM;AACX;;;;;;;;GAQG;AACH,MAAM;AAEN;;;;;;GAMG;AACH,IAAI;AAEJ;;;;;;GAMG;AACH,MAAM,GACP,GAAG,cAAc,CAChB,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,kBAAkB,EAAE,CACxE,CAAA","sourcesContent":["// Note: since nyc uses this module to output coverage, any lines\n// that are in the direct sync flow of nyc's outputCoverage are\n// ignored, since we can never get coverage for them.\n// grab a reference to node's real process object right away\nimport { signals } from './signals.js'\nexport { signals }\n\n// just a loosened process type so we can do some evil things\ntype ProcessRE = NodeJS.Process & {\n reallyExit: (code?: number | undefined | null) => any\n emit: (ev: string, ...a: any[]) => any\n}\n\nconst processOk = (process: any): process is ProcessRE =>\n !!process &&\n typeof process === 'object' &&\n typeof process.removeListener === 'function' &&\n typeof process.emit === 'function' &&\n typeof process.reallyExit === 'function' &&\n typeof process.listeners === 'function' &&\n typeof process.kill === 'function' &&\n typeof process.pid === 'number' &&\n typeof process.on === 'function'\n\nconst kExitEmitter = Symbol.for('signal-exit emitter')\nconst global: typeof globalThis & { [kExitEmitter]?: Emitter } = globalThis\nconst ObjectDefineProperty = Object.defineProperty.bind(Object)\n\n/**\n * A function that takes an exit code and signal as arguments\n *\n * In the case of signal exits *only*, a return value of true\n * will indicate that the signal is being handled, and we should\n * not synthetically exit with the signal we received. Regardless\n * of the handler return value, the handler is unloaded when an\n * otherwise fatal signal is received, so you get exactly 1 shot\n * at it, unless you add another onExit handler at that point.\n *\n * In the case of numeric code exits, we may already have committed\n * to exiting the process, for example via a fatal exception or\n * unhandled promise rejection, so it is impossible to stop safely.\n */\nexport type Handler = (\n code: number | null | undefined,\n signal: NodeJS.Signals | null\n) => true | void\ntype ExitEvent = 'afterExit' | 'exit'\ntype Emitted = { [k in ExitEvent]: boolean }\ntype Listeners = { [k in ExitEvent]: Handler[] }\n\n// teeny special purpose ee\nclass Emitter {\n emitted: Emitted = {\n afterExit: false,\n exit: false,\n }\n\n listeners: Listeners = {\n afterExit: [],\n exit: [],\n }\n\n count: number = 0\n id: number = Math.random()\n\n constructor() {\n if (global[kExitEmitter]) {\n return global[kExitEmitter]\n }\n ObjectDefineProperty(global, kExitEmitter, {\n value: this,\n writable: false,\n enumerable: false,\n configurable: false,\n })\n }\n\n on(ev: ExitEvent, fn: Handler) {\n this.listeners[ev].push(fn)\n }\n\n removeListener(ev: ExitEvent, fn: Handler) {\n const list = this.listeners[ev]\n const i = list.indexOf(fn)\n /* c8 ignore start */\n if (i === -1) {\n return\n }\n /* c8 ignore stop */\n if (i === 0 && list.length === 1) {\n list.length = 0\n } else {\n list.splice(i, 1)\n }\n }\n\n emit(\n ev: ExitEvent,\n code: number | null | undefined,\n signal: NodeJS.Signals | null\n ): boolean {\n if (this.emitted[ev]) {\n return false\n }\n this.emitted[ev] = true\n let ret: boolean = false\n for (const fn of this.listeners[ev]) {\n ret = fn(code, signal) === true || ret\n }\n if (ev === 'exit') {\n ret = this.emit('afterExit', code, signal) || ret\n }\n return ret\n }\n}\n\nabstract class SignalExitBase {\n abstract onExit(cb: Handler, opts?: { alwaysLast?: boolean }): () => void\n abstract load(): void\n abstract unload(): void\n}\n\nconst signalExitWrap = (handler: T) => {\n return {\n onExit(cb: Handler, opts?: { alwaysLast?: boolean }) {\n return handler.onExit(cb, opts)\n },\n load() {\n return handler.load()\n },\n unload() {\n return handler.unload()\n },\n }\n}\n\nclass SignalExitFallback extends SignalExitBase {\n onExit() {\n return () => {}\n }\n load() {}\n unload() {}\n}\n\nclass SignalExit extends SignalExitBase {\n // \"SIGHUP\" throws an `ENOSYS` error on Windows,\n // so use a supported signal instead\n /* c8 ignore start */\n #hupSig = process.platform === 'win32' ? 'SIGINT' : 'SIGHUP'\n /* c8 ignore stop */\n #emitter = new Emitter()\n #process: ProcessRE\n #originalProcessEmit: ProcessRE['emit']\n #originalProcessReallyExit: ProcessRE['reallyExit']\n\n #sigListeners: { [k in NodeJS.Signals]?: () => void } = {}\n #loaded: boolean = false\n\n constructor(process: ProcessRE) {\n super()\n this.#process = process\n // { : , ... }\n this.#sigListeners = {}\n for (const sig of signals) {\n this.#sigListeners[sig] = () => {\n // If there are no other listeners, an exit is coming!\n // Simplest way: remove us and then re-send the signal.\n // We know that this will kill the process, so we can\n // safely emit now.\n const listeners = this.#process.listeners(sig)\n let { count } = this.#emitter\n // This is a workaround for the fact that signal-exit v3 and signal\n // exit v4 are not aware of each other, and each will attempt to let\n // the other handle it, so neither of them do. To correct this, we\n // detect if we're the only handler *except* for previous versions\n // of signal-exit, and increment by the count of listeners it has\n // created.\n /* c8 ignore start */\n const p = process as unknown as {\n __signal_exit_emitter__?: { count: number }\n }\n if (\n typeof p.__signal_exit_emitter__ === 'object' &&\n typeof p.__signal_exit_emitter__.count === 'number'\n ) {\n count += p.__signal_exit_emitter__.count\n }\n /* c8 ignore stop */\n if (listeners.length === count) {\n this.unload()\n const ret = this.#emitter.emit('exit', null, sig)\n /* c8 ignore start */\n const s = sig === 'SIGHUP' ? this.#hupSig : sig\n if (!ret) process.kill(process.pid, s)\n /* c8 ignore stop */\n }\n }\n }\n\n this.#originalProcessReallyExit = process.reallyExit\n this.#originalProcessEmit = process.emit\n }\n\n onExit(cb: Handler, opts?: { alwaysLast?: boolean }) {\n /* c8 ignore start */\n if (!processOk(this.#process)) {\n return () => {}\n }\n /* c8 ignore stop */\n\n if (this.#loaded === false) {\n this.load()\n }\n\n const ev = opts?.alwaysLast ? 'afterExit' : 'exit'\n this.#emitter.on(ev, cb)\n return () => {\n this.#emitter.removeListener(ev, cb)\n if (\n this.#emitter.listeners['exit'].length === 0 &&\n this.#emitter.listeners['afterExit'].length === 0\n ) {\n this.unload()\n }\n }\n }\n\n load() {\n if (this.#loaded) {\n return\n }\n this.#loaded = true\n\n // This is the number of onSignalExit's that are in play.\n // It's important so that we can count the correct number of\n // listeners on signals, and don't wait for the other one to\n // handle it instead of us.\n this.#emitter.count += 1\n\n for (const sig of signals) {\n try {\n const fn = this.#sigListeners[sig]\n if (fn) this.#process.on(sig, fn)\n } catch (_) {}\n }\n\n this.#process.emit = (ev: string, ...a: any[]) => {\n return this.#processEmit(ev, ...a)\n }\n this.#process.reallyExit = (code?: number | null | undefined) => {\n return this.#processReallyExit(code)\n }\n }\n\n unload() {\n if (!this.#loaded) {\n return\n }\n this.#loaded = false\n\n signals.forEach(sig => {\n const listener = this.#sigListeners[sig]\n /* c8 ignore start */\n if (!listener) {\n throw new Error('Listener not defined for signal: ' + sig)\n }\n /* c8 ignore stop */\n try {\n this.#process.removeListener(sig, listener)\n /* c8 ignore start */\n } catch (_) {}\n /* c8 ignore stop */\n })\n this.#process.emit = this.#originalProcessEmit\n this.#process.reallyExit = this.#originalProcessReallyExit\n this.#emitter.count -= 1\n }\n\n #processReallyExit(code?: number | null | undefined) {\n /* c8 ignore start */\n if (!processOk(this.#process)) {\n return 0\n }\n this.#process.exitCode = code || 0\n /* c8 ignore stop */\n\n this.#emitter.emit('exit', this.#process.exitCode, null)\n return this.#originalProcessReallyExit.call(\n this.#process,\n this.#process.exitCode\n )\n }\n\n #processEmit(ev: string, ...args: any[]): any {\n const og = this.#originalProcessEmit\n if (ev === 'exit' && processOk(this.#process)) {\n if (typeof args[0] === 'number') {\n this.#process.exitCode = args[0]\n /* c8 ignore start */\n }\n /* c8 ignore start */\n const ret = og.call(this.#process, ev, ...args)\n /* c8 ignore start */\n this.#emitter.emit('exit', this.#process.exitCode, null)\n /* c8 ignore stop */\n return ret\n } else {\n return og.call(this.#process, ev, ...args)\n }\n }\n}\n\nconst process = globalThis.process\n// wrap so that we call the method on the actual handler, without\n// exporting it directly.\nexport const {\n /**\n * Called when the process is exiting, whether via signal, explicit\n * exit, or running out of stuff to do.\n *\n * If the global process object is not suitable for instrumentation,\n * then this will be a no-op.\n *\n * Returns a function that may be used to unload signal-exit.\n */\n onExit,\n\n /**\n * Load the listeners. Likely you never need to call this, unless\n * doing a rather deep integration with signal-exit functionality.\n * Mostly exposed for the benefit of testing.\n *\n * @internal\n */\n load,\n\n /**\n * Unload the listeners. Likely you never need to call this, unless\n * doing a rather deep integration with signal-exit functionality.\n * Mostly exposed for the benefit of testing.\n *\n * @internal\n */\n unload,\n} = signalExitWrap(\n processOk(process) ? new SignalExit(process) : new SignalExitFallback()\n)\n"]} \ No newline at end of file diff --git a/node_modules/signal-exit/dist/mjs/package.json b/node_modules/signal-exit/dist/mjs/package.json new file mode 100644 index 0000000..3dbc1ca --- /dev/null +++ b/node_modules/signal-exit/dist/mjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/signal-exit/dist/mjs/signals.d.ts b/node_modules/signal-exit/dist/mjs/signals.d.ts new file mode 100644 index 0000000..3f01ef0 --- /dev/null +++ b/node_modules/signal-exit/dist/mjs/signals.d.ts @@ -0,0 +1,29 @@ +/// +/** + * This is not the set of all possible signals. + * + * It IS, however, the set of all signals that trigger + * an exit on either Linux or BSD systems. Linux is a + * superset of the signal names supported on BSD, and + * the unknown signals just fail to register, so we can + * catch that easily enough. + * + * Windows signals are a different set, since there are + * signals that terminate Windows processes, but don't + * terminate (or don't even exist) on Posix systems. + * + * Don't bother with SIGKILL. It's uncatchable, which + * means that we can't fire any callbacks anyway. + * + * If a user does happen to register a handler on a non- + * fatal signal like SIGWINCH or something, and then + * exit, it'll end up firing `process.emit('exit')`, so + * the handler will be fired anyway. + * + * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised + * artificially, inherently leave the process in a + * state from which it is not safe to try and enter JS + * listeners. + */ +export declare const signals: NodeJS.Signals[]; +//# sourceMappingURL=signals.d.ts.map \ No newline at end of file diff --git a/node_modules/signal-exit/dist/mjs/signals.d.ts.map b/node_modules/signal-exit/dist/mjs/signals.d.ts.map new file mode 100644 index 0000000..891fe1e --- /dev/null +++ b/node_modules/signal-exit/dist/mjs/signals.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"signals.d.ts","sourceRoot":"","sources":["../../src/signals.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,OAAO,EAAE,MAAM,CAAC,OAAO,EAAO,CAAA"} \ No newline at end of file diff --git a/node_modules/signal-exit/dist/mjs/signals.js b/node_modules/signal-exit/dist/mjs/signals.js new file mode 100644 index 0000000..7dbf15a --- /dev/null +++ b/node_modules/signal-exit/dist/mjs/signals.js @@ -0,0 +1,39 @@ +/** + * This is not the set of all possible signals. + * + * It IS, however, the set of all signals that trigger + * an exit on either Linux or BSD systems. Linux is a + * superset of the signal names supported on BSD, and + * the unknown signals just fail to register, so we can + * catch that easily enough. + * + * Windows signals are a different set, since there are + * signals that terminate Windows processes, but don't + * terminate (or don't even exist) on Posix systems. + * + * Don't bother with SIGKILL. It's uncatchable, which + * means that we can't fire any callbacks anyway. + * + * If a user does happen to register a handler on a non- + * fatal signal like SIGWINCH or something, and then + * exit, it'll end up firing `process.emit('exit')`, so + * the handler will be fired anyway. + * + * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised + * artificially, inherently leave the process in a + * state from which it is not safe to try and enter JS + * listeners. + */ +export const signals = []; +signals.push('SIGHUP', 'SIGINT', 'SIGTERM'); +if (process.platform !== 'win32') { + signals.push('SIGALRM', 'SIGABRT', 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT' + // should detect profiler and enable/disable accordingly. + // see #21 + // 'SIGPROF' + ); +} +if (process.platform === 'linux') { + signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT'); +} +//# sourceMappingURL=signals.js.map \ No newline at end of file diff --git a/node_modules/signal-exit/dist/mjs/signals.js.map b/node_modules/signal-exit/dist/mjs/signals.js.map new file mode 100644 index 0000000..91008c9 --- /dev/null +++ b/node_modules/signal-exit/dist/mjs/signals.js.map @@ -0,0 +1 @@ +{"version":3,"file":"signals.js","sourceRoot":"","sources":["../../src/signals.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,CAAC,MAAM,OAAO,GAAqB,EAAE,CAAA;AAC3C,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAA;AAE3C,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;IAChC,OAAO,CAAC,IAAI,CACV,SAAS,EACT,SAAS,EACT,WAAW,EACX,SAAS,EACT,SAAS,EACT,SAAS,EACT,SAAS,EACT,QAAQ,EACR,SAAS,EACT,QAAQ;IACR,yDAAyD;IACzD,UAAU;IACV,YAAY;KACb,CAAA;CACF;AAED,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;IAChC,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAA;CACxD","sourcesContent":["/**\n * This is not the set of all possible signals.\n *\n * It IS, however, the set of all signals that trigger\n * an exit on either Linux or BSD systems. Linux is a\n * superset of the signal names supported on BSD, and\n * the unknown signals just fail to register, so we can\n * catch that easily enough.\n *\n * Windows signals are a different set, since there are\n * signals that terminate Windows processes, but don't\n * terminate (or don't even exist) on Posix systems.\n *\n * Don't bother with SIGKILL. It's uncatchable, which\n * means that we can't fire any callbacks anyway.\n *\n * If a user does happen to register a handler on a non-\n * fatal signal like SIGWINCH or something, and then\n * exit, it'll end up firing `process.emit('exit')`, so\n * the handler will be fired anyway.\n *\n * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised\n * artificially, inherently leave the process in a\n * state from which it is not safe to try and enter JS\n * listeners.\n */\nexport const signals: NodeJS.Signals[] = []\nsignals.push('SIGHUP', 'SIGINT', 'SIGTERM')\n\nif (process.platform !== 'win32') {\n signals.push(\n 'SIGALRM',\n 'SIGABRT',\n 'SIGVTALRM',\n 'SIGXCPU',\n 'SIGXFSZ',\n 'SIGUSR2',\n 'SIGTRAP',\n 'SIGSYS',\n 'SIGQUIT',\n 'SIGIOT'\n // should detect profiler and enable/disable accordingly.\n // see #21\n // 'SIGPROF'\n )\n}\n\nif (process.platform === 'linux') {\n signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT')\n}\n"]} \ No newline at end of file diff --git a/node_modules/signal-exit/package.json b/node_modules/signal-exit/package.json new file mode 100644 index 0000000..ac176ce --- /dev/null +++ b/node_modules/signal-exit/package.json @@ -0,0 +1,106 @@ +{ + "name": "signal-exit", + "version": "4.1.0", + "description": "when you want to fire an event no matter how a process exits.", + "main": "./dist/cjs/index.js", + "module": "./dist/mjs/index.js", + "browser": "./dist/mjs/browser.js", + "types": "./dist/mjs/index.d.ts", + "exports": { + ".": { + "import": { + "types": "./dist/mjs/index.d.ts", + "default": "./dist/mjs/index.js" + }, + "require": { + "types": "./dist/cjs/index.d.ts", + "default": "./dist/cjs/index.js" + } + }, + "./signals": { + "import": { + "types": "./dist/mjs/signals.d.ts", + "default": "./dist/mjs/signals.js" + }, + "require": { + "types": "./dist/cjs/signals.d.ts", + "default": "./dist/cjs/signals.js" + } + }, + "./browser": { + "import": { + "types": "./dist/mjs/browser.d.ts", + "default": "./dist/mjs/browser.js" + }, + "require": { + "types": "./dist/cjs/browser.d.ts", + "default": "./dist/cjs/browser.js" + } + } + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=14" + }, + "repository": { + "type": "git", + "url": "https://github.com/tapjs/signal-exit.git" + }, + "keywords": [ + "signal", + "exit" + ], + "author": "Ben Coe ", + "license": "ISC", + "devDependencies": { + "@types/cross-spawn": "^6.0.2", + "@types/node": "^18.15.11", + "@types/signal-exit": "^3.0.1", + "@types/tap": "^15.0.8", + "c8": "^7.13.0", + "prettier": "^2.8.6", + "tap": "^16.3.4", + "ts-node": "^10.9.1", + "typedoc": "^0.23.28", + "typescript": "^5.0.2" + }, + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "preprepare": "rm -rf dist", + "prepare": "tsc -p tsconfig.json && tsc -p tsconfig-esm.json && bash ./scripts/fixup.sh", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "c8 tap", + "snap": "c8 tap", + "format": "prettier --write . --loglevel warn", + "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts" + }, + "prettier": { + "semi": false, + "printWidth": 75, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "tap": { + "coverage": false, + "jobs": 1, + "node-arg": [ + "--no-warnings", + "--loader", + "ts-node/esm" + ], + "ts": false + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } +} diff --git a/node_modules/slash/index.js b/node_modules/slash/index.js new file mode 100644 index 0000000..b946a08 --- /dev/null +++ b/node_modules/slash/index.js @@ -0,0 +1,11 @@ +'use strict'; +module.exports = function (str) { + var isExtendedLengthPath = /^\\\\\?\\/.test(str); + var hasNonAscii = /[^\x00-\x80]+/.test(str); + + if (isExtendedLengthPath || hasNonAscii) { + return str; + } + + return str.replace(/\\/g, '/'); +}; diff --git a/node_modules/slash/package.json b/node_modules/slash/package.json new file mode 100644 index 0000000..7e744a4 --- /dev/null +++ b/node_modules/slash/package.json @@ -0,0 +1,33 @@ +{ + "name": "slash", + "version": "1.0.0", + "description": "Convert Windows backslash paths to slash paths", + "keywords": [ + "path", + "seperator", + "sep", + "slash", + "backslash", + "windows", + "win" + ], + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "http://sindresorhus.com" + }, + "repository": "sindresorhus/slash", + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "mocha": "*" + }, + "engines": { + "node": ">=0.10.0" + }, + "license": "MIT", + "files": [ + "index.js" + ] +} diff --git a/node_modules/slash/readme.md b/node_modules/slash/readme.md new file mode 100644 index 0000000..15672f0 --- /dev/null +++ b/node_modules/slash/readme.md @@ -0,0 +1,44 @@ +# slash [![Build Status](https://travis-ci.org/sindresorhus/slash.svg?branch=master)](https://travis-ci.org/sindresorhus/slash) + +> Convert Windows backslash paths to slash paths: `foo\\bar` ➔ `foo/bar` + +[Forward-slash paths can be used in Windows](http://superuser.com/a/176395/6877) as long as they're not extended-length paths and don't contain any non-ascii characters. + +This was created since the `path` methods in Node outputs `\\` paths on Windows. + + +## Install + +```sh +$ npm install --save slash +``` + + +## Usage + +```js +var path = require('path'); +var slash = require('slash'); + +var str = path.join('foo', 'bar'); +// Unix => foo/bar +// Windows => foo\\bar + +slash(str); +// Unix => foo/bar +// Windows => foo/bar +``` + + +## API + +### slash(path) + +Type: `string` + +Accepts a Windows backslash path and returns a slash path. + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/node_modules/slugify/CHANGELOG.md b/node_modules/slugify/CHANGELOG.md new file mode 100644 index 0000000..2211ddb --- /dev/null +++ b/node_modules/slugify/CHANGELOG.md @@ -0,0 +1,94 @@ +## Change Log + +### v1.6.6 (2023-03-26) +- [#174](https://github.com/simov/slugify/pull/174) correctly handle empty strings in charmaps (@iliazeus) +- [#169](https://github.com/simov/slugify/pull/169) Add changelog (@simov) +- [#168](https://github.com/simov/slugify/pull/168) chore: document limitations of the `remove` option (#168) (@Trott) +- [#157](https://github.com/simov/slugify/pull/157) Run CI in Node.js 18 (@stscoundrel) +- [#151](https://github.com/simov/slugify/pull/151) Update README.md (#151) (@lorand-horvath) + +### v1.6.5 (2022-01-03) +- [#146](https://github.com/simov/slugify/pull/146) chore: use GitHub Actions for testing (#146) (@Trott) + +### v1.6.4 (2021-12-16) +- [#145](https://github.com/simov/slugify/pull/145) fix: consolidate replacement chars from extend() (#145) (@Trott) +- [#142](https://github.com/simov/slugify/pull/142) More Yoruba support (@9jaboy) + +### v1.6.3 (2021-11-22) +- [#139](https://github.com/simov/slugify/pull/139) Added few more locales (@daniel1901) +- [#138](https://github.com/simov/slugify/pull/138) Add 'ß' (ss) to german locale (@maxkrickl) + +### v1.6.2 (2021-11-07) +- [#136](https://github.com/simov/slugify/pull/136) Add Bulgarian locale. (@haltsir) + +### v1.6.1 (2021-10-04) +- [#132](https://github.com/simov/slugify/pull/132) Add arabic and persian characters and numbers to charmap (@kiron) +- [#128](https://github.com/simov/slugify/pull/128) Added danish support to locales.json (@ItzLue) + +### v1.6.0 (2021-07-15) +- [#125](https://github.com/simov/slugify/pull/125) Update README.md (@SuecoMarcus) +- [#123](https://github.com/simov/slugify/pull/123) feat: add "trim" option (#123) (@Trott) +- [#119](https://github.com/simov/slugify/pull/119) adding Armenian support (@ashotjanibekyan) + +### v1.5.3 (2021-05-11) +- [#116](https://github.com/simov/slugify/pull/116) fix: remove replacement char from start and end in strict mode (#116) (@Trott) + +### v1.5.2 (2021-05-08) +- [#115](https://github.com/simov/slugify/pull/115) fix: trim leading and trailing replacement chars (#115) (@Trott) + +### v1.5.1 (2021-05-02) +- [#111](https://github.com/simov/slugify/pull/111) Two new special chars for charmap.json (@ovidasas) +- [#113](https://github.com/simov/slugify/pull/113) Added Ukrainian characters (@YegorShtonda) +- [#107](https://github.com/simov/slugify/pull/107) Indicate that ES2015 is required & use Object.assign (@realityking) + +### v1.4.7 (2021-02-21) +- [#104](https://github.com/simov/slugify/pull/104) added more translations for german locale (@roydigerhund) +- [#103](https://github.com/simov/slugify/pull/103) Add a French locale to replace symbols like "&", "<", "|" by their French equivalent (#103) (@saadyousfi) + +### v1.4.5 (2020-07-26) +- [#87](https://github.com/simov/slugify/pull/87) Add German locale (@schwigri) + +### v1.4.2 (2020-06-23) +- [#71](https://github.com/simov/slugify/pull/71) add turkish currency character (@ugurh) +- [#79](https://github.com/simov/slugify/pull/79) Ensure duplicate replacement characters are removed in strict mode (@thompsonsj) + +### v1.3.6 (2019-11-03) +- [#63](https://github.com/simov/slugify/pull/63) Fix broken link in README (@roschaefer) + +### v1.3.5 (2019-09-08) +- [#47](https://github.com/simov/slugify/pull/47) Update eslint and related packages; fix new linting errors (@realityking) + +### v1.3.4 (2018-12-06) +- [#45](https://github.com/simov/slugify/pull/45) Added % handling (#44) (@chucksense) +- [#44](https://github.com/simov/slugify/pull/44) Added % handling (#44) (Chuck Burt) + +### v1.3.1 (2018-08-05) +- [#34](https://github.com/simov/slugify/pull/34) docs: align example code (@adrukh) + +### v1.3.0 (2018-05-13) +- [#28](https://github.com/simov/slugify/pull/28) Minor typo fix (@chmac) + +### v1.2.9 (2017-12-30) +- [#27](https://github.com/simov/slugify/pull/27) Support TypeScript types for `extend` properties (@rohmanhm) + +### v1.2.8 (2017-12-23) +- [#25](https://github.com/simov/slugify/pull/25) fix es6 import (@sylvaindumont) + +### v1.2.7 (2017-12-17) +- [#23](https://github.com/simov/slugify/pull/23) add georgian alphabet (@xxzefgh) + +### v1.2.6 (2017-11-24) +- [#19](https://github.com/simov/slugify/pull/19) fix - ts typings now export slugify correctly (@neonerd) + +### v1.2.3 (2017-11-13) +- [#14](https://github.com/simov/slugify/pull/14) add typescript support (@sylvaindumont) + +### v1.2.2 (2017-11-09) +- [#7](https://github.com/simov/slugify/pull/7) Added support for Serbian characters (@slavkobabic) +- [#11](https://github.com/simov/slugify/pull/11) Add Russian Ruble (@toptalo) + +### v1.1.0 (2017-01-08) +- [#6](https://github.com/simov/slugify/pull/6) Fix then/than homophone grammar mistake. (@PatrickNausha) + +### v1.0.1 (2016-08-08) +- [#1](https://github.com/simov/slugify/pull/1) Update README.md (@mrzmyr) diff --git a/node_modules/slugify/LICENSE b/node_modules/slugify/LICENSE new file mode 100644 index 0000000..ebbb2c2 --- /dev/null +++ b/node_modules/slugify/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Simeon Velichkov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/slugify/README.md b/node_modules/slugify/README.md new file mode 100644 index 0000000..385d7b0 --- /dev/null +++ b/node_modules/slugify/README.md @@ -0,0 +1,98 @@ + +# slugify + +[![npm-version]][npm] [![coveralls-status]][coveralls] + +```js +var slugify = require('slugify') + +slugify('some string') // some-string + +// if you prefer something other than '-' as separator +slugify('some string', '_') // some_string +``` + +- Vanilla ES2015 JavaScript + - If you need to use Slugify with older browsers, consider using [version 1.4.7](https://github.com/simov/slugify/releases/tag/v1.4.7) +- No dependencies +- Coerces foreign symbols to their English equivalent (check out the [charMap][charmap] for more details) +- Works in the browser (window.slugify) and AMD/CommonJS-flavored module loaders + +## Options + +```js +slugify('some string', { + replacement: '-', // replace spaces with replacement character, defaults to `-` + remove: undefined, // remove characters that match regex, defaults to `undefined` + lower: false, // convert to lower case, defaults to `false` + strict: false, // strip special characters except replacement, defaults to `false` + locale: 'vi', // language code of the locale to use + trim: true // trim leading and trailing replacement chars, defaults to `true` +}) +``` + +## Remove + +For example, to remove `*+~.()'"!:@` from the result slug, you can use `slugify('..', {remove: /[*+~.()'"!:@]/g})`. + +* If the value of `remove` is a regular expression, it should be a + [character class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes) + and only a character class. It should also use the + [global flag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/global). + (For example: `/[*+~.()'"!:@]/g`.) Otherwise, the `remove` option might not + work as expected. +* If the value of `remove` is a string, it should be a single character. + Otherwise, the `remove` option might not work as expected. + +## Locales + +The main `charmap.json` file contains all known characters and their transliteration. All new characters should be added there first. In case you stumble upon a character already set in `charmap.json`, but not transliterated correctly according to your language, then you have to add those characters in `locales.json` to override the already existing transliteration in `charmap.json`, but for your locale only. + +You can get the correct language code of your language from [here](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). + +## Extend + +Out of the box `slugify` comes with support for a handful of Unicode symbols. For example the `☢` (radioactive) symbol is not defined in the [`charMap`][charmap] and therefore it will be stripped by default: + +```js +slugify('unicode ♥ is ☢') // unicode-love-is +``` + +However you can extend the supported symbols, or override the existing ones with your own: + +```js +slugify.extend({'☢': 'radioactive'}) +slugify('unicode ♥ is ☢') // unicode-love-is-radioactive +``` + +Keep in mind that the `extend` method extends/overrides the default `charMap` for the entire process. In case you need a fresh instance of the slugify's `charMap` object you have to clean up the module cache first: + +```js +delete require.cache[require.resolve('slugify')] +var slugify = require('slugify') +``` + +## Contribute + +1. Add chars to `charmap.json` +2. Run tests `npm test` +3. The tests will build the charmap in `index.js` and will sort the `charmap.json` +4. Commit **all** modified files + +--- + +> Originally this was a vanilla javascript port of [node-slug][node-slug].
+> Note that the original [slug][slug] module has been ported to vanilla javascript too. + + + [npm-version]: https://img.shields.io/npm/v/slugify.svg?style=flat-square (NPM Package Version) + [coveralls-status]: https://img.shields.io/coveralls/simov/slugify.svg?style=flat-square (Test Coverage - Coveralls) + + [npm]: https://www.npmjs.com/package/slugify + [coveralls]: https://coveralls.io/r/simov/slugify?branch=master + + [node-slug]: https://github.com/dodo/node-slug + [slug]: https://www.npmjs.com/package/slug + [unicode]: https://www.npmjs.com/package/unicode + [index]: https://github.com/simov/slugify/blob/master/index.js + [charmap]: https://github.com/simov/slugify/blob/master/config/charmap.json diff --git a/node_modules/slugify/package.json b/node_modules/slugify/package.json new file mode 100644 index 0000000..1d8a95a --- /dev/null +++ b/node_modules/slugify/package.json @@ -0,0 +1,42 @@ +{ + "name": "slugify", + "version": "1.6.6", + "description": "Slugifies a String", + "keywords": [ + "slugify", + "slug", + "url", + "urlify" + ], + "license": "MIT", + "homepage": "https://github.com/simov/slugify", + "author": "Simeon Velichkov (https://simov.github.io)", + "repository": { + "type": "git", + "url": "https://github.com/simov/slugify.git" + }, + "devDependencies": { + "coveralls": "^3.1.0", + "github-changes": "^2.0.3", + "mocha": "^7.2.0", + "nyc": "^15.1.0" + }, + "main": "./slugify.js", + "files": [ + "LICENSE", + "README.md", + "slugify.d.ts", + "slugify.js" + ], + "types": "slugify.d.ts", + "scripts": { + "build": "node bin/build", + "build:changelog": "github-changes --owner simov --repository slugify --only-pulls --use-commit-body --date-format '(YYYY-MM-DD)' --file CHANGELOG.md --verbose", + "test:ci": "npx mocha --recursive", + "test:cov": "npx nyc --reporter=lcov --reporter=text-summary mocha -- --recursive", + "test": "npm run build && npm run test:ci" + }, + "engines": { + "node": ">=8.0.0" + } +} diff --git a/node_modules/slugify/slugify.d.ts b/node_modules/slugify/slugify.d.ts new file mode 100644 index 0000000..e20f795 --- /dev/null +++ b/node_modules/slugify/slugify.d.ts @@ -0,0 +1,24 @@ +declare module slugify { + type ExtendArgs = { + [key: string]: any; + } + + export function extend (args: ExtendArgs): void; +} + +declare function slugify( + string: string, + options?: + | { + replacement?: string; + remove?: RegExp; + lower?: boolean; + strict?: boolean; + locale?: string; + trim?: boolean; + } + | string, + +): string; + +export default slugify; diff --git a/node_modules/slugify/slugify.js b/node_modules/slugify/slugify.js new file mode 100644 index 0000000..f5a6a1e --- /dev/null +++ b/node_modules/slugify/slugify.js @@ -0,0 +1,69 @@ + +;(function (name, root, factory) { + if (typeof exports === 'object') { + module.exports = factory() + module.exports['default'] = factory() + } + /* istanbul ignore next */ + else if (typeof define === 'function' && define.amd) { + define(factory) + } + else { + root[name] = factory() + } +}('slugify', this, function () { + var charMap = JSON.parse('{"$":"dollar","%":"percent","&":"and","<":"less",">":"greater","|":"or","¢":"cent","£":"pound","¤":"currency","¥":"yen","©":"(c)","ª":"a","®":"(r)","º":"o","À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","Æ":"AE","Ç":"C","È":"E","É":"E","Ê":"E","Ë":"E","Ì":"I","Í":"I","Î":"I","Ï":"I","Ð":"D","Ñ":"N","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","Ù":"U","Ú":"U","Û":"U","Ü":"U","Ý":"Y","Þ":"TH","ß":"ss","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","æ":"ae","ç":"c","è":"e","é":"e","ê":"e","ë":"e","ì":"i","í":"i","î":"i","ï":"i","ð":"d","ñ":"n","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","ù":"u","ú":"u","û":"u","ü":"u","ý":"y","þ":"th","ÿ":"y","Ā":"A","ā":"a","Ă":"A","ă":"a","Ą":"A","ą":"a","Ć":"C","ć":"c","Č":"C","č":"c","Ď":"D","ď":"d","Đ":"DJ","đ":"dj","Ē":"E","ē":"e","Ė":"E","ė":"e","Ę":"e","ę":"e","Ě":"E","ě":"e","Ğ":"G","ğ":"g","Ģ":"G","ģ":"g","Ĩ":"I","ĩ":"i","Ī":"i","ī":"i","Į":"I","į":"i","İ":"I","ı":"i","Ķ":"k","ķ":"k","Ļ":"L","ļ":"l","Ľ":"L","ľ":"l","Ł":"L","ł":"l","Ń":"N","ń":"n","Ņ":"N","ņ":"n","Ň":"N","ň":"n","Ō":"O","ō":"o","Ő":"O","ő":"o","Œ":"OE","œ":"oe","Ŕ":"R","ŕ":"r","Ř":"R","ř":"r","Ś":"S","ś":"s","Ş":"S","ş":"s","Š":"S","š":"s","Ţ":"T","ţ":"t","Ť":"T","ť":"t","Ũ":"U","ũ":"u","Ū":"u","ū":"u","Ů":"U","ů":"u","Ű":"U","ű":"u","Ų":"U","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","ź":"z","Ż":"Z","ż":"z","Ž":"Z","ž":"z","Ə":"E","ƒ":"f","Ơ":"O","ơ":"o","Ư":"U","ư":"u","Lj":"LJ","lj":"lj","Nj":"NJ","nj":"nj","Ș":"S","ș":"s","Ț":"T","ț":"t","ə":"e","˚":"o","Ά":"A","Έ":"E","Ή":"H","Ί":"I","Ό":"O","Ύ":"Y","Ώ":"W","ΐ":"i","Α":"A","Β":"B","Γ":"G","Δ":"D","Ε":"E","Ζ":"Z","Η":"H","Θ":"8","Ι":"I","Κ":"K","Λ":"L","Μ":"M","Ν":"N","Ξ":"3","Ο":"O","Π":"P","Ρ":"R","Σ":"S","Τ":"T","Υ":"Y","Φ":"F","Χ":"X","Ψ":"PS","Ω":"W","Ϊ":"I","Ϋ":"Y","ά":"a","έ":"e","ή":"h","ί":"i","ΰ":"y","α":"a","β":"b","γ":"g","δ":"d","ε":"e","ζ":"z","η":"h","θ":"8","ι":"i","κ":"k","λ":"l","μ":"m","ν":"n","ξ":"3","ο":"o","π":"p","ρ":"r","ς":"s","σ":"s","τ":"t","υ":"y","φ":"f","χ":"x","ψ":"ps","ω":"w","ϊ":"i","ϋ":"y","ό":"o","ύ":"y","ώ":"w","Ё":"Yo","Ђ":"DJ","Є":"Ye","І":"I","Ї":"Yi","Ј":"J","Љ":"LJ","Њ":"NJ","Ћ":"C","Џ":"DZ","А":"A","Б":"B","В":"V","Г":"G","Д":"D","Е":"E","Ж":"Zh","З":"Z","И":"I","Й":"J","К":"K","Л":"L","М":"M","Н":"N","О":"O","П":"P","Р":"R","С":"S","Т":"T","У":"U","Ф":"F","Х":"H","Ц":"C","Ч":"Ch","Ш":"Sh","Щ":"Sh","Ъ":"U","Ы":"Y","Ь":"","Э":"E","Ю":"Yu","Я":"Ya","а":"a","б":"b","в":"v","г":"g","д":"d","е":"e","ж":"zh","з":"z","и":"i","й":"j","к":"k","л":"l","м":"m","н":"n","о":"o","п":"p","р":"r","с":"s","т":"t","у":"u","ф":"f","х":"h","ц":"c","ч":"ch","ш":"sh","щ":"sh","ъ":"u","ы":"y","ь":"","э":"e","ю":"yu","я":"ya","ё":"yo","ђ":"dj","є":"ye","і":"i","ї":"yi","ј":"j","љ":"lj","њ":"nj","ћ":"c","ѝ":"u","џ":"dz","Ґ":"G","ґ":"g","Ғ":"GH","ғ":"gh","Қ":"KH","қ":"kh","Ң":"NG","ң":"ng","Ү":"UE","ү":"ue","Ұ":"U","ұ":"u","Һ":"H","һ":"h","Ә":"AE","ә":"ae","Ө":"OE","ө":"oe","Ա":"A","Բ":"B","Գ":"G","Դ":"D","Ե":"E","Զ":"Z","Է":"E\'","Ը":"Y\'","Թ":"T\'","Ժ":"JH","Ի":"I","Լ":"L","Խ":"X","Ծ":"C\'","Կ":"K","Հ":"H","Ձ":"D\'","Ղ":"GH","Ճ":"TW","Մ":"M","Յ":"Y","Ն":"N","Շ":"SH","Չ":"CH","Պ":"P","Ջ":"J","Ռ":"R\'","Ս":"S","Վ":"V","Տ":"T","Ր":"R","Ց":"C","Փ":"P\'","Ք":"Q\'","Օ":"O\'\'","Ֆ":"F","և":"EV","ء":"a","آ":"aa","أ":"a","ؤ":"u","إ":"i","ئ":"e","ا":"a","ب":"b","ة":"h","ت":"t","ث":"th","ج":"j","ح":"h","خ":"kh","د":"d","ذ":"th","ر":"r","ز":"z","س":"s","ش":"sh","ص":"s","ض":"dh","ط":"t","ظ":"z","ع":"a","غ":"gh","ف":"f","ق":"q","ك":"k","ل":"l","م":"m","ن":"n","ه":"h","و":"w","ى":"a","ي":"y","ً":"an","ٌ":"on","ٍ":"en","َ":"a","ُ":"u","ِ":"e","ْ":"","٠":"0","١":"1","٢":"2","٣":"3","٤":"4","٥":"5","٦":"6","٧":"7","٨":"8","٩":"9","پ":"p","چ":"ch","ژ":"zh","ک":"k","گ":"g","ی":"y","۰":"0","۱":"1","۲":"2","۳":"3","۴":"4","۵":"5","۶":"6","۷":"7","۸":"8","۹":"9","฿":"baht","ა":"a","ბ":"b","გ":"g","დ":"d","ე":"e","ვ":"v","ზ":"z","თ":"t","ი":"i","კ":"k","ლ":"l","მ":"m","ნ":"n","ო":"o","პ":"p","ჟ":"zh","რ":"r","ს":"s","ტ":"t","უ":"u","ფ":"f","ქ":"k","ღ":"gh","ყ":"q","შ":"sh","ჩ":"ch","ც":"ts","ძ":"dz","წ":"ts","ჭ":"ch","ხ":"kh","ჯ":"j","ჰ":"h","Ṣ":"S","ṣ":"s","Ẁ":"W","ẁ":"w","Ẃ":"W","ẃ":"w","Ẅ":"W","ẅ":"w","ẞ":"SS","Ạ":"A","ạ":"a","Ả":"A","ả":"a","Ấ":"A","ấ":"a","Ầ":"A","ầ":"a","Ẩ":"A","ẩ":"a","Ẫ":"A","ẫ":"a","Ậ":"A","ậ":"a","Ắ":"A","ắ":"a","Ằ":"A","ằ":"a","Ẳ":"A","ẳ":"a","Ẵ":"A","ẵ":"a","Ặ":"A","ặ":"a","Ẹ":"E","ẹ":"e","Ẻ":"E","ẻ":"e","Ẽ":"E","ẽ":"e","Ế":"E","ế":"e","Ề":"E","ề":"e","Ể":"E","ể":"e","Ễ":"E","ễ":"e","Ệ":"E","ệ":"e","Ỉ":"I","ỉ":"i","Ị":"I","ị":"i","Ọ":"O","ọ":"o","Ỏ":"O","ỏ":"o","Ố":"O","ố":"o","Ồ":"O","ồ":"o","Ổ":"O","ổ":"o","Ỗ":"O","ỗ":"o","Ộ":"O","ộ":"o","Ớ":"O","ớ":"o","Ờ":"O","ờ":"o","Ở":"O","ở":"o","Ỡ":"O","ỡ":"o","Ợ":"O","ợ":"o","Ụ":"U","ụ":"u","Ủ":"U","ủ":"u","Ứ":"U","ứ":"u","Ừ":"U","ừ":"u","Ử":"U","ử":"u","Ữ":"U","ữ":"u","Ự":"U","ự":"u","Ỳ":"Y","ỳ":"y","Ỵ":"Y","ỵ":"y","Ỷ":"Y","ỷ":"y","Ỹ":"Y","ỹ":"y","–":"-","‘":"\'","’":"\'","“":"\\\"","”":"\\\"","„":"\\\"","†":"+","•":"*","…":"...","₠":"ecu","₢":"cruzeiro","₣":"french franc","₤":"lira","₥":"mill","₦":"naira","₧":"peseta","₨":"rupee","₩":"won","₪":"new shequel","₫":"dong","€":"euro","₭":"kip","₮":"tugrik","₯":"drachma","₰":"penny","₱":"peso","₲":"guarani","₳":"austral","₴":"hryvnia","₵":"cedi","₸":"kazakhstani tenge","₹":"indian rupee","₺":"turkish lira","₽":"russian ruble","₿":"bitcoin","℠":"sm","™":"tm","∂":"d","∆":"delta","∑":"sum","∞":"infinity","♥":"love","元":"yuan","円":"yen","﷼":"rial","ﻵ":"laa","ﻷ":"laa","ﻹ":"lai","ﻻ":"la"}') + var locales = JSON.parse('{"bg":{"Й":"Y","Ц":"Ts","Щ":"Sht","Ъ":"A","Ь":"Y","й":"y","ц":"ts","щ":"sht","ъ":"a","ь":"y"},"de":{"Ä":"AE","ä":"ae","Ö":"OE","ö":"oe","Ü":"UE","ü":"ue","ß":"ss","%":"prozent","&":"und","|":"oder","∑":"summe","∞":"unendlich","♥":"liebe"},"es":{"%":"por ciento","&":"y","<":"menor que",">":"mayor que","|":"o","¢":"centavos","£":"libras","¤":"moneda","₣":"francos","∑":"suma","∞":"infinito","♥":"amor"},"fr":{"%":"pourcent","&":"et","<":"plus petit",">":"plus grand","|":"ou","¢":"centime","£":"livre","¤":"devise","₣":"franc","∑":"somme","∞":"infini","♥":"amour"},"pt":{"%":"porcento","&":"e","<":"menor",">":"maior","|":"ou","¢":"centavo","∑":"soma","£":"libra","∞":"infinito","♥":"amor"},"uk":{"И":"Y","и":"y","Й":"Y","й":"y","Ц":"Ts","ц":"ts","Х":"Kh","х":"kh","Щ":"Shch","щ":"shch","Г":"H","г":"h"},"vi":{"Đ":"D","đ":"d"},"da":{"Ø":"OE","ø":"oe","Å":"AA","å":"aa","%":"procent","&":"og","|":"eller","$":"dollar","<":"mindre end",">":"større end"},"nb":{"&":"og","Å":"AA","Æ":"AE","Ø":"OE","å":"aa","æ":"ae","ø":"oe"},"it":{"&":"e"},"nl":{"&":"en"},"sv":{"&":"och","Å":"AA","Ä":"AE","Ö":"OE","å":"aa","ä":"ae","ö":"oe"}}') + + function replace (string, options) { + if (typeof string !== 'string') { + throw new Error('slugify: string argument expected') + } + + options = (typeof options === 'string') + ? {replacement: options} + : options || {} + + var locale = locales[options.locale] || {} + + var replacement = options.replacement === undefined ? '-' : options.replacement + + var trim = options.trim === undefined ? true : options.trim + + var slug = string.normalize().split('') + // replace characters based on charMap + .reduce(function (result, ch) { + var appendChar = locale[ch]; + if (appendChar === undefined) appendChar = charMap[ch]; + if (appendChar === undefined) appendChar = ch; + if (appendChar === replacement) appendChar = ' '; + return result + appendChar + // remove not allowed characters + .replace(options.remove || /[^\w\s$*_+~.()'"!\-:@]+/g, '') + }, ''); + + if (options.strict) { + slug = slug.replace(/[^A-Za-z0-9\s]/g, ''); + } + + if (trim) { + slug = slug.trim() + } + + // Replace spaces with replacement character, treating multiple consecutive + // spaces as a single space. + slug = slug.replace(/\s+/g, replacement); + + if (options.lower) { + slug = slug.toLowerCase() + } + + return slug + } + + replace.extend = function (customMap) { + Object.assign(charMap, customMap) + } + + return replace +})) diff --git a/node_modules/source-map-js/LICENSE b/node_modules/source-map-js/LICENSE new file mode 100644 index 0000000..ed1b7cf --- /dev/null +++ b/node_modules/source-map-js/LICENSE @@ -0,0 +1,28 @@ + +Copyright (c) 2009-2011, Mozilla Foundation and contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the names of the Mozilla Foundation nor the names of project + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/source-map-js/README.md b/node_modules/source-map-js/README.md new file mode 100644 index 0000000..614962d --- /dev/null +++ b/node_modules/source-map-js/README.md @@ -0,0 +1,765 @@ +# Source Map JS + +[![NPM](https://nodei.co/npm/source-map-js.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map-js) + +Difference between original [source-map](https://github.com/mozilla/source-map): + +> TL,DR: it's fork of original source-map@0.6, but with perfomance optimizations. + +This journey starts from [source-map@0.7.0](https://github.com/mozilla/source-map/blob/master/CHANGELOG.md#070). Some part of it was rewritten to Rust and WASM and API became async. + +It's still a major block for many libraries like PostCSS or Sass for example because they need to migrate the whole API to the async way. This is the reason why 0.6.1 has 2x more downloads than 0.7.3 while it's faster several times. + +![Downloads count](media/downloads.png) + +More important that WASM version has some optimizations in JS code too. This is why [community asked to create branch for 0.6 version](https://github.com/mozilla/source-map/issues/324) and port these optimizations but, sadly, the answer was «no». A bit later I discovered [the issue](https://github.com/mozilla/source-map/issues/370) created by [Ben Rothman (@benthemonkey)](https://github.com/benthemonkey) with no response at all. + +[Roman Dvornov (@lahmatiy)](https://github.com/lahmatiy) wrote a [serveral posts](https://t.me/gorshochekvarit/76) (russian, only, sorry) about source-map library in his own Telegram channel. He mentioned the article [«Maybe you don't need Rust and WASM to speed up your JS»](https://mrale.ph/blog/2018/02/03/maybe-you-dont-need-rust-to-speed-up-your-js.html) written by [Vyacheslav Egorov (@mraleph)](https://github.com/mraleph). This article contains optimizations and hacks that lead to almost the same performance compare to WASM implementation. + +I decided to fork the original source-map and port these optimizations from the article and several others PR from the original source-map. + +--------- + +This is a library to generate and consume the source map format +[described here][format]. + +[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit + +## Use with Node + + $ npm install source-map-js + + + +-------------------------------------------------------------------------------- + + + + + +## Table of Contents + +- [Examples](#examples) + - [Consuming a source map](#consuming-a-source-map) + - [Generating a source map](#generating-a-source-map) + - [With SourceNode (high level API)](#with-sourcenode-high-level-api) + - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) +- [API](#api) + - [SourceMapConsumer](#sourcemapconsumer) + - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) + - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) + - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) + - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) + - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) + - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) + - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) + - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) + - [SourceMapGenerator](#sourcemapgenerator) + - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) + - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer) + - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) + - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) + - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) + - [SourceNode](#sourcenode) + - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) + - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) + - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) + - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) + - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) + - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) + - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) + - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) + - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) + - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) + + + +## Examples + +### Consuming a source map + +```js +var rawSourceMap = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + sourceRoot: 'http://example.com/www/js/', + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' +}; + +var smc = new SourceMapConsumer(rawSourceMap); + +console.log(smc.sources); +// [ 'http://example.com/www/js/one.js', +// 'http://example.com/www/js/two.js' ] + +console.log(smc.originalPositionFor({ + line: 2, + column: 28 +})); +// { source: 'http://example.com/www/js/two.js', +// line: 2, +// column: 10, +// name: 'n' } + +console.log(smc.generatedPositionFor({ + source: 'http://example.com/www/js/two.js', + line: 2, + column: 10 +})); +// { line: 2, column: 28 } + +smc.eachMapping(function (m) { + // ... +}); +``` + +### Generating a source map + +In depth guide: +[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) + +#### With SourceNode (high level API) + +```js +function compile(ast) { + switch (ast.type) { + case 'BinaryExpression': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + [compile(ast.left), " + ", compile(ast.right)] + ); + case 'Literal': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + String(ast.value) + ); + // ... + default: + throw new Error("Bad AST"); + } +} + +var ast = parse("40 + 2", "add.js"); +console.log(compile(ast).toStringWithSourceMap({ + file: 'add.js' +})); +// { code: '40 + 2', +// map: [object SourceMapGenerator] } +``` + +#### With SourceMapGenerator (low level API) + +```js +var map = new SourceMapGenerator({ + file: "source-mapped.js" +}); + +map.addMapping({ + generated: { + line: 10, + column: 35 + }, + source: "foo.js", + original: { + line: 33, + column: 2 + }, + name: "christopher" +}); + +console.log(map.toString()); +// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' +``` + +## API + +Get a reference to the module: + +```js +// Node.js +var sourceMap = require('source-map'); + +// Browser builds +var sourceMap = window.sourceMap; + +// Inside Firefox +const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); +``` + +### SourceMapConsumer + +A SourceMapConsumer instance represents a parsed source map which we can query +for information about the original file positions by giving it a file position +in the generated source. + +#### new SourceMapConsumer(rawSourceMap) + +The only parameter is the raw source map (either as a string which can be +`JSON.parse`'d, or an object). According to the spec, source maps have the +following attributes: + +* `version`: Which version of the source map spec this map is following. + +* `sources`: An array of URLs to the original source files. + +* `names`: An array of identifiers which can be referenced by individual + mappings. + +* `sourceRoot`: Optional. The URL root from which all sources are relative. + +* `sourcesContent`: Optional. An array of contents of the original source files. + +* `mappings`: A string of base64 VLQs which contain the actual mappings. + +* `file`: Optional. The generated filename this source map is associated with. + +```js +var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData); +``` + +#### SourceMapConsumer.prototype.computeColumnSpans() + +Compute the last column for each generated mapping. The last column is +inclusive. + +```js +// Before: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] + +consumer.computeColumnSpans(); + +// After: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1, +// lastColumn: 9 }, +// { line: 2, +// column: 10, +// lastColumn: 19 }, +// { line: 2, +// column: 20, +// lastColumn: Infinity } ] + +``` + +#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) + +Returns the original source, line, and column information for the generated +source's line and column positions provided. The only argument is an object with +the following properties: + +* `line`: The line number in the generated source. Line numbers in + this library are 1-based (note that the underlying source map + specification uses 0-based line numbers -- this library handles the + translation). + +* `column`: The column number in the generated source. Column numbers + in this library are 0-based. + +* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or + `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest + element that is smaller than or greater than the one we are searching for, + respectively, if the exact element cannot be found. Defaults to + `SourceMapConsumer.GREATEST_LOWER_BOUND`. + +and an object is returned with the following properties: + +* `source`: The original source file, or null if this information is not + available. + +* `line`: The line number in the original source, or null if this information is + not available. The line number is 1-based. + +* `column`: The column number in the original source, or null if this + information is not available. The column number is 0-based. + +* `name`: The original identifier, or null if this information is not available. + +```js +consumer.originalPositionFor({ line: 2, column: 10 }) +// { source: 'foo.coffee', +// line: 2, +// column: 2, +// name: null } + +consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) +// { source: null, +// line: null, +// column: null, +// name: null } +``` + +#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) + +Returns the generated line and column information for the original source, +line, and column positions provided. The only argument is an object with +the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: The column number in the original source. The column + number is 0-based. + +and an object is returned with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) +// { line: 1, +// column: 56 } +``` + +#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) + +Returns all generated line and column information for the original source, line, +and column provided. If no column is provided, returns all mappings +corresponding to a either the line we are searching for or the next closest line +that has any mappings. Otherwise, returns all mappings corresponding to the +given line and either the column we are searching for or the next closest column +that has any offsets. + +The only argument is an object with the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: Optional. The column number in the original source. The + column number is 0-based. + +and an array of objects is returned, each with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] +``` + +#### SourceMapConsumer.prototype.hasContentsOfAllSources() + +Return true if we have the embedded source content for every source listed in +the source map, false otherwise. + +In other words, if this method returns `true`, then +`consumer.sourceContentFor(s)` will succeed for every source `s` in +`consumer.sources`. + +```js +// ... +if (consumer.hasContentsOfAllSources()) { + consumerReadyCallback(consumer); +} else { + fetchSources(consumer, consumerReadyCallback); +} +// ... +``` + +#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) + +Returns the original source content for the source provided. The only +argument is the URL of the original source file. + +If the source content for the given source is not found, then an error is +thrown. Optionally, pass `true` as the second param to have `null` returned +instead. + +```js +consumer.sources +// [ "my-cool-lib.clj" ] + +consumer.sourceContentFor("my-cool-lib.clj") +// "..." + +consumer.sourceContentFor("this is not in the source map"); +// Error: "this is not in the source map" is not in the source map + +consumer.sourceContentFor("this is not in the source map", true); +// null +``` + +#### SourceMapConsumer.prototype.eachMapping(callback, context, order) + +Iterate over each mapping between an original source/line/column and a +generated line/column in this source map. + +* `callback`: The function that is called with each mapping. Mappings have the + form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, + name }` + +* `context`: Optional. If specified, this object will be the value of `this` + every time that `callback` is called. + +* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or + `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over + the mappings sorted by the generated file's line/column order or the + original's source/line/column order, respectively. Defaults to + `SourceMapConsumer.GENERATED_ORDER`. + +```js +consumer.eachMapping(function (m) { console.log(m); }) +// ... +// { source: 'illmatic.js', +// generatedLine: 1, +// generatedColumn: 0, +// originalLine: 1, +// originalColumn: 0, +// name: null } +// { source: 'illmatic.js', +// generatedLine: 2, +// generatedColumn: 0, +// originalLine: 2, +// originalColumn: 0, +// name: null } +// ... +``` +### SourceMapGenerator + +An instance of the SourceMapGenerator represents a source map which is being +built incrementally. + +#### new SourceMapGenerator([startOfSourceMap]) + +You may pass an object with the following properties: + +* `file`: The filename of the generated source that this source map is + associated with. + +* `sourceRoot`: A root for all relative URLs in this source map. + +* `skipValidation`: Optional. When `true`, disables validation of mappings as + they are added. This can improve performance but should be used with + discretion, as a last resort. Even then, one should avoid using this flag when + running tests, if possible. + +* `ignoreInvalidMapping`: Optional. When `true`, instead of throwing error on + invalid mapping, it will be ignored. + +```js +var generator = new sourceMap.SourceMapGenerator({ + file: "my-generated-javascript-file.js", + sourceRoot: "http://example.com/app/js/" +}); +``` + +#### SourceMapGenerator.fromSourceMap(sourceMapConsumer, sourceMapGeneratorOptions) + +Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. + +* `sourceMapConsumer` The SourceMap. + +* `sourceMapGeneratorOptions` options that will be passed to the SourceMapGenerator constructor which used under the hood. + +```js +var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer, { + ignoreInvalidMapping: true, +}); +``` + +#### SourceMapGenerator.prototype.addMapping(mapping) + +Add a single mapping from original source line and column to the generated +source's line and column for this source map being created. The mapping object +should have the following properties: + +* `generated`: An object with the generated line and column positions. + +* `original`: An object with the original line and column positions. + +* `source`: The original source file (relative to the sourceRoot). + +* `name`: An optional original token name for this mapping. + +```js +generator.addMapping({ + source: "module-one.scm", + original: { line: 128, column: 0 }, + generated: { line: 3, column: 456 } +}) +``` + +#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for an original source file. + +* `sourceFile` the URL of the original source file. + +* `sourceContent` the content of the source file. + +```js +generator.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) + +Applies a SourceMap for a source file to the SourceMap. +Each mapping to the supplied source file is rewritten using the +supplied SourceMap. Note: The resolution for the resulting mappings +is the minimum of this map and the supplied map. + +* `sourceMapConsumer`: The SourceMap to be applied. + +* `sourceFile`: Optional. The filename of the source file. + If omitted, sourceMapConsumer.file will be used, if it exists. + Otherwise an error will be thrown. + +* `sourceMapPath`: Optional. The dirname of the path to the SourceMap + to be applied. If relative, it is relative to the SourceMap. + + This parameter is needed when the two SourceMaps aren't in the same + directory, and the SourceMap to be applied contains relative source + paths. If so, those relative source paths need to be rewritten + relative to the SourceMap. + + If omitted, it is assumed that both SourceMaps are in the same directory, + thus not needing any rewriting. (Supplying `'.'` has the same effect.) + +#### SourceMapGenerator.prototype.toString() + +Renders the source map being generated to a string. + +```js +generator.toString() +// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' +``` + +### SourceNode + +SourceNodes provide a way to abstract over interpolating and/or concatenating +snippets of generated JavaScript source code, while maintaining the line and +column information associated between those snippets and the original source +code. This is useful as the final intermediate representation a compiler might +use before outputting the generated JS and source map. + +#### new SourceNode([line, column, source[, chunk[, name]]]) + +* `line`: The original line number associated with this source node, or null if + it isn't associated with an original line. The line number is 1-based. + +* `column`: The original column number associated with this source node, or null + if it isn't associated with an original column. The column number + is 0-based. + +* `source`: The original source's filename; null if no filename is provided. + +* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see + below. + +* `name`: Optional. The original identifier. + +```js +var node = new SourceNode(1, 2, "a.cpp", [ + new SourceNode(3, 4, "b.cpp", "extern int status;\n"), + new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), + new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), +]); +``` + +#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) + +Creates a SourceNode from generated code and a SourceMapConsumer. + +* `code`: The generated code + +* `sourceMapConsumer` The SourceMap for the generated code + +* `relativePath` The optional path that relative sources in `sourceMapConsumer` + should be relative to. + +```js +var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8")); +var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), + consumer); +``` + +#### SourceNode.prototype.add(chunk) + +Add a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.add(" + "); +node.add(otherNode); +node.add([leftHandOperandNode, " + ", rightHandOperandNode]); +``` + +#### SourceNode.prototype.prepend(chunk) + +Prepend a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.prepend("/** Build Id: f783haef86324gf **/\n\n"); +``` + +#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for a source file. This will be added to the +`SourceMap` in the `sourcesContent` field. + +* `sourceFile`: The filename of the source file + +* `sourceContent`: The content of the source file + +```js +node.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceNode.prototype.walk(fn) + +Walk over the tree of JS snippets in this node and its children. The walking +function is called once for each snippet of JS and is passed that snippet and +the its original associated source's line/column location. + +* `fn`: The traversal function. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.walk(function (code, loc) { console.log("WALK:", code, loc); }) +// WALK: uno { source: 'b.js', line: 3, column: 4, name: null } +// WALK: dos { source: 'a.js', line: 1, column: 2, name: null } +// WALK: tres { source: 'a.js', line: 1, column: 2, name: null } +// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } +``` + +#### SourceNode.prototype.walkSourceContents(fn) + +Walk over the tree of SourceNodes. The walking function is called for each +source file content and is passed the filename and source content. + +* `fn`: The traversal function. + +```js +var a = new SourceNode(1, 2, "a.js", "generated from a"); +a.setSourceContent("a.js", "original a"); +var b = new SourceNode(1, 2, "b.js", "generated from b"); +b.setSourceContent("b.js", "original b"); +var c = new SourceNode(1, 2, "c.js", "generated from c"); +c.setSourceContent("c.js", "original c"); + +var node = new SourceNode(null, null, null, [a, b, c]); +node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) +// WALK: a.js : original a +// WALK: b.js : original b +// WALK: c.js : original c +``` + +#### SourceNode.prototype.join(sep) + +Like `Array.prototype.join` except for SourceNodes. Inserts the separator +between each of this source node's children. + +* `sep`: The separator. + +```js +var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); +var operand = new SourceNode(3, 4, "a.rs", "="); +var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); + +var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); +var joinedNode = node.join(" "); +``` + +#### SourceNode.prototype.replaceRight(pattern, replacement) + +Call `String.prototype.replace` on the very right-most source snippet. Useful +for trimming white space from the end of a source node, etc. + +* `pattern`: The pattern to replace. + +* `replacement`: The thing to replace the pattern with. + +```js +// Trim trailing white space. +node.replaceRight(/\s*$/, ""); +``` + +#### SourceNode.prototype.toString() + +Return the string representation of this source node. Walks over the tree and +concatenates all the various snippets together to one string. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toString() +// 'unodostresquatro' +``` + +#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) + +Returns the string representation of this tree of source nodes, plus a +SourceMapGenerator which contains all the mappings between the generated and +original sources. + +The arguments are the same as those to `new SourceMapGenerator`. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toStringWithSourceMap({ file: "my-output-file.js" }) +// { code: 'unodostresquatro', +// map: [object SourceMapGenerator] } +``` diff --git a/node_modules/source-map-js/lib/array-set.js b/node_modules/source-map-js/lib/array-set.js new file mode 100644 index 0000000..fbd5c81 --- /dev/null +++ b/node_modules/source-map-js/lib/array-set.js @@ -0,0 +1,121 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var has = Object.prototype.hasOwnProperty; +var hasNativeMap = typeof Map !== "undefined"; + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); +} + +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; +}; + +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; +}; + +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } +}; + +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } +}; + +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); +}; + +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); +}; + +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; + +exports.ArraySet = ArraySet; diff --git a/node_modules/source-map-js/lib/base64-vlq.js b/node_modules/source-map-js/lib/base64-vlq.js new file mode 100644 index 0000000..612b404 --- /dev/null +++ b/node_modules/source-map-js/lib/base64-vlq.js @@ -0,0 +1,140 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +var base64 = require('./base64'); + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 + +var VLQ_BASE_SHIFT = 5; + +// binary: 100000 +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + +// binary: 011111 +var VLQ_BASE_MASK = VLQ_BASE - 1; + +// binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} + +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; +} + +/** + * Returns the base 64 VLQ encoded value. + */ +exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; +}; + +/** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ +exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; +}; diff --git a/node_modules/source-map-js/lib/base64.js b/node_modules/source-map-js/lib/base64.js new file mode 100644 index 0000000..8aa86b3 --- /dev/null +++ b/node_modules/source-map-js/lib/base64.js @@ -0,0 +1,67 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); +}; + +/** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ +exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; +}; diff --git a/node_modules/source-map-js/lib/binary-search.js b/node_modules/source-map-js/lib/binary-search.js new file mode 100644 index 0000000..010ac94 --- /dev/null +++ b/node_modules/source-map-js/lib/binary-search.js @@ -0,0 +1,111 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; + +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } +} + +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; +}; diff --git a/node_modules/source-map-js/lib/mapping-list.js b/node_modules/source-map-js/lib/mapping-list.js new file mode 100644 index 0000000..06d1274 --- /dev/null +++ b/node_modules/source-map-js/lib/mapping-list.js @@ -0,0 +1,79 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} + +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; +} + +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } +}; + +/** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; +}; + +exports.MappingList = MappingList; diff --git a/node_modules/source-map-js/lib/quick-sort.js b/node_modules/source-map-js/lib/quick-sort.js new file mode 100644 index 0000000..23f9eda --- /dev/null +++ b/node_modules/source-map-js/lib/quick-sort.js @@ -0,0 +1,132 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. + +function SortTemplate(comparator) { + +/** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; +} + +/** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); +} + +/** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ +function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot, false) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } +} + + return doQuickSort; +} + +function cloneSort(comparator) { + let template = SortTemplate.toString(); + let templateFn = new Function(`return ${template}`)(); + return templateFn(comparator); +} + +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + +let sortCache = new WeakMap(); +exports.quickSort = function (ary, comparator, start = 0) { + let doQuickSort = sortCache.get(comparator); + if (doQuickSort === void 0) { + doQuickSort = cloneSort(comparator); + sortCache.set(comparator, doQuickSort); + } + doQuickSort(ary, comparator, start, ary.length - 1); +}; diff --git a/node_modules/source-map-js/lib/source-map-consumer.d.ts b/node_modules/source-map-js/lib/source-map-consumer.d.ts new file mode 100644 index 0000000..744bda7 --- /dev/null +++ b/node_modules/source-map-js/lib/source-map-consumer.d.ts @@ -0,0 +1 @@ +export { SourceMapConsumer } from '..'; diff --git a/node_modules/source-map-js/lib/source-map-consumer.js b/node_modules/source-map-js/lib/source-map-consumer.js new file mode 100644 index 0000000..ee66114 --- /dev/null +++ b/node_modules/source-map-js/lib/source-map-consumer.js @@ -0,0 +1,1188 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var binarySearch = require('./binary-search'); +var ArraySet = require('./array-set').ArraySet; +var base64VLQ = require('./base64-vlq'); +var quickSort = require('./quick-sort').quickSort; + +function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); +} + +SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); +} + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer.prototype._version = 3; + +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. + +SourceMapConsumer.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } +}); + +SourceMapConsumer.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } +}); + +SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + +SourceMapConsumer.GENERATED_ORDER = 1; +SourceMapConsumer.ORIGINAL_ORDER = 2; + +SourceMapConsumer.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer.LEAST_UPPER_BOUND = 2; + +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ +SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + var boundCallback = aCallback.bind(context); + var names = this._names; + var sources = this._sources; + var sourceMapURL = this._sourceMapURL; + + for (var i = 0, n = mappings.length; i < n; i++) { + var mapping = mappings[i]; + var source = mapping.source === null ? null : sources.at(mapping.source); + if(source !== null) { + source = util.computeSourceURL(sourceRoot, source, sourceMapURL); + } + boundCallback({ + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : names.at(mapping.name) + }); + } + }; + +/** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + +exports.SourceMapConsumer = SourceMapConsumer; + +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; +} + +BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + +/** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ +BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; +}; + +/** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ +BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + +/** + * The version of the source mapping spec that we are consuming. + */ +BasicSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } +}); + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + +const compareGenerated = util.compareByGeneratedPositionsDeflatedNoLine; +function sortGenerated(array, start) { + let l = array.length; + let n = array.length - start; + if (n <= 1) { + return; + } else if (n == 2) { + let a = array[start]; + let b = array[start + 1]; + if (compareGenerated(a, b) > 0) { + array[start] = b; + array[start + 1] = a; + } + } else if (n < 20) { + for (let i = start; i < l; i++) { + for (let j = i; j > start; j--) { + let a = array[j - 1]; + let b = array[j]; + if (compareGenerated(a, b) <= 0) { + break; + } + array[j - 1] = b; + array[j] = a; + } + } + } else { + quickSort(array, compareGenerated, start); + } +} +BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + let subarrayStart = 0; + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + + sortGenerated(generatedMappings, subarrayStart); + subarrayStart = generatedMappings.length; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + let currentSource = mapping.source; + while (originalMappings.length <= currentSource) { + originalMappings.push(null); + } + if (originalMappings[currentSource] === null) { + originalMappings[currentSource] = []; + } + originalMappings[currentSource].push(mapping); + } + } + } + + sortGenerated(generatedMappings, subarrayStart); + this.__generatedMappings = generatedMappings; + + for (var i = 0; i < originalMappings.length; i++) { + if (originalMappings[i] != null) { + quickSort(originalMappings[i], util.compareByOriginalPositionsNoSource); + } + } + this.__originalMappings = [].concat(...originalMappings); + }; + +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + +exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); +} + +IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + +/** + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } +}); + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content || content === '') { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + if(source !== null) { + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + } + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + +exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; diff --git a/node_modules/source-map-js/lib/source-map-generator.d.ts b/node_modules/source-map-js/lib/source-map-generator.d.ts new file mode 100644 index 0000000..f59d70a --- /dev/null +++ b/node_modules/source-map-js/lib/source-map-generator.d.ts @@ -0,0 +1 @@ +export { SourceMapGenerator } from '..'; diff --git a/node_modules/source-map-js/lib/source-map-generator.js b/node_modules/source-map-js/lib/source-map-generator.js new file mode 100644 index 0000000..bab04ff --- /dev/null +++ b/node_modules/source-map-js/lib/source-map-generator.js @@ -0,0 +1,444 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var base64VLQ = require('./base64-vlq'); +var util = require('./util'); +var ArraySet = require('./array-set').ArraySet; +var MappingList = require('./mapping-list').MappingList; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._ignoreInvalidMapping = util.getArg(aArgs, 'ignoreInvalidMapping', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; +} + +SourceMapGenerator.prototype._version = 3; + +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer, generatorOps) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator(Object.assign(generatorOps || {}, { + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + })); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + +/** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ +SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + if (this._validateMapping(generated, original, source, name) === false) { + return; + } + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + +/** + * Set the source content for a source file. + */ +SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + var message = 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + + if (this._ignoreInvalidMapping) { + if (typeof console !== 'undefined' && console.warn) { + console.warn(message); + } + return false; + } else { + throw new Error(message); + } + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + var message = 'Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + }); + + if (this._ignoreInvalidMapping) { + if (typeof console !== 'undefined' && console.warn) { + console.warn(message); + } + return false; + } else { + throw new Error(message) + } + } + }; + +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + +SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + +/** + * Externalize the source map. + */ +SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + +exports.SourceMapGenerator = SourceMapGenerator; diff --git a/node_modules/source-map-js/lib/source-node.d.ts b/node_modules/source-map-js/lib/source-node.d.ts new file mode 100644 index 0000000..4df6a1a --- /dev/null +++ b/node_modules/source-map-js/lib/source-node.d.ts @@ -0,0 +1 @@ +export { SourceNode } from '..'; diff --git a/node_modules/source-map-js/lib/source-node.js b/node_modules/source-map-js/lib/source-node.js new file mode 100644 index 0000000..8bcdbe3 --- /dev/null +++ b/node_modules/source-map-js/lib/source-node.js @@ -0,0 +1,413 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; +var util = require('./util'); + +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE = /(\r?\n)/; + +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE = 10; + +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode = "$$$isSourceNode$$$"; + +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); +} + +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ +SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + +/** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } +}; + +/** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ +SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; +}; + +/** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ +SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; +}; + +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + +/** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + +/** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ +SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; + +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; +}; + +exports.SourceNode = SourceNode; diff --git a/node_modules/source-map-js/lib/util.js b/node_modules/source-map-js/lib/util.js new file mode 100644 index 0000000..430e2d0 --- /dev/null +++ b/node_modules/source-map-js/lib/util.js @@ -0,0 +1,594 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } +} +exports.getArg = getArg; + +var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; +var dataUrlRegexp = /^data:.+\,.+$/; + +function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +var MAX_CACHED_INPUTS = 32; + +/** + * Takes some function `f(input) -> result` and returns a memoized version of + * `f`. + * + * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The + * memoization is a dumb-simple, linear least-recently-used cache. + */ +function lruMemoize(f) { + var cache = []; + + return function(input) { + for (var i = 0; i < cache.length; i++) { + if (cache[i].input === input) { + var temp = cache[0]; + cache[0] = cache[i]; + cache[i] = temp; + return cache[0].result; + } + } + + var result = f(input); + + cache.unshift({ + input, + result, + }); + + if (cache.length > MAX_CACHED_INPUTS) { + cache.pop(); + } + + return result; + }; +} + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +var normalize = lruMemoize(function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + // Split the path into parts between `/` characters. This is much faster than + // using `.split(/\/+/g)`. + var parts = []; + var start = 0; + var i = 0; + while (true) { + start = i; + i = path.indexOf("/", start); + if (i === -1) { + parts.push(path.slice(start)); + break; + } else { + parts.push(path.slice(start, i)); + while (i < path.length && path[i] === "/") { + i++; + } + } + } + + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +}); +exports.normalize = normalize; + +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; + +exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); +}; + +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; + +var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); +}()); + +function identity (s) { + return s; +} + +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; + +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; + +function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; +} + +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositions = compareByOriginalPositions; + +function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) { + var cmp + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource; + +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + +function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine; + +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; +} + +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + +/** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ +function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); +} +exports.parseSourceMapInput = parseSourceMapInput; + +/** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ +function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); +} +exports.computeSourceURL = computeSourceURL; diff --git a/node_modules/source-map-js/package.json b/node_modules/source-map-js/package.json new file mode 100644 index 0000000..f58dbeb --- /dev/null +++ b/node_modules/source-map-js/package.json @@ -0,0 +1,71 @@ +{ + "name": "source-map-js", + "description": "Generates and consumes source maps", + "version": "1.2.1", + "homepage": "https://github.com/7rulnik/source-map-js", + "author": "Valentin 7rulnik Semirulnik ", + "contributors": [ + "Nick Fitzgerald ", + "Tobias Koppers ", + "Duncan Beevers ", + "Stephen Crane ", + "Ryan Seddon ", + "Miles Elam ", + "Mihai Bazon ", + "Michael Ficarra ", + "Todd Wolfson ", + "Alexander Solovyov ", + "Felix Gnass ", + "Conrad Irwin ", + "usrbincc ", + "David Glasser ", + "Chase Douglas ", + "Evan Wallace ", + "Heather Arthur ", + "Hugh Kennedy ", + "David Glasser ", + "Simon Lydell ", + "Jmeas Smith ", + "Michael Z Goddard ", + "azu ", + "John Gozde ", + "Adam Kirkton ", + "Chris Montgomery ", + "J. Ryan Stinnett ", + "Jack Herrington ", + "Chris Truter ", + "Daniel Espeset ", + "Jamie Wong ", + "Eddy Bruël ", + "Hawken Rives ", + "Gilad Peleg ", + "djchie ", + "Gary Ye ", + "Nicolas Lalevée " + ], + "repository": "7rulnik/source-map-js", + "main": "./source-map.js", + "files": [ + "source-map.js", + "source-map.d.ts", + "lib/" + ], + "engines": { + "node": ">=0.10.0" + }, + "license": "BSD-3-Clause", + "scripts": { + "test": "npm run build && node test/run-tests.js", + "build": "webpack --color", + "toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md" + }, + "devDependencies": { + "clean-publish": "^3.1.0", + "doctoc": "^0.15.0", + "webpack": "^1.12.0" + }, + "clean-publish": { + "cleanDocs": true + }, + "typings": "source-map.d.ts" +} diff --git a/node_modules/source-map-js/source-map.d.ts b/node_modules/source-map-js/source-map.d.ts new file mode 100644 index 0000000..ec8892f --- /dev/null +++ b/node_modules/source-map-js/source-map.d.ts @@ -0,0 +1,104 @@ +export interface StartOfSourceMap { + file?: string; + sourceRoot?: string; +} + +export interface RawSourceMap extends StartOfSourceMap { + version: string; + sources: string[]; + names: string[]; + sourcesContent?: string[]; + mappings: string; +} + +export interface Position { + line: number; + column: number; +} + +export interface LineRange extends Position { + lastColumn: number; +} + +export interface FindPosition extends Position { + // SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND + bias?: number; +} + +export interface SourceFindPosition extends FindPosition { + source: string; +} + +export interface MappedPosition extends Position { + source: string; + name?: string; +} + +export interface MappingItem { + source: string | null; + generatedLine: number; + generatedColumn: number; + originalLine: number | null; + originalColumn: number | null; + name: string | null; +} + +export class SourceMapConsumer { + static GENERATED_ORDER: number; + static ORIGINAL_ORDER: number; + + static GREATEST_LOWER_BOUND: number; + static LEAST_UPPER_BOUND: number; + + constructor(rawSourceMap: RawSourceMap); + readonly file: string | undefined | null; + readonly sourceRoot: string | undefined | null; + readonly sourcesContent: readonly string[] | null | undefined; + readonly sources: readonly string[] + + computeColumnSpans(): void; + originalPositionFor(generatedPosition: FindPosition): MappedPosition; + generatedPositionFor(originalPosition: SourceFindPosition): LineRange; + allGeneratedPositionsFor(originalPosition: MappedPosition): Position[]; + hasContentsOfAllSources(): boolean; + sourceContentFor(source: string, returnNullOnMissing?: boolean): string | null; + eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void; +} + +export interface Mapping { + generated: Position; + original?: Position | null; + source?: string | null; + name?: string | null; +} + +export class SourceMapGenerator { + constructor(startOfSourceMap?: StartOfSourceMap); + static fromSourceMap(sourceMapConsumer: SourceMapConsumer, startOfSourceMap?: StartOfSourceMap): SourceMapGenerator; + addMapping(mapping: Mapping): void; + setSourceContent(sourceFile: string, sourceContent: string | null | undefined): void; + applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void; + toString(): string; + toJSON(): RawSourceMap; +} + +export interface CodeWithSourceMap { + code: string; + map: SourceMapGenerator; +} + +export class SourceNode { + constructor(); + constructor(line: number, column: number, source: string); + constructor(line: number, column: number, source: string, chunk?: string, name?: string); + static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode; + add(chunk: string): void; + prepend(chunk: string): void; + setSourceContent(sourceFile: string, sourceContent: string): void; + walk(fn: (chunk: string, mapping: MappedPosition) => void): void; + walkSourceContents(fn: (file: string, content: string) => void): void; + join(sep: string): SourceNode; + replaceRight(pattern: string, replacement: string): SourceNode; + toString(): string; + toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap; +} diff --git a/node_modules/source-map-js/source-map.js b/node_modules/source-map-js/source-map.js new file mode 100644 index 0000000..bc88fe8 --- /dev/null +++ b/node_modules/source-map-js/source-map.js @@ -0,0 +1,8 @@ +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; +exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; +exports.SourceNode = require('./lib/source-node').SourceNode; diff --git a/node_modules/spdx-correct/LICENSE b/node_modules/spdx-correct/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/spdx-correct/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/spdx-correct/README.md b/node_modules/spdx-correct/README.md new file mode 100644 index 0000000..af563d8 --- /dev/null +++ b/node_modules/spdx-correct/README.md @@ -0,0 +1,22 @@ +## Usage + +```javascript +var correct = require('spdx-correct') +var assert = require('assert') + +assert.strictEqual(correct('mit'), 'MIT') + +assert.strictEqual(correct('Apache 2'), 'Apache-2.0') + +assert(correct('No idea what license') === null) + +// disable upgrade option +assert(correct('GPL-3.0'), 'GPL-3.0-or-later') +assert(correct('GPL-3.0', { upgrade: false }), 'GPL-3.0') +``` + +## Contributors + +spdx-correct has benefited from the work of several contributors. +See [the GitHub repository](https://github.com/jslicense/spdx-correct.js/graphs/contributors) +for more information. diff --git a/node_modules/spdx-correct/index.js b/node_modules/spdx-correct/index.js new file mode 100644 index 0000000..4d9037e --- /dev/null +++ b/node_modules/spdx-correct/index.js @@ -0,0 +1,386 @@ +/* +Copyright spdx-correct.js contributors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +var parse = require('spdx-expression-parse') +var spdxLicenseIds = require('spdx-license-ids') + +function valid (string) { + try { + parse(string) + return true + } catch (error) { + return false + } +} + +// Sorting function that orders the given array of transpositions such +// that a transposition with the longer pattern comes before a transposition +// with a shorter pattern. This is to prevent e.g. the transposition +// ["General Public License", "GPL"] from matching to "Lesser General Public License" +// before a longer and more accurate transposition ["Lesser General Public License", "LGPL"] +// has a chance to be recognized. +function sortTranspositions(a, b) { + var length = b[0].length - a[0].length + if (length !== 0) return length + return a[0].toUpperCase().localeCompare(b[0].toUpperCase()) +} + +// Common transpositions of license identifier acronyms +var transpositions = [ + ['APGL', 'AGPL'], + ['Gpl', 'GPL'], + ['GLP', 'GPL'], + ['APL', 'Apache'], + ['ISD', 'ISC'], + ['GLP', 'GPL'], + ['IST', 'ISC'], + ['Claude', 'Clause'], + [' or later', '+'], + [' International', ''], + ['GNU', 'GPL'], + ['GUN', 'GPL'], + ['+', ''], + ['GNU GPL', 'GPL'], + ['GNU LGPL', 'LGPL'], + ['GNU/GPL', 'GPL'], + ['GNU GLP', 'GPL'], + ['GNU LESSER GENERAL PUBLIC LICENSE', 'LGPL'], + ['GNU Lesser General Public License', 'LGPL'], + ['GNU LESSER GENERAL PUBLIC LICENSE', 'LGPL-2.1'], + ['GNU Lesser General Public License', 'LGPL-2.1'], + ['LESSER GENERAL PUBLIC LICENSE', 'LGPL'], + ['Lesser General Public License', 'LGPL'], + ['LESSER GENERAL PUBLIC LICENSE', 'LGPL-2.1'], + ['Lesser General Public License', 'LGPL-2.1'], + ['GNU General Public License', 'GPL'], + ['Gnu public license', 'GPL'], + ['GNU Public License', 'GPL'], + ['GNU GENERAL PUBLIC LICENSE', 'GPL'], + ['MTI', 'MIT'], + ['Mozilla Public License', 'MPL'], + ['Universal Permissive License', 'UPL'], + ['WTH', 'WTF'], + ['WTFGPL', 'WTFPL'], + ['-License', ''] +].sort(sortTranspositions) + +var TRANSPOSED = 0 +var CORRECT = 1 + +// Simple corrections to nearly valid identifiers. +var transforms = [ + // e.g. 'mit' + function (argument) { + return argument.toUpperCase() + }, + // e.g. 'MIT ' + function (argument) { + return argument.trim() + }, + // e.g. 'M.I.T.' + function (argument) { + return argument.replace(/\./g, '') + }, + // e.g. 'Apache- 2.0' + function (argument) { + return argument.replace(/\s+/g, '') + }, + // e.g. 'CC BY 4.0'' + function (argument) { + return argument.replace(/\s+/g, '-') + }, + // e.g. 'LGPLv2.1' + function (argument) { + return argument.replace('v', '-') + }, + // e.g. 'Apache 2.0' + function (argument) { + return argument.replace(/,?\s*(\d)/, '-$1') + }, + // e.g. 'GPL 2' + function (argument) { + return argument.replace(/,?\s*(\d)/, '-$1.0') + }, + // e.g. 'Apache Version 2.0' + function (argument) { + return argument + .replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, '-$2') + }, + // e.g. 'Apache Version 2' + function (argument) { + return argument + .replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, '-$2.0') + }, + // e.g. 'ZLIB' + function (argument) { + return argument[0].toUpperCase() + argument.slice(1) + }, + // e.g. 'MPL/2.0' + function (argument) { + return argument.replace('/', '-') + }, + // e.g. 'Apache 2' + function (argument) { + return argument + .replace(/\s*V\s*(\d)/, '-$1') + .replace(/(\d)$/, '$1.0') + }, + // e.g. 'GPL-2.0', 'GPL-3.0' + function (argument) { + if (argument.indexOf('3.0') !== -1) { + return argument + '-or-later' + } else { + return argument + '-only' + } + }, + // e.g. 'GPL-2.0-' + function (argument) { + return argument + 'only' + }, + // e.g. 'GPL2' + function (argument) { + return argument.replace(/(\d)$/, '-$1.0') + }, + // e.g. 'BSD 3' + function (argument) { + return argument.replace(/(-| )?(\d)$/, '-$2-Clause') + }, + // e.g. 'BSD clause 3' + function (argument) { + return argument.replace(/(-| )clause(-| )(\d)/, '-$3-Clause') + }, + // e.g. 'New BSD license' + function (argument) { + return argument.replace(/\b(Modified|New|Revised)(-| )?BSD((-| )License)?/i, 'BSD-3-Clause') + }, + // e.g. 'Simplified BSD license' + function (argument) { + return argument.replace(/\bSimplified(-| )?BSD((-| )License)?/i, 'BSD-2-Clause') + }, + // e.g. 'Free BSD license' + function (argument) { + return argument.replace(/\b(Free|Net)(-| )?BSD((-| )License)?/i, 'BSD-2-Clause-$1BSD') + }, + // e.g. 'Clear BSD license' + function (argument) { + return argument.replace(/\bClear(-| )?BSD((-| )License)?/i, 'BSD-3-Clause-Clear') + }, + // e.g. 'Old BSD License' + function (argument) { + return argument.replace(/\b(Old|Original)(-| )?BSD((-| )License)?/i, 'BSD-4-Clause') + }, + // e.g. 'BY-NC-4.0' + function (argument) { + return 'CC-' + argument + }, + // e.g. 'BY-NC' + function (argument) { + return 'CC-' + argument + '-4.0' + }, + // e.g. 'Attribution-NonCommercial' + function (argument) { + return argument + .replace('Attribution', 'BY') + .replace('NonCommercial', 'NC') + .replace('NoDerivatives', 'ND') + .replace(/ (\d)/, '-$1') + .replace(/ ?International/, '') + }, + // e.g. 'Attribution-NonCommercial' + function (argument) { + return 'CC-' + + argument + .replace('Attribution', 'BY') + .replace('NonCommercial', 'NC') + .replace('NoDerivatives', 'ND') + .replace(/ (\d)/, '-$1') + .replace(/ ?International/, '') + + '-4.0' + } +] + +var licensesWithVersions = spdxLicenseIds + .map(function (id) { + var match = /^(.*)-\d+\.\d+$/.exec(id) + return match + ? [match[0], match[1]] + : [id, null] + }) + .reduce(function (objectMap, item) { + var key = item[1] + objectMap[key] = objectMap[key] || [] + objectMap[key].push(item[0]) + return objectMap + }, {}) + +var licensesWithOneVersion = Object.keys(licensesWithVersions) + .map(function makeEntries (key) { + return [key, licensesWithVersions[key]] + }) + .filter(function identifySoleVersions (item) { + return ( + // Licenses has just one valid version suffix. + item[1].length === 1 && + item[0] !== null && + // APL will be considered Apache, rather than APL-1.0 + item[0] !== 'APL' + ) + }) + .map(function createLastResorts (item) { + return [item[0], item[1][0]] + }) + +licensesWithVersions = undefined + +// If all else fails, guess that strings containing certain substrings +// meant to identify certain licenses. +var lastResorts = [ + ['UNLI', 'Unlicense'], + ['WTF', 'WTFPL'], + ['2 CLAUSE', 'BSD-2-Clause'], + ['2-CLAUSE', 'BSD-2-Clause'], + ['3 CLAUSE', 'BSD-3-Clause'], + ['3-CLAUSE', 'BSD-3-Clause'], + ['AFFERO', 'AGPL-3.0-or-later'], + ['AGPL', 'AGPL-3.0-or-later'], + ['APACHE', 'Apache-2.0'], + ['ARTISTIC', 'Artistic-2.0'], + ['Affero', 'AGPL-3.0-or-later'], + ['BEER', 'Beerware'], + ['BOOST', 'BSL-1.0'], + ['BSD', 'BSD-2-Clause'], + ['CDDL', 'CDDL-1.1'], + ['ECLIPSE', 'EPL-1.0'], + ['FUCK', 'WTFPL'], + ['GNU', 'GPL-3.0-or-later'], + ['LGPL', 'LGPL-3.0-or-later'], + ['GPLV1', 'GPL-1.0-only'], + ['GPL-1', 'GPL-1.0-only'], + ['GPLV2', 'GPL-2.0-only'], + ['GPL-2', 'GPL-2.0-only'], + ['GPL', 'GPL-3.0-or-later'], + ['MIT +NO-FALSE-ATTRIBS', 'MITNFA'], + ['MIT', 'MIT'], + ['MPL', 'MPL-2.0'], + ['X11', 'X11'], + ['ZLIB', 'Zlib'] +].concat(licensesWithOneVersion).sort(sortTranspositions) + +var SUBSTRING = 0 +var IDENTIFIER = 1 + +var validTransformation = function (identifier) { + for (var i = 0; i < transforms.length; i++) { + var transformed = transforms[i](identifier).trim() + if (transformed !== identifier && valid(transformed)) { + return transformed + } + } + return null +} + +var validLastResort = function (identifier) { + var upperCased = identifier.toUpperCase() + for (var i = 0; i < lastResorts.length; i++) { + var lastResort = lastResorts[i] + if (upperCased.indexOf(lastResort[SUBSTRING]) > -1) { + return lastResort[IDENTIFIER] + } + } + return null +} + +var anyCorrection = function (identifier, check) { + for (var i = 0; i < transpositions.length; i++) { + var transposition = transpositions[i] + var transposed = transposition[TRANSPOSED] + if (identifier.indexOf(transposed) > -1) { + var corrected = identifier.replace( + transposed, + transposition[CORRECT] + ) + var checked = check(corrected) + if (checked !== null) { + return checked + } + } + } + return null +} + +module.exports = function (identifier, options) { + options = options || {} + var upgrade = options.upgrade === undefined ? true : !!options.upgrade + function postprocess (value) { + return upgrade ? upgradeGPLs(value) : value + } + var validArugment = ( + typeof identifier === 'string' && + identifier.trim().length !== 0 + ) + if (!validArugment) { + throw Error('Invalid argument. Expected non-empty string.') + } + identifier = identifier.trim() + if (valid(identifier)) { + return postprocess(identifier) + } + var noPlus = identifier.replace(/\+$/, '').trim() + if (valid(noPlus)) { + return postprocess(noPlus) + } + var transformed = validTransformation(identifier) + if (transformed !== null) { + return postprocess(transformed) + } + transformed = anyCorrection(identifier, function (argument) { + if (valid(argument)) { + return argument + } + return validTransformation(argument) + }) + if (transformed !== null) { + return postprocess(transformed) + } + transformed = validLastResort(identifier) + if (transformed !== null) { + return postprocess(transformed) + } + transformed = anyCorrection(identifier, validLastResort) + if (transformed !== null) { + return postprocess(transformed) + } + return null +} + +function upgradeGPLs (value) { + if ([ + 'GPL-1.0', 'LGPL-1.0', 'AGPL-1.0', + 'GPL-2.0', 'LGPL-2.0', 'AGPL-2.0', + 'LGPL-2.1' + ].indexOf(value) !== -1) { + return value + '-only' + } else if ([ + 'GPL-1.0+', 'GPL-2.0+', 'GPL-3.0+', + 'LGPL-2.0+', 'LGPL-2.1+', 'LGPL-3.0+', + 'AGPL-1.0+', 'AGPL-3.0+' + ].indexOf(value) !== -1) { + return value.replace(/\+$/, '-or-later') + } else if (['GPL-3.0', 'LGPL-3.0', 'AGPL-3.0'].indexOf(value) !== -1) { + return value + '-or-later' + } else { + return value + } +} diff --git a/node_modules/spdx-correct/package.json b/node_modules/spdx-correct/package.json new file mode 100644 index 0000000..d776156 --- /dev/null +++ b/node_modules/spdx-correct/package.json @@ -0,0 +1,32 @@ +{ + "name": "spdx-correct", + "description": "correct invalid SPDX expressions", + "version": "3.2.0", + "dependencies": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + }, + "devDependencies": { + "defence-cli": "^3.0.1", + "replace-require-self": "^1.0.0", + "standard": "^14.3.4", + "standard-markdown": "^6.0.0", + "tape": "^5.0.1" + }, + "files": [ + "index.js" + ], + "keywords": [ + "SPDX", + "law", + "legal", + "license", + "metadata" + ], + "license": "Apache-2.0", + "repository": "jslicense/spdx-correct.js", + "scripts": { + "lint": "standard && standard-markdown README.md", + "test": "defence README.md | replace-require-self | node && node test.js" + } +} diff --git a/node_modules/spdx-exceptions/README.md b/node_modules/spdx-exceptions/README.md new file mode 100644 index 0000000..6c927ec --- /dev/null +++ b/node_modules/spdx-exceptions/README.md @@ -0,0 +1,36 @@ +The package exports an array of strings. Each string is an identifier +for a license exception under the [Software Package Data Exchange +(SPDX)][SPDX] software license metadata standard. + +[SPDX]: https://spdx.org + +## Copyright and Licensing + +### SPDX + +"SPDX" is a federally registered United States trademark of The Linux +Foundation Corporation. + +From version 2.0 of the [SPDX] specification: + +> Copyright © 2010-2015 Linux Foundation and its Contributors. Licensed +> under the Creative Commons Attribution License 3.0 Unported. All other +> rights are expressly reserved. + +The Linux Foundation and the SPDX working groups are good people. Only +they decide what "SPDX" means, as a standard and otherwise. I respect +their work and their rights. You should, too. + +### This Package + +> I created this package by copying exception identifiers out of the +> SPDX specification. That work was mechanical, routine, and required no +> creativity whatsoever. - Kyle Mitchell, package author + +United States users concerned about intellectual property may wish to +discuss the following Supreme Court decisions with their attorneys: + +- _Baker v. Selden_, 101 U.S. 99 (1879) + +- _Feist Publications, Inc., v. Rural Telephone Service Co._, + 499 U.S. 340 (1991) diff --git a/node_modules/spdx-exceptions/deprecated.json b/node_modules/spdx-exceptions/deprecated.json new file mode 100644 index 0000000..cba7e2b --- /dev/null +++ b/node_modules/spdx-exceptions/deprecated.json @@ -0,0 +1,3 @@ +[ + "Nokia-Qt-exception-1.1" +] diff --git a/node_modules/spdx-exceptions/index.json b/node_modules/spdx-exceptions/index.json new file mode 100644 index 0000000..d9549d3 --- /dev/null +++ b/node_modules/spdx-exceptions/index.json @@ -0,0 +1,68 @@ +[ + "389-exception", + "Asterisk-exception", + "Autoconf-exception-2.0", + "Autoconf-exception-3.0", + "Autoconf-exception-generic", + "Autoconf-exception-generic-3.0", + "Autoconf-exception-macro", + "Bison-exception-1.24", + "Bison-exception-2.2", + "Bootloader-exception", + "Classpath-exception-2.0", + "CLISP-exception-2.0", + "cryptsetup-OpenSSL-exception", + "DigiRule-FOSS-exception", + "eCos-exception-2.0", + "Fawkes-Runtime-exception", + "FLTK-exception", + "fmt-exception", + "Font-exception-2.0", + "freertos-exception-2.0", + "GCC-exception-2.0", + "GCC-exception-2.0-note", + "GCC-exception-3.1", + "Gmsh-exception", + "GNAT-exception", + "GNOME-examples-exception", + "GNU-compiler-exception", + "gnu-javamail-exception", + "GPL-3.0-interface-exception", + "GPL-3.0-linking-exception", + "GPL-3.0-linking-source-exception", + "GPL-CC-1.0", + "GStreamer-exception-2005", + "GStreamer-exception-2008", + "i2p-gpl-java-exception", + "KiCad-libraries-exception", + "LGPL-3.0-linking-exception", + "libpri-OpenH323-exception", + "Libtool-exception", + "Linux-syscall-note", + "LLGPL", + "LLVM-exception", + "LZMA-exception", + "mif-exception", + "OCaml-LGPL-linking-exception", + "OCCT-exception-1.0", + "OpenJDK-assembly-exception-1.0", + "openvpn-openssl-exception", + "PS-or-PDF-font-exception-20170817", + "QPL-1.0-INRIA-2004-exception", + "Qt-GPL-exception-1.0", + "Qt-LGPL-exception-1.1", + "Qwt-exception-1.0", + "SANE-exception", + "SHL-2.0", + "SHL-2.1", + "stunnel-exception", + "SWI-exception", + "Swift-exception", + "Texinfo-exception", + "u-boot-exception-2.0", + "UBDL-exception", + "Universal-FOSS-exception-1.0", + "vsftpd-openssl-exception", + "WxWindows-exception-3.1", + "x11vnc-openssl-exception" +] diff --git a/node_modules/spdx-exceptions/package.json b/node_modules/spdx-exceptions/package.json new file mode 100644 index 0000000..2f9a950 --- /dev/null +++ b/node_modules/spdx-exceptions/package.json @@ -0,0 +1,19 @@ +{ + "name": "spdx-exceptions", + "description": "list of SPDX standard license exceptions", + "version": "2.5.0", + "author": "The Linux Foundation", + "contributors": [ + "Kyle E. Mitchell (https://kemitchell.com/)" + ], + "license": "CC-BY-3.0", + "repository": "kemitchell/spdx-exceptions.json", + "files": [ + "index.json", + "deprecated.json" + ], + "scripts": { + "build": "node build.js", + "latest": "node latest.js" + } +} diff --git a/node_modules/spdx-expression-parse/AUTHORS b/node_modules/spdx-expression-parse/AUTHORS new file mode 100644 index 0000000..257a76b --- /dev/null +++ b/node_modules/spdx-expression-parse/AUTHORS @@ -0,0 +1,4 @@ +C. Scott Ananian (http://cscott.net) +Kyle E. Mitchell (https://kemitchell.com) +Shinnosuke Watanabe +Antoine Motet diff --git a/node_modules/spdx-expression-parse/LICENSE b/node_modules/spdx-expression-parse/LICENSE new file mode 100644 index 0000000..831618e --- /dev/null +++ b/node_modules/spdx-expression-parse/LICENSE @@ -0,0 +1,22 @@ +The MIT License + +Copyright (c) 2015 Kyle E. Mitchell & other authors listed in AUTHORS + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/spdx-expression-parse/README.md b/node_modules/spdx-expression-parse/README.md new file mode 100644 index 0000000..9406462 --- /dev/null +++ b/node_modules/spdx-expression-parse/README.md @@ -0,0 +1,91 @@ +This package parses [SPDX license expression](https://spdx.org/spdx-specification-21-web-version#h.jxpfx0ykyb60) strings describing license terms, like [package.json license strings](https://docs.npmjs.com/files/package.json#license), into consistently structured ECMAScript objects. The npm command-line interface depends on this package, as do many automatic license-audit tools. + +In a nutshell: + +```javascript +var parse = require('spdx-expression-parse') +var assert = require('assert') + +assert.deepEqual( + // Licensed under the terms of the Two-Clause BSD License. + parse('BSD-2-Clause'), + {license: 'BSD-2-Clause'} +) + +assert.throws(function () { + // An invalid SPDX license expression. + // Should be `Apache-2.0`. + parse('Apache 2') +}) + +assert.deepEqual( + // Dual licensed under either: + // - LGPL 2.1 + // - a combination of Three-Clause BSD and MIT + parse('(LGPL-2.1 OR BSD-3-Clause AND MIT)'), + { + left: {license: 'LGPL-2.1'}, + conjunction: 'or', + right: { + left: {license: 'BSD-3-Clause'}, + conjunction: 'and', + right: {license: 'MIT'} + } + } +) +``` + +The syntax comes from the [Software Package Data eXchange (SPDX)](https://spdx.org/), a standard from the [Linux Foundation](https://www.linuxfoundation.org) for shareable data about software package license terms. SPDX aims to make sharing and auditing license data easy, especially for users of open-source software. + +The bulk of the SPDX standard describes syntax and semantics of XML metadata files. This package implements two lightweight, plain-text components of that larger standard: + +1. The [license list](https://spdx.org/licenses), a mapping from specific string identifiers, like `Apache-2.0`, to standard form license texts and bolt-on license exceptions. The [spdx-license-ids](https://www.npmjs.com/package/spdx-license-ids) and [spdx-exceptions](https://www.npmjs.com/package/spdx-exceptions) packages implement the license list. `spdx-expression-parse` depends on and `require()`s them. + + Any license identifier from the license list is a valid license expression: + + ```javascript + var identifiers = [] + .concat(require('spdx-license-ids')) + .concat(require('spdx-license-ids/deprecated')) + + identifiers.forEach(function (id) { + assert.deepEqual(parse(id), {license: id}) + }) + ``` + + So is any license identifier `WITH` a standardized license exception: + + ```javascript + identifiers.forEach(function (id) { + require('spdx-exceptions').forEach(function (e) { + assert.deepEqual( + parse(id + ' WITH ' + e), + {license: id, exception: e} + ) + }) + }) + ``` + +2. The license expression language, for describing simple and complex license terms, like `MIT` for MIT-licensed and `(GPL-2.0 OR Apache-2.0)` for dual-licensing under GPL 2.0 and Apache 2.0. `spdx-expression-parse` itself implements license expression language, exporting a parser. + + ```javascript + assert.deepEqual( + // Licensed under a combination of: + // - the MIT License AND + // - a combination of: + // - LGPL 2.1 (or a later version) AND + // - Three-Clause BSD + parse('(MIT AND (LGPL-2.1+ AND BSD-3-Clause))'), + { + left: {license: 'MIT'}, + conjunction: 'and', + right: { + left: {license: 'LGPL-2.1', plus: true}, + conjunction: 'and', + right: {license: 'BSD-3-Clause'} + } + } + ) + ``` + +The Linux Foundation and its contributors license the SPDX standard under the terms of [the Creative Commons Attribution License 3.0 Unported (SPDX: "CC-BY-3.0")](http://spdx.org/licenses/CC-BY-3.0). "SPDX" is a United States federally registered trademark of the Linux Foundation. The authors of this package license their work under the terms of the MIT License. diff --git a/node_modules/spdx-expression-parse/index.js b/node_modules/spdx-expression-parse/index.js new file mode 100644 index 0000000..52fab56 --- /dev/null +++ b/node_modules/spdx-expression-parse/index.js @@ -0,0 +1,8 @@ +'use strict' + +var scan = require('./scan') +var parse = require('./parse') + +module.exports = function (source) { + return parse(scan(source)) +} diff --git a/node_modules/spdx-expression-parse/package.json b/node_modules/spdx-expression-parse/package.json new file mode 100644 index 0000000..c9edc9f --- /dev/null +++ b/node_modules/spdx-expression-parse/package.json @@ -0,0 +1,39 @@ +{ + "name": "spdx-expression-parse", + "description": "parse SPDX license expressions", + "version": "3.0.1", + "author": "Kyle E. Mitchell (https://kemitchell.com)", + "files": [ + "AUTHORS", + "index.js", + "parse.js", + "scan.js" + ], + "dependencies": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + }, + "devDependencies": { + "defence-cli": "^3.0.1", + "replace-require-self": "^1.0.0", + "standard": "^14.1.0" + }, + "keywords": [ + "SPDX", + "law", + "legal", + "license", + "metadata", + "package", + "package.json", + "standards" + ], + "license": "MIT", + "repository": "jslicense/spdx-expression-parse.js", + "scripts": { + "lint": "standard", + "test:readme": "defence -i javascript README.md | replace-require-self | node", + "test:suite": "node test.js", + "test": "npm run test:suite && npm run test:readme" + } +} diff --git a/node_modules/spdx-expression-parse/parse.js b/node_modules/spdx-expression-parse/parse.js new file mode 100644 index 0000000..5a00b45 --- /dev/null +++ b/node_modules/spdx-expression-parse/parse.js @@ -0,0 +1,138 @@ +'use strict' + +// The ABNF grammar in the spec is totally ambiguous. +// +// This parser follows the operator precedence defined in the +// `Order of Precedence and Parentheses` section. + +module.exports = function (tokens) { + var index = 0 + + function hasMore () { + return index < tokens.length + } + + function token () { + return hasMore() ? tokens[index] : null + } + + function next () { + if (!hasMore()) { + throw new Error() + } + index++ + } + + function parseOperator (operator) { + var t = token() + if (t && t.type === 'OPERATOR' && operator === t.string) { + next() + return t.string + } + } + + function parseWith () { + if (parseOperator('WITH')) { + var t = token() + if (t && t.type === 'EXCEPTION') { + next() + return t.string + } + throw new Error('Expected exception after `WITH`') + } + } + + function parseLicenseRef () { + // TODO: Actually, everything is concatenated into one string + // for backward-compatibility but it could be better to return + // a nice structure. + var begin = index + var string = '' + var t = token() + if (t.type === 'DOCUMENTREF') { + next() + string += 'DocumentRef-' + t.string + ':' + if (!parseOperator(':')) { + throw new Error('Expected `:` after `DocumentRef-...`') + } + } + t = token() + if (t.type === 'LICENSEREF') { + next() + string += 'LicenseRef-' + t.string + return { license: string } + } + index = begin + } + + function parseLicense () { + var t = token() + if (t && t.type === 'LICENSE') { + next() + var node = { license: t.string } + if (parseOperator('+')) { + node.plus = true + } + var exception = parseWith() + if (exception) { + node.exception = exception + } + return node + } + } + + function parseParenthesizedExpression () { + var left = parseOperator('(') + if (!left) { + return + } + + var expr = parseExpression() + + if (!parseOperator(')')) { + throw new Error('Expected `)`') + } + + return expr + } + + function parseAtom () { + return ( + parseParenthesizedExpression() || + parseLicenseRef() || + parseLicense() + ) + } + + function makeBinaryOpParser (operator, nextParser) { + return function parseBinaryOp () { + var left = nextParser() + if (!left) { + return + } + + if (!parseOperator(operator)) { + return left + } + + var right = parseBinaryOp() + if (!right) { + throw new Error('Expected expression') + } + return { + left: left, + conjunction: operator.toLowerCase(), + right: right + } + } + } + + var parseAnd = makeBinaryOpParser('AND', parseAtom) + var parseExpression = makeBinaryOpParser('OR', parseAnd) + + var node = parseExpression() + if (!node || hasMore()) { + throw new Error('Syntax error') + } + return node +} diff --git a/node_modules/spdx-expression-parse/scan.js b/node_modules/spdx-expression-parse/scan.js new file mode 100644 index 0000000..b74fce2 --- /dev/null +++ b/node_modules/spdx-expression-parse/scan.js @@ -0,0 +1,131 @@ +'use strict' + +var licenses = [] + .concat(require('spdx-license-ids')) + .concat(require('spdx-license-ids/deprecated')) +var exceptions = require('spdx-exceptions') + +module.exports = function (source) { + var index = 0 + + function hasMore () { + return index < source.length + } + + // `value` can be a regexp or a string. + // If it is recognized, the matching source string is returned and + // the index is incremented. Otherwise `undefined` is returned. + function read (value) { + if (value instanceof RegExp) { + var chars = source.slice(index) + var match = chars.match(value) + if (match) { + index += match[0].length + return match[0] + } + } else { + if (source.indexOf(value, index) === index) { + index += value.length + return value + } + } + } + + function skipWhitespace () { + read(/[ ]*/) + } + + function operator () { + var string + var possibilities = ['WITH', 'AND', 'OR', '(', ')', ':', '+'] + for (var i = 0; i < possibilities.length; i++) { + string = read(possibilities[i]) + if (string) { + break + } + } + + if (string === '+' && index > 1 && source[index - 2] === ' ') { + throw new Error('Space before `+`') + } + + return string && { + type: 'OPERATOR', + string: string + } + } + + function idstring () { + return read(/[A-Za-z0-9-.]+/) + } + + function expectIdstring () { + var string = idstring() + if (!string) { + throw new Error('Expected idstring at offset ' + index) + } + return string + } + + function documentRef () { + if (read('DocumentRef-')) { + var string = expectIdstring() + return { type: 'DOCUMENTREF', string: string } + } + } + + function licenseRef () { + if (read('LicenseRef-')) { + var string = expectIdstring() + return { type: 'LICENSEREF', string: string } + } + } + + function identifier () { + var begin = index + var string = idstring() + + if (licenses.indexOf(string) !== -1) { + return { + type: 'LICENSE', + string: string + } + } else if (exceptions.indexOf(string) !== -1) { + return { + type: 'EXCEPTION', + string: string + } + } + + index = begin + } + + // Tries to read the next token. Returns `undefined` if no token is + // recognized. + function parseToken () { + // Ordering matters + return ( + operator() || + documentRef() || + licenseRef() || + identifier() + ) + } + + var tokens = [] + while (hasMore()) { + skipWhitespace() + if (!hasMore()) { + break + } + + var token = parseToken() + if (!token) { + throw new Error('Unexpected `' + source[index] + + '` at offset ' + index) + } + + tokens.push(token) + } + return tokens +} diff --git a/node_modules/spdx-license-ids/README.md b/node_modules/spdx-license-ids/README.md new file mode 100644 index 0000000..500e32d --- /dev/null +++ b/node_modules/spdx-license-ids/README.md @@ -0,0 +1,52 @@ +# spdx-license-ids + +[![npm version](https://img.shields.io/npm/v/spdx-license-ids.svg)](https://www.npmjs.com/package/spdx-license-ids) +[![Github Actions](https://action-badges.now.sh/jslicense/spdx-license-ids)](https://wdp9fww0r9.execute-api.us-west-2.amazonaws.com/production/results/jslicense/spdx-license-ids) + +A list of [SPDX license](https://spdx.org/licenses/) identifiers + +## Installation + +[Download JSON directly](https://raw.githubusercontent.com/jslicense/spdx-license-ids/main/index.json), or [use](https://docs.npmjs.com/cli/install) [npm](https://docs.npmjs.com/about-npm/): + +``` +npm install spdx-license-ids +``` + +## [Node.js](https://nodejs.org/) API + +### require('spdx-license-ids') + +Type: `string[]` + +All license IDs except for the currently deprecated ones. + +```javascript +const ids = require('spdx-license-ids'); +//=> ['0BSD', 'AAL', 'ADSL', 'AFL-1.1', 'AFL-1.2', 'AFL-2.0', 'AFL-2.1', 'AFL-3.0', 'AGPL-1.0-only', ...] + +ids.includes('BSD-3-Clause'); //=> true +ids.includes('CC-BY-1.0'); //=> true + +ids.includes('GPL-3.0'); //=> false +``` + +### require('spdx-license-ids/deprecated') + +Type: `string[]` + +Deprecated license IDs. + +```javascript +const deprecatedIds = require('spdx-license-ids/deprecated'); +//=> ['AGPL-1.0', 'AGPL-3.0', 'GFDL-1.1', 'GFDL-1.2', 'GFDL-1.3', 'GPL-1.0', 'GPL-2.0', ...] + +deprecatedIds.includes('BSD-3-Clause'); //=> false +deprecatedIds.includes('CC-BY-1.0'); //=> false + +deprecatedIds.includes('GPL-3.0'); //=> true +``` + +## License + +[Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/deed) diff --git a/node_modules/spdx-license-ids/deprecated.json b/node_modules/spdx-license-ids/deprecated.json new file mode 100644 index 0000000..4f70a14 --- /dev/null +++ b/node_modules/spdx-license-ids/deprecated.json @@ -0,0 +1,28 @@ +[ + "AGPL-1.0", + "AGPL-3.0", + "BSD-2-Clause-FreeBSD", + "BSD-2-Clause-NetBSD", + "GFDL-1.1", + "GFDL-1.2", + "GFDL-1.3", + "GPL-1.0", + "GPL-2.0", + "GPL-2.0-with-GCC-exception", + "GPL-2.0-with-autoconf-exception", + "GPL-2.0-with-bison-exception", + "GPL-2.0-with-classpath-exception", + "GPL-2.0-with-font-exception", + "GPL-3.0", + "GPL-3.0-with-GCC-exception", + "GPL-3.0-with-autoconf-exception", + "LGPL-2.0", + "LGPL-2.1", + "LGPL-3.0", + "Net-SNMP", + "Nunit", + "StandardML-NJ", + "bzip2-1.0.5", + "eCos-2.0", + "wxWindows" +] diff --git a/node_modules/spdx-license-ids/index.json b/node_modules/spdx-license-ids/index.json new file mode 100644 index 0000000..f43d501 --- /dev/null +++ b/node_modules/spdx-license-ids/index.json @@ -0,0 +1,636 @@ +[ + "0BSD", + "3D-Slicer-1.0", + "AAL", + "ADSL", + "AFL-1.1", + "AFL-1.2", + "AFL-2.0", + "AFL-2.1", + "AFL-3.0", + "AGPL-1.0-only", + "AGPL-1.0-or-later", + "AGPL-3.0-only", + "AGPL-3.0-or-later", + "AMD-newlib", + "AMDPLPA", + "AML", + "AML-glslang", + "AMPAS", + "ANTLR-PD", + "ANTLR-PD-fallback", + "APAFML", + "APL-1.0", + "APSL-1.0", + "APSL-1.1", + "APSL-1.2", + "APSL-2.0", + "ASWF-Digital-Assets-1.0", + "ASWF-Digital-Assets-1.1", + "Abstyles", + "AdaCore-doc", + "Adobe-2006", + "Adobe-Display-PostScript", + "Adobe-Glyph", + "Adobe-Utopia", + "Afmparse", + "Aladdin", + "Apache-1.0", + "Apache-1.1", + "Apache-2.0", + "App-s2p", + "Arphic-1999", + "Artistic-1.0", + "Artistic-1.0-Perl", + "Artistic-1.0-cl8", + "Artistic-2.0", + "BSD-1-Clause", + "BSD-2-Clause", + "BSD-2-Clause-Darwin", + "BSD-2-Clause-Patent", + "BSD-2-Clause-Views", + "BSD-2-Clause-first-lines", + "BSD-3-Clause", + "BSD-3-Clause-Attribution", + "BSD-3-Clause-Clear", + "BSD-3-Clause-HP", + "BSD-3-Clause-LBNL", + "BSD-3-Clause-Modification", + "BSD-3-Clause-No-Military-License", + "BSD-3-Clause-No-Nuclear-License", + "BSD-3-Clause-No-Nuclear-License-2014", + "BSD-3-Clause-No-Nuclear-Warranty", + "BSD-3-Clause-Open-MPI", + "BSD-3-Clause-Sun", + "BSD-3-Clause-acpica", + "BSD-3-Clause-flex", + "BSD-4-Clause", + "BSD-4-Clause-Shortened", + "BSD-4-Clause-UC", + "BSD-4.3RENO", + "BSD-4.3TAHOE", + "BSD-Advertising-Acknowledgement", + "BSD-Attribution-HPND-disclaimer", + "BSD-Inferno-Nettverk", + "BSD-Protection", + "BSD-Source-Code", + "BSD-Source-beginning-file", + "BSD-Systemics", + "BSD-Systemics-W3Works", + "BSL-1.0", + "BUSL-1.1", + "Baekmuk", + "Bahyph", + "Barr", + "Beerware", + "BitTorrent-1.0", + "BitTorrent-1.1", + "Bitstream-Charter", + "Bitstream-Vera", + "BlueOak-1.0.0", + "Boehm-GC", + "Borceux", + "Brian-Gladman-2-Clause", + "Brian-Gladman-3-Clause", + "C-UDA-1.0", + "CAL-1.0", + "CAL-1.0-Combined-Work-Exception", + "CATOSL-1.1", + "CC-BY-1.0", + "CC-BY-2.0", + "CC-BY-2.5", + "CC-BY-2.5-AU", + "CC-BY-3.0", + "CC-BY-3.0-AT", + "CC-BY-3.0-AU", + "CC-BY-3.0-DE", + "CC-BY-3.0-IGO", + "CC-BY-3.0-NL", + "CC-BY-3.0-US", + "CC-BY-4.0", + "CC-BY-NC-1.0", + "CC-BY-NC-2.0", + "CC-BY-NC-2.5", + "CC-BY-NC-3.0", + "CC-BY-NC-3.0-DE", + "CC-BY-NC-4.0", + "CC-BY-NC-ND-1.0", + "CC-BY-NC-ND-2.0", + "CC-BY-NC-ND-2.5", + "CC-BY-NC-ND-3.0", + "CC-BY-NC-ND-3.0-DE", + "CC-BY-NC-ND-3.0-IGO", + "CC-BY-NC-ND-4.0", + "CC-BY-NC-SA-1.0", + "CC-BY-NC-SA-2.0", + "CC-BY-NC-SA-2.0-DE", + "CC-BY-NC-SA-2.0-FR", + "CC-BY-NC-SA-2.0-UK", + "CC-BY-NC-SA-2.5", + "CC-BY-NC-SA-3.0", + "CC-BY-NC-SA-3.0-DE", + "CC-BY-NC-SA-3.0-IGO", + "CC-BY-NC-SA-4.0", + "CC-BY-ND-1.0", + "CC-BY-ND-2.0", + "CC-BY-ND-2.5", + "CC-BY-ND-3.0", + "CC-BY-ND-3.0-DE", + "CC-BY-ND-4.0", + "CC-BY-SA-1.0", + "CC-BY-SA-2.0", + "CC-BY-SA-2.0-UK", + "CC-BY-SA-2.1-JP", + "CC-BY-SA-2.5", + "CC-BY-SA-3.0", + "CC-BY-SA-3.0-AT", + "CC-BY-SA-3.0-DE", + "CC-BY-SA-3.0-IGO", + "CC-BY-SA-4.0", + "CC-PDDC", + "CC0-1.0", + "CDDL-1.0", + "CDDL-1.1", + "CDL-1.0", + "CDLA-Permissive-1.0", + "CDLA-Permissive-2.0", + "CDLA-Sharing-1.0", + "CECILL-1.0", + "CECILL-1.1", + "CECILL-2.0", + "CECILL-2.1", + "CECILL-B", + "CECILL-C", + "CERN-OHL-1.1", + "CERN-OHL-1.2", + "CERN-OHL-P-2.0", + "CERN-OHL-S-2.0", + "CERN-OHL-W-2.0", + "CFITSIO", + "CMU-Mach", + "CMU-Mach-nodoc", + "CNRI-Jython", + "CNRI-Python", + "CNRI-Python-GPL-Compatible", + "COIL-1.0", + "CPAL-1.0", + "CPL-1.0", + "CPOL-1.02", + "CUA-OPL-1.0", + "Caldera", + "Caldera-no-preamble", + "Catharon", + "ClArtistic", + "Clips", + "Community-Spec-1.0", + "Condor-1.1", + "Cornell-Lossless-JPEG", + "Cronyx", + "Crossword", + "CrystalStacker", + "Cube", + "D-FSL-1.0", + "DEC-3-Clause", + "DL-DE-BY-2.0", + "DL-DE-ZERO-2.0", + "DOC", + "DRL-1.0", + "DRL-1.1", + "DSDP", + "DocBook-Schema", + "DocBook-XML", + "Dotseqn", + "ECL-1.0", + "ECL-2.0", + "EFL-1.0", + "EFL-2.0", + "EPICS", + "EPL-1.0", + "EPL-2.0", + "EUDatagrid", + "EUPL-1.0", + "EUPL-1.1", + "EUPL-1.2", + "Elastic-2.0", + "Entessa", + "ErlPL-1.1", + "Eurosym", + "FBM", + "FDK-AAC", + "FSFAP", + "FSFAP-no-warranty-disclaimer", + "FSFUL", + "FSFULLR", + "FSFULLRWD", + "FTL", + "Fair", + "Ferguson-Twofish", + "Frameworx-1.0", + "FreeBSD-DOC", + "FreeImage", + "Furuseth", + "GCR-docs", + "GD", + "GFDL-1.1-invariants-only", + "GFDL-1.1-invariants-or-later", + "GFDL-1.1-no-invariants-only", + "GFDL-1.1-no-invariants-or-later", + "GFDL-1.1-only", + "GFDL-1.1-or-later", + "GFDL-1.2-invariants-only", + "GFDL-1.2-invariants-or-later", + "GFDL-1.2-no-invariants-only", + "GFDL-1.2-no-invariants-or-later", + "GFDL-1.2-only", + "GFDL-1.2-or-later", + "GFDL-1.3-invariants-only", + "GFDL-1.3-invariants-or-later", + "GFDL-1.3-no-invariants-only", + "GFDL-1.3-no-invariants-or-later", + "GFDL-1.3-only", + "GFDL-1.3-or-later", + "GL2PS", + "GLWTPL", + "GPL-1.0-only", + "GPL-1.0-or-later", + "GPL-2.0-only", + "GPL-2.0-or-later", + "GPL-3.0-only", + "GPL-3.0-or-later", + "Giftware", + "Glide", + "Glulxe", + "Graphics-Gems", + "Gutmann", + "HIDAPI", + "HP-1986", + "HP-1989", + "HPND", + "HPND-DEC", + "HPND-Fenneberg-Livingston", + "HPND-INRIA-IMAG", + "HPND-Intel", + "HPND-Kevlin-Henney", + "HPND-MIT-disclaimer", + "HPND-Markus-Kuhn", + "HPND-Netrek", + "HPND-Pbmplus", + "HPND-UC", + "HPND-UC-export-US", + "HPND-doc", + "HPND-doc-sell", + "HPND-export-US", + "HPND-export-US-acknowledgement", + "HPND-export-US-modify", + "HPND-export2-US", + "HPND-merchantability-variant", + "HPND-sell-MIT-disclaimer-xserver", + "HPND-sell-regexpr", + "HPND-sell-variant", + "HPND-sell-variant-MIT-disclaimer", + "HPND-sell-variant-MIT-disclaimer-rev", + "HTMLTIDY", + "HaskellReport", + "Hippocratic-2.1", + "IBM-pibs", + "ICU", + "IEC-Code-Components-EULA", + "IJG", + "IJG-short", + "IPA", + "IPL-1.0", + "ISC", + "ISC-Veillard", + "ImageMagick", + "Imlib2", + "Info-ZIP", + "Inner-Net-2.0", + "Intel", + "Intel-ACPI", + "Interbase-1.0", + "JPL-image", + "JPNIC", + "JSON", + "Jam", + "JasPer-2.0", + "Kastrup", + "Kazlib", + "Knuth-CTAN", + "LAL-1.2", + "LAL-1.3", + "LGPL-2.0-only", + "LGPL-2.0-or-later", + "LGPL-2.1-only", + "LGPL-2.1-or-later", + "LGPL-3.0-only", + "LGPL-3.0-or-later", + "LGPLLR", + "LOOP", + "LPD-document", + "LPL-1.0", + "LPL-1.02", + "LPPL-1.0", + "LPPL-1.1", + "LPPL-1.2", + "LPPL-1.3a", + "LPPL-1.3c", + "LZMA-SDK-9.11-to-9.20", + "LZMA-SDK-9.22", + "Latex2e", + "Latex2e-translated-notice", + "Leptonica", + "LiLiQ-P-1.1", + "LiLiQ-R-1.1", + "LiLiQ-Rplus-1.1", + "Libpng", + "Linux-OpenIB", + "Linux-man-pages-1-para", + "Linux-man-pages-copyleft", + "Linux-man-pages-copyleft-2-para", + "Linux-man-pages-copyleft-var", + "Lucida-Bitmap-Fonts", + "MIT", + "MIT-0", + "MIT-CMU", + "MIT-Festival", + "MIT-Khronos-old", + "MIT-Modern-Variant", + "MIT-Wu", + "MIT-advertising", + "MIT-enna", + "MIT-feh", + "MIT-open-group", + "MIT-testregex", + "MITNFA", + "MMIXware", + "MPEG-SSG", + "MPL-1.0", + "MPL-1.1", + "MPL-2.0", + "MPL-2.0-no-copyleft-exception", + "MS-LPL", + "MS-PL", + "MS-RL", + "MTLL", + "Mackerras-3-Clause", + "Mackerras-3-Clause-acknowledgment", + "MakeIndex", + "Martin-Birgmeier", + "McPhee-slideshow", + "Minpack", + "MirOS", + "Motosoto", + "MulanPSL-1.0", + "MulanPSL-2.0", + "Multics", + "Mup", + "NAIST-2003", + "NASA-1.3", + "NBPL-1.0", + "NCBI-PD", + "NCGL-UK-2.0", + "NCL", + "NCSA", + "NGPL", + "NICTA-1.0", + "NIST-PD", + "NIST-PD-fallback", + "NIST-Software", + "NLOD-1.0", + "NLOD-2.0", + "NLPL", + "NOSL", + "NPL-1.0", + "NPL-1.1", + "NPOSL-3.0", + "NRL", + "NTP", + "NTP-0", + "Naumen", + "NetCDF", + "Newsletr", + "Nokia", + "Noweb", + "O-UDA-1.0", + "OAR", + "OCCT-PL", + "OCLC-2.0", + "ODC-By-1.0", + "ODbL-1.0", + "OFFIS", + "OFL-1.0", + "OFL-1.0-RFN", + "OFL-1.0-no-RFN", + "OFL-1.1", + "OFL-1.1-RFN", + "OFL-1.1-no-RFN", + "OGC-1.0", + "OGDL-Taiwan-1.0", + "OGL-Canada-2.0", + "OGL-UK-1.0", + "OGL-UK-2.0", + "OGL-UK-3.0", + "OGTSL", + "OLDAP-1.1", + "OLDAP-1.2", + "OLDAP-1.3", + "OLDAP-1.4", + "OLDAP-2.0", + "OLDAP-2.0.1", + "OLDAP-2.1", + "OLDAP-2.2", + "OLDAP-2.2.1", + "OLDAP-2.2.2", + "OLDAP-2.3", + "OLDAP-2.4", + "OLDAP-2.5", + "OLDAP-2.6", + "OLDAP-2.7", + "OLDAP-2.8", + "OLFL-1.3", + "OML", + "OPL-1.0", + "OPL-UK-3.0", + "OPUBL-1.0", + "OSET-PL-2.1", + "OSL-1.0", + "OSL-1.1", + "OSL-2.0", + "OSL-2.1", + "OSL-3.0", + "OpenPBS-2.3", + "OpenSSL", + "OpenSSL-standalone", + "OpenVision", + "PADL", + "PDDL-1.0", + "PHP-3.0", + "PHP-3.01", + "PPL", + "PSF-2.0", + "Parity-6.0.0", + "Parity-7.0.0", + "Pixar", + "Plexus", + "PolyForm-Noncommercial-1.0.0", + "PolyForm-Small-Business-1.0.0", + "PostgreSQL", + "Python-2.0", + "Python-2.0.1", + "QPL-1.0", + "QPL-1.0-INRIA-2004", + "Qhull", + "RHeCos-1.1", + "RPL-1.1", + "RPL-1.5", + "RPSL-1.0", + "RSA-MD", + "RSCPL", + "Rdisc", + "Ruby", + "Ruby-pty", + "SAX-PD", + "SAX-PD-2.0", + "SCEA", + "SGI-B-1.0", + "SGI-B-1.1", + "SGI-B-2.0", + "SGI-OpenGL", + "SGP4", + "SHL-0.5", + "SHL-0.51", + "SISSL", + "SISSL-1.2", + "SL", + "SMLNJ", + "SMPPL", + "SNIA", + "SPL-1.0", + "SSH-OpenSSH", + "SSH-short", + "SSLeay-standalone", + "SSPL-1.0", + "SWL", + "Saxpath", + "SchemeReport", + "Sendmail", + "Sendmail-8.23", + "SimPL-2.0", + "Sleepycat", + "Soundex", + "Spencer-86", + "Spencer-94", + "Spencer-99", + "SugarCRM-1.1.3", + "Sun-PPP", + "Sun-PPP-2000", + "SunPro", + "Symlinks", + "TAPR-OHL-1.0", + "TCL", + "TCP-wrappers", + "TGPPL-1.0", + "TMate", + "TORQUE-1.1", + "TOSL", + "TPDL", + "TPL-1.0", + "TTWL", + "TTYP0", + "TU-Berlin-1.0", + "TU-Berlin-2.0", + "TermReadKey", + "UCAR", + "UCL-1.0", + "UMich-Merit", + "UPL-1.0", + "URT-RLE", + "Ubuntu-font-1.0", + "Unicode-3.0", + "Unicode-DFS-2015", + "Unicode-DFS-2016", + "Unicode-TOU", + "UnixCrypt", + "Unlicense", + "VOSTROM", + "VSL-1.0", + "Vim", + "W3C", + "W3C-19980720", + "W3C-20150513", + "WTFPL", + "Watcom-1.0", + "Widget-Workshop", + "Wsuipa", + "X11", + "X11-distribute-modifications-variant", + "X11-swapped", + "XFree86-1.1", + "XSkat", + "Xdebug-1.03", + "Xerox", + "Xfig", + "Xnet", + "YPL-1.0", + "YPL-1.1", + "ZPL-1.1", + "ZPL-2.0", + "ZPL-2.1", + "Zed", + "Zeeff", + "Zend-2.0", + "Zimbra-1.3", + "Zimbra-1.4", + "Zlib", + "any-OSI", + "bcrypt-Solar-Designer", + "blessing", + "bzip2-1.0.6", + "check-cvs", + "checkmk", + "copyleft-next-0.3.0", + "copyleft-next-0.3.1", + "curl", + "cve-tou", + "diffmark", + "dtoa", + "dvipdfm", + "eGenix", + "etalab-2.0", + "fwlw", + "gSOAP-1.3b", + "gnuplot", + "gtkbook", + "hdparm", + "iMatix", + "libpng-2.0", + "libselinux-1.0", + "libtiff", + "libutil-David-Nugent", + "lsof", + "magaz", + "mailprio", + "metamail", + "mpi-permissive", + "mpich2", + "mplus", + "pkgconf", + "pnmstitch", + "psfrag", + "psutils", + "python-ldap", + "radvd", + "snprintf", + "softSurfer", + "ssh-keyscan", + "swrule", + "threeparttable", + "ulem", + "w3m", + "xinetd", + "xkeyboard-config-Zinoviev", + "xlock", + "xpp", + "xzoom", + "zlib-acknowledgement" +] diff --git a/node_modules/spdx-license-ids/package.json b/node_modules/spdx-license-ids/package.json new file mode 100644 index 0000000..7ab34aa --- /dev/null +++ b/node_modules/spdx-license-ids/package.json @@ -0,0 +1,39 @@ +{ + "name": "spdx-license-ids", + "version": "3.0.20", + "description": "A list of SPDX license identifiers", + "repository": "jslicense/spdx-license-ids", + "author": "Shinnosuke Watanabe (https://github.com/shinnn)", + "license": "CC0-1.0", + "scripts": { + "build": "node build.js", + "pretest": "eslint .", + "latest": "node latest.js", + "test": "node test.js" + }, + "files": [ + "deprecated.json", + "index.json" + ], + "keywords": [ + "spdx", + "license", + "licenses", + "id", + "identifier", + "identifiers", + "json", + "array", + "oss" + ], + "devDependencies": { + "@shinnn/eslint-config": "^7.0.0", + "eslint": "^8.49.0", + "eslint-formatter-codeframe": "^7.32.1", + "rmfr": "^2.0.0", + "tape": "^5.6.6" + }, + "eslintConfig": { + "extends": "@shinnn" + } +} diff --git a/node_modules/sprintf-js/.npmignore b/node_modules/sprintf-js/.npmignore new file mode 100644 index 0000000..096746c --- /dev/null +++ b/node_modules/sprintf-js/.npmignore @@ -0,0 +1 @@ +/node_modules/ \ No newline at end of file diff --git a/node_modules/sprintf-js/LICENSE b/node_modules/sprintf-js/LICENSE new file mode 100644 index 0000000..663ac52 --- /dev/null +++ b/node_modules/sprintf-js/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2007-2014, Alexandru Marasteanu +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of this software nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/sprintf-js/README.md b/node_modules/sprintf-js/README.md new file mode 100644 index 0000000..8386356 --- /dev/null +++ b/node_modules/sprintf-js/README.md @@ -0,0 +1,88 @@ +# sprintf.js +**sprintf.js** is a complete open source JavaScript sprintf implementation for the *browser* and *node.js*. + +Its prototype is simple: + + string sprintf(string format , [mixed arg1 [, mixed arg2 [ ,...]]]) + +The placeholders in the format string are marked by `%` and are followed by one or more of these elements, in this order: + +* An optional number followed by a `$` sign that selects which argument index to use for the value. If not specified, arguments will be placed in the same order as the placeholders in the input string. +* An optional `+` sign that forces to preceed the result with a plus or minus sign on numeric values. By default, only the `-` sign is used on negative numbers. +* An optional padding specifier that says what character to use for padding (if specified). Possible values are `0` or any other character precedeed by a `'` (single quote). The default is to pad with *spaces*. +* An optional `-` sign, that causes sprintf to left-align the result of this placeholder. The default is to right-align the result. +* An optional number, that says how many characters the result should have. If the value to be returned is shorter than this number, the result will be padded. When used with the `j` (JSON) type specifier, the padding length specifies the tab size used for indentation. +* An optional precision modifier, consisting of a `.` (dot) followed by a number, that says how many digits should be displayed for floating point numbers. When used with the `g` type specifier, it specifies the number of significant digits. When used on a string, it causes the result to be truncated. +* A type specifier that can be any of: + * `%` — yields a literal `%` character + * `b` — yields an integer as a binary number + * `c` — yields an integer as the character with that ASCII value + * `d` or `i` — yields an integer as a signed decimal number + * `e` — yields a float using scientific notation + * `u` — yields an integer as an unsigned decimal number + * `f` — yields a float as is; see notes on precision above + * `g` — yields a float as is; see notes on precision above + * `o` — yields an integer as an octal number + * `s` — yields a string as is + * `x` — yields an integer as a hexadecimal number (lower-case) + * `X` — yields an integer as a hexadecimal number (upper-case) + * `j` — yields a JavaScript object or array as a JSON encoded string + +## JavaScript `vsprintf` +`vsprintf` is the same as `sprintf` except that it accepts an array of arguments, rather than a variable number of arguments: + + vsprintf("The first 4 letters of the english alphabet are: %s, %s, %s and %s", ["a", "b", "c", "d"]) + +## Argument swapping +You can also swap the arguments. That is, the order of the placeholders doesn't have to match the order of the arguments. You can do that by simply indicating in the format string which arguments the placeholders refer to: + + sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") +And, of course, you can repeat the placeholders without having to increase the number of arguments. + +## Named arguments +Format strings may contain replacement fields rather than positional placeholders. Instead of referring to a certain argument, you can now refer to a certain key within an object. Replacement fields are surrounded by rounded parentheses - `(` and `)` - and begin with a keyword that refers to a key: + + var user = { + name: "Dolly" + } + sprintf("Hello %(name)s", user) // Hello Dolly +Keywords in replacement fields can be optionally followed by any number of keywords or indexes: + + var users = [ + {name: "Dolly"}, + {name: "Molly"}, + {name: "Polly"} + ] + sprintf("Hello %(users[0].name)s, %(users[1].name)s and %(users[2].name)s", {users: users}) // Hello Dolly, Molly and Polly +Note: mixing positional and named placeholders is not (yet) supported + +## Computed values +You can pass in a function as a dynamic value and it will be invoked (with no arguments) in order to compute the value on-the-fly. + + sprintf("Current timestamp: %d", Date.now) // Current timestamp: 1398005382890 + sprintf("Current date and time: %s", function() { return new Date().toString() }) + +# AngularJS +You can now use `sprintf` and `vsprintf` (also aliased as `fmt` and `vfmt` respectively) in your AngularJS projects. See `demo/`. + +# Installation + +## Via Bower + + bower install sprintf + +## Or as a node.js module + + npm install sprintf-js + +### Usage + + var sprintf = require("sprintf-js").sprintf, + vsprintf = require("sprintf-js").vsprintf + + sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") + vsprintf("The first 4 letters of the english alphabet are: %s, %s, %s and %s", ["a", "b", "c", "d"]) + +# License + +**sprintf.js** is licensed under the terms of the 3-clause BSD license. diff --git a/node_modules/sprintf-js/bower.json b/node_modules/sprintf-js/bower.json new file mode 100644 index 0000000..d90a759 --- /dev/null +++ b/node_modules/sprintf-js/bower.json @@ -0,0 +1,14 @@ +{ + "name": "sprintf", + "description": "JavaScript sprintf implementation", + "version": "1.0.3", + "main": "src/sprintf.js", + "license": "BSD-3-Clause-Clear", + "keywords": ["sprintf", "string", "formatting"], + "authors": ["Alexandru Marasteanu (http://alexei.ro/)"], + "homepage": "https://github.com/alexei/sprintf.js", + "repository": { + "type": "git", + "url": "git://github.com/alexei/sprintf.js.git" + } +} diff --git a/node_modules/sprintf-js/demo/angular.html b/node_modules/sprintf-js/demo/angular.html new file mode 100644 index 0000000..3559efd --- /dev/null +++ b/node_modules/sprintf-js/demo/angular.html @@ -0,0 +1,20 @@ + + + + + + + + +
{{ "%+010d"|sprintf:-123 }}
+
{{ "%+010d"|vsprintf:[-123] }}
+
{{ "%+010d"|fmt:-123 }}
+
{{ "%+010d"|vfmt:[-123] }}
+
{{ "I've got %2$d apples and %1$d oranges."|fmt:4:2 }}
+
{{ "I've got %(apples)d apples and %(oranges)d oranges."|fmt:{apples: 2, oranges: 4} }}
+ + + + diff --git a/node_modules/sprintf-js/dist/angular-sprintf.min.js b/node_modules/sprintf-js/dist/angular-sprintf.min.js new file mode 100644 index 0000000..dbaf744 --- /dev/null +++ b/node_modules/sprintf-js/dist/angular-sprintf.min.js @@ -0,0 +1,4 @@ +/*! sprintf-js | Alexandru Marasteanu (http://alexei.ro/) | BSD-3-Clause */ + +angular.module("sprintf",[]).filter("sprintf",function(){return function(){return sprintf.apply(null,arguments)}}).filter("fmt",["$filter",function(a){return a("sprintf")}]).filter("vsprintf",function(){return function(a,b){return vsprintf(a,b)}}).filter("vfmt",["$filter",function(a){return a("vsprintf")}]); +//# sourceMappingURL=angular-sprintf.min.map \ No newline at end of file diff --git a/node_modules/sprintf-js/dist/angular-sprintf.min.js.map b/node_modules/sprintf-js/dist/angular-sprintf.min.js.map new file mode 100644 index 0000000..055964c --- /dev/null +++ b/node_modules/sprintf-js/dist/angular-sprintf.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"angular-sprintf.min.js","sources":["../src/angular-sprintf.js"],"names":["angular","module","filter","sprintf","apply","arguments","$filter","format","argv","vsprintf"],"mappings":";;AAAAA,QACIC,OAAO,cACPC,OAAO,UAAW,WACd,MAAO,YACH,MAAOC,SAAQC,MAAM,KAAMC,cAGnCH,OAAO,OAAQ,UAAW,SAASI,GAC/B,MAAOA,GAAQ,cAEnBJ,OAAO,WAAY,WACf,MAAO,UAASK,EAAQC,GACpB,MAAOC,UAASF,EAAQC,MAGhCN,OAAO,QAAS,UAAW,SAASI,GAChC,MAAOA,GAAQ"} \ No newline at end of file diff --git a/node_modules/sprintf-js/dist/angular-sprintf.min.map b/node_modules/sprintf-js/dist/angular-sprintf.min.map new file mode 100644 index 0000000..055964c --- /dev/null +++ b/node_modules/sprintf-js/dist/angular-sprintf.min.map @@ -0,0 +1 @@ +{"version":3,"file":"angular-sprintf.min.js","sources":["../src/angular-sprintf.js"],"names":["angular","module","filter","sprintf","apply","arguments","$filter","format","argv","vsprintf"],"mappings":";;AAAAA,QACIC,OAAO,cACPC,OAAO,UAAW,WACd,MAAO,YACH,MAAOC,SAAQC,MAAM,KAAMC,cAGnCH,OAAO,OAAQ,UAAW,SAASI,GAC/B,MAAOA,GAAQ,cAEnBJ,OAAO,WAAY,WACf,MAAO,UAASK,EAAQC,GACpB,MAAOC,UAASF,EAAQC,MAGhCN,OAAO,QAAS,UAAW,SAASI,GAChC,MAAOA,GAAQ"} \ No newline at end of file diff --git a/node_modules/sprintf-js/dist/sprintf.min.js b/node_modules/sprintf-js/dist/sprintf.min.js new file mode 100644 index 0000000..dc61e51 --- /dev/null +++ b/node_modules/sprintf-js/dist/sprintf.min.js @@ -0,0 +1,4 @@ +/*! sprintf-js | Alexandru Marasteanu (http://alexei.ro/) | BSD-3-Clause */ + +!function(a){function b(){var a=arguments[0],c=b.cache;return c[a]&&c.hasOwnProperty(a)||(c[a]=b.parse(a)),b.format.call(null,c[a],arguments)}function c(a){return Object.prototype.toString.call(a).slice(8,-1).toLowerCase()}function d(a,b){return Array(b+1).join(a)}var e={not_string:/[^s]/,number:/[diefg]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[\+\-]/};b.format=function(a,f){var g,h,i,j,k,l,m,n=1,o=a.length,p="",q=[],r=!0,s="";for(h=0;o>h;h++)if(p=c(a[h]),"string"===p)q[q.length]=a[h];else if("array"===p){if(j=a[h],j[2])for(g=f[n],i=0;i=0),j[8]){case"b":g=g.toString(2);break;case"c":g=String.fromCharCode(g);break;case"d":case"i":g=parseInt(g,10);break;case"j":g=JSON.stringify(g,null,j[6]?parseInt(j[6]):0);break;case"e":g=j[7]?g.toExponential(j[7]):g.toExponential();break;case"f":g=j[7]?parseFloat(g).toFixed(j[7]):parseFloat(g);break;case"g":g=j[7]?parseFloat(g).toPrecision(j[7]):parseFloat(g);break;case"o":g=g.toString(8);break;case"s":g=(g=String(g))&&j[7]?g.substring(0,j[7]):g;break;case"u":g>>>=0;break;case"x":g=g.toString(16);break;case"X":g=g.toString(16).toUpperCase()}e.json.test(j[8])?q[q.length]=g:(!e.number.test(j[8])||r&&!j[3]?s="":(s=r?"+":"-",g=g.toString().replace(e.sign,"")),l=j[4]?"0"===j[4]?"0":j[4].charAt(1):" ",m=j[6]-(s+g).length,k=j[6]&&m>0?d(l,m):"",q[q.length]=j[5]?s+g+k:"0"===l?s+k+g:k+s+g)}return q.join("")},b.cache={},b.parse=function(a){for(var b=a,c=[],d=[],f=0;b;){if(null!==(c=e.text.exec(b)))d[d.length]=c[0];else if(null!==(c=e.modulo.exec(b)))d[d.length]="%";else{if(null===(c=e.placeholder.exec(b)))throw new SyntaxError("[sprintf] unexpected placeholder");if(c[2]){f|=1;var g=[],h=c[2],i=[];if(null===(i=e.key.exec(h)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(g[g.length]=i[1];""!==(h=h.substring(i[0].length));)if(null!==(i=e.key_access.exec(h)))g[g.length]=i[1];else{if(null===(i=e.index_access.exec(h)))throw new SyntaxError("[sprintf] failed to parse named argument key");g[g.length]=i[1]}c[2]=g}else f|=2;if(3===f)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");d[d.length]=c}b=b.substring(c[0].length)}return d};var f=function(a,c,d){return d=(c||[]).slice(0),d.splice(0,0,a),b.apply(null,d)};"undefined"!=typeof exports?(exports.sprintf=b,exports.vsprintf=f):(a.sprintf=b,a.vsprintf=f,"function"==typeof define&&define.amd&&define(function(){return{sprintf:b,vsprintf:f}}))}("undefined"==typeof window?this:window); +//# sourceMappingURL=sprintf.min.map \ No newline at end of file diff --git a/node_modules/sprintf-js/dist/sprintf.min.js.map b/node_modules/sprintf-js/dist/sprintf.min.js.map new file mode 100644 index 0000000..369dbaf --- /dev/null +++ b/node_modules/sprintf-js/dist/sprintf.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sprintf.min.js","sources":["../src/sprintf.js"],"names":["window","sprintf","key","arguments","cache","hasOwnProperty","parse","format","call","get_type","variable","Object","prototype","toString","slice","toLowerCase","str_repeat","input","multiplier","Array","join","re","not_string","number","json","not_json","text","modulo","placeholder","key_access","index_access","sign","parse_tree","argv","arg","i","k","match","pad","pad_character","pad_length","cursor","tree_length","length","node_type","output","is_positive","Error","test","isNaN","TypeError","String","fromCharCode","parseInt","JSON","stringify","toExponential","parseFloat","toFixed","substring","toUpperCase","replace","charAt","fmt","_fmt","arg_names","exec","SyntaxError","field_list","replacement_field","field_match","vsprintf","_argv","splice","apply","exports","define","amd","this"],"mappings":";;CAAA,SAAUA,GAeN,QAASC,KACL,GAAIC,GAAMC,UAAU,GAAIC,EAAQH,EAAQG,KAIxC,OAHMA,GAAMF,IAAQE,EAAMC,eAAeH,KACrCE,EAAMF,GAAOD,EAAQK,MAAMJ,IAExBD,EAAQM,OAAOC,KAAK,KAAMJ,EAAMF,GAAMC,WA4JjD,QAASM,GAASC,GACd,MAAOC,QAAOC,UAAUC,SAASL,KAAKE,GAAUI,MAAM,EAAG,IAAIC,cAGjE,QAASC,GAAWC,EAAOC,GACvB,MAAOC,OAAMD,EAAa,GAAGE,KAAKH,GApLtC,GAAII,IACAC,WAAY,OACZC,OAAQ,SACRC,KAAM,MACNC,SAAU,OACVC,KAAM,YACNC,OAAQ,WACRC,YAAa,yFACb1B,IAAK,sBACL2B,WAAY,wBACZC,aAAc,aACdC,KAAM,UAWV9B,GAAQM,OAAS,SAASyB,EAAYC,GAClC,GAAiEC,GAAkBC,EAAGC,EAAGC,EAAOC,EAAKC,EAAeC,EAAhHC,EAAS,EAAGC,EAAcV,EAAWW,OAAQC,EAAY,GAASC,KAA0DC,GAAc,EAAMf,EAAO,EAC3J,KAAKI,EAAI,EAAOO,EAAJP,EAAiBA,IAEzB,GADAS,EAAYnC,EAASuB,EAAWG,IACd,WAAdS,EACAC,EAAOA,EAAOF,QAAUX,EAAWG,OAElC,IAAkB,UAAdS,EAAuB,CAE5B,GADAP,EAAQL,EAAWG,GACfE,EAAM,GAEN,IADAH,EAAMD,EAAKQ,GACNL,EAAI,EAAGA,EAAIC,EAAM,GAAGM,OAAQP,IAAK,CAClC,IAAKF,EAAI7B,eAAegC,EAAM,GAAGD,IAC7B,KAAM,IAAIW,OAAM9C,EAAQ,yCAA0CoC,EAAM,GAAGD,IAE/EF,GAAMA,EAAIG,EAAM,GAAGD,QAIvBF,GADKG,EAAM,GACLJ,EAAKI,EAAM,IAGXJ,EAAKQ,IAOf,IAJqB,YAAjBhC,EAASyB,KACTA,EAAMA,KAGNb,EAAGC,WAAW0B,KAAKX,EAAM,KAAOhB,EAAGI,SAASuB,KAAKX,EAAM,KAAyB,UAAjB5B,EAASyB,IAAoBe,MAAMf,GAClG,KAAM,IAAIgB,WAAUjD,EAAQ,0CAA2CQ,EAASyB,IAOpF,QAJIb,EAAGE,OAAOyB,KAAKX,EAAM,MACrBS,EAAcZ,GAAO,GAGjBG,EAAM,IACV,IAAK,IACDH,EAAMA,EAAIrB,SAAS,EACvB,MACA,KAAK,IACDqB,EAAMiB,OAAOC,aAAalB,EAC9B,MACA,KAAK,IACL,IAAK,IACDA,EAAMmB,SAASnB,EAAK,GACxB,MACA,KAAK,IACDA,EAAMoB,KAAKC,UAAUrB,EAAK,KAAMG,EAAM,GAAKgB,SAAShB,EAAM,IAAM,EACpE,MACA,KAAK,IACDH,EAAMG,EAAM,GAAKH,EAAIsB,cAAcnB,EAAM,IAAMH,EAAIsB,eACvD,MACA,KAAK,IACDtB,EAAMG,EAAM,GAAKoB,WAAWvB,GAAKwB,QAAQrB,EAAM,IAAMoB,WAAWvB,EACpE,MACA,KAAK,IACDA,EAAMA,EAAIrB,SAAS,EACvB,MACA,KAAK,IACDqB,GAAQA,EAAMiB,OAAOjB,KAASG,EAAM,GAAKH,EAAIyB,UAAU,EAAGtB,EAAM,IAAMH,CAC1E,MACA,KAAK,IACDA,KAAc,CAClB,MACA,KAAK,IACDA,EAAMA,EAAIrB,SAAS,GACvB,MACA,KAAK,IACDqB,EAAMA,EAAIrB,SAAS,IAAI+C,cAG3BvC,EAAGG,KAAKwB,KAAKX,EAAM,IACnBQ,EAAOA,EAAOF,QAAUT,IAGpBb,EAAGE,OAAOyB,KAAKX,EAAM,KAASS,IAAeT,EAAM,GAKnDN,EAAO,IAJPA,EAAOe,EAAc,IAAM,IAC3BZ,EAAMA,EAAIrB,WAAWgD,QAAQxC,EAAGU,KAAM,KAK1CQ,EAAgBF,EAAM,GAAkB,MAAbA,EAAM,GAAa,IAAMA,EAAM,GAAGyB,OAAO,GAAK,IACzEtB,EAAaH,EAAM,IAAMN,EAAOG,GAAKS,OACrCL,EAAMD,EAAM,IAAMG,EAAa,EAAIxB,EAAWuB,EAAeC,GAAoB,GACjFK,EAAOA,EAAOF,QAAUN,EAAM,GAAKN,EAAOG,EAAMI,EAAyB,MAAlBC,EAAwBR,EAAOO,EAAMJ,EAAMI,EAAMP,EAAOG,GAI3H,MAAOW,GAAOzB,KAAK,KAGvBnB,EAAQG,SAERH,EAAQK,MAAQ,SAASyD,GAErB,IADA,GAAIC,GAAOD,EAAK1B,KAAYL,KAAiBiC,EAAY,EAClDD,GAAM,CACT,GAAqC,QAAhC3B,EAAQhB,EAAGK,KAAKwC,KAAKF,IACtBhC,EAAWA,EAAWW,QAAUN,EAAM,OAErC,IAAuC,QAAlCA,EAAQhB,EAAGM,OAAOuC,KAAKF,IAC7BhC,EAAWA,EAAWW,QAAU,QAE/B,CAAA,GAA4C,QAAvCN,EAAQhB,EAAGO,YAAYsC,KAAKF,IAgClC,KAAM,IAAIG,aAAY,mCA/BtB,IAAI9B,EAAM,GAAI,CACV4B,GAAa,CACb,IAAIG,MAAiBC,EAAoBhC,EAAM,GAAIiC,IACnD,IAAuD,QAAlDA,EAAcjD,EAAGnB,IAAIgE,KAAKG,IAe3B,KAAM,IAAIF,aAAY,+CAbtB,KADAC,EAAWA,EAAWzB,QAAU2B,EAAY,GACwC,MAA5ED,EAAoBA,EAAkBV,UAAUW,EAAY,GAAG3B,UACnE,GAA8D,QAAzD2B,EAAcjD,EAAGQ,WAAWqC,KAAKG,IAClCD,EAAWA,EAAWzB,QAAU2B,EAAY,OAE3C,CAAA,GAAgE,QAA3DA,EAAcjD,EAAGS,aAAaoC,KAAKG,IAIzC,KAAM,IAAIF,aAAY,+CAHtBC,GAAWA,EAAWzB,QAAU2B,EAAY,GAUxDjC,EAAM,GAAK+B,MAGXH,IAAa,CAEjB,IAAkB,IAAdA,EACA,KAAM,IAAIlB,OAAM,4EAEpBf,GAAWA,EAAWW,QAAUN,EAKpC2B,EAAOA,EAAKL,UAAUtB,EAAM,GAAGM,QAEnC,MAAOX,GAGX,IAAIuC,GAAW,SAASR,EAAK9B,EAAMuC,GAG/B,MAFAA,IAASvC,OAAYnB,MAAM,GAC3B0D,EAAMC,OAAO,EAAG,EAAGV,GACZ9D,EAAQyE,MAAM,KAAMF,GAiBR,oBAAZG,UACPA,QAAQ1E,QAAUA,EAClB0E,QAAQJ,SAAWA,IAGnBvE,EAAOC,QAAUA,EACjBD,EAAOuE,SAAWA,EAEI,kBAAXK,SAAyBA,OAAOC,KACvCD,OAAO,WACH,OACI3E,QAASA,EACTsE,SAAUA,OAKT,mBAAXvE,QAAyB8E,KAAO9E"} \ No newline at end of file diff --git a/node_modules/sprintf-js/dist/sprintf.min.map b/node_modules/sprintf-js/dist/sprintf.min.map new file mode 100644 index 0000000..ee011aa --- /dev/null +++ b/node_modules/sprintf-js/dist/sprintf.min.map @@ -0,0 +1 @@ +{"version":3,"file":"sprintf.min.js","sources":["../src/sprintf.js"],"names":["window","sprintf","key","arguments","cache","hasOwnProperty","parse","format","call","get_type","variable","Object","prototype","toString","slice","toLowerCase","str_repeat","input","multiplier","Array","join","re","not_string","number","json","not_json","text","modulo","placeholder","key_access","index_access","sign","parse_tree","argv","arg","i","k","match","pad","pad_character","pad_length","cursor","tree_length","length","node_type","output","is_positive","Error","test","isNaN","TypeError","String","fromCharCode","parseInt","JSON","stringify","toExponential","parseFloat","toFixed","toPrecision","substring","toUpperCase","replace","charAt","fmt","_fmt","arg_names","exec","SyntaxError","field_list","replacement_field","field_match","vsprintf","_argv","splice","apply","exports","define","amd","this"],"mappings":";;CAAA,SAAUA,GAeN,QAASC,KACL,GAAIC,GAAMC,UAAU,GAAIC,EAAQH,EAAQG,KAIxC,OAHMA,GAAMF,IAAQE,EAAMC,eAAeH,KACrCE,EAAMF,GAAOD,EAAQK,MAAMJ,IAExBD,EAAQM,OAAOC,KAAK,KAAMJ,EAAMF,GAAMC,WA+JjD,QAASM,GAASC,GACd,MAAOC,QAAOC,UAAUC,SAASL,KAAKE,GAAUI,MAAM,EAAG,IAAIC,cAGjE,QAASC,GAAWC,EAAOC,GACvB,MAAOC,OAAMD,EAAa,GAAGE,KAAKH,GAvLtC,GAAII,IACAC,WAAY,OACZC,OAAQ,UACRC,KAAM,MACNC,SAAU,OACVC,KAAM,YACNC,OAAQ,WACRC,YAAa,yFACb1B,IAAK,sBACL2B,WAAY,wBACZC,aAAc,aACdC,KAAM,UAWV9B,GAAQM,OAAS,SAASyB,EAAYC,GAClC,GAAiEC,GAAkBC,EAAGC,EAAGC,EAAOC,EAAKC,EAAeC,EAAhHC,EAAS,EAAGC,EAAcV,EAAWW,OAAQC,EAAY,GAASC,KAA0DC,GAAc,EAAMf,EAAO,EAC3J,KAAKI,EAAI,EAAOO,EAAJP,EAAiBA,IAEzB,GADAS,EAAYnC,EAASuB,EAAWG,IACd,WAAdS,EACAC,EAAOA,EAAOF,QAAUX,EAAWG,OAElC,IAAkB,UAAdS,EAAuB,CAE5B,GADAP,EAAQL,EAAWG,GACfE,EAAM,GAEN,IADAH,EAAMD,EAAKQ,GACNL,EAAI,EAAGA,EAAIC,EAAM,GAAGM,OAAQP,IAAK,CAClC,IAAKF,EAAI7B,eAAegC,EAAM,GAAGD,IAC7B,KAAM,IAAIW,OAAM9C,EAAQ,yCAA0CoC,EAAM,GAAGD,IAE/EF,GAAMA,EAAIG,EAAM,GAAGD,QAIvBF,GADKG,EAAM,GACLJ,EAAKI,EAAM,IAGXJ,EAAKQ,IAOf,IAJqB,YAAjBhC,EAASyB,KACTA,EAAMA,KAGNb,EAAGC,WAAW0B,KAAKX,EAAM,KAAOhB,EAAGI,SAASuB,KAAKX,EAAM,KAAyB,UAAjB5B,EAASyB,IAAoBe,MAAMf,GAClG,KAAM,IAAIgB,WAAUjD,EAAQ,0CAA2CQ,EAASyB,IAOpF,QAJIb,EAAGE,OAAOyB,KAAKX,EAAM,MACrBS,EAAcZ,GAAO,GAGjBG,EAAM,IACV,IAAK,IACDH,EAAMA,EAAIrB,SAAS,EACvB,MACA,KAAK,IACDqB,EAAMiB,OAAOC,aAAalB,EAC9B,MACA,KAAK,IACL,IAAK,IACDA,EAAMmB,SAASnB,EAAK,GACxB,MACA,KAAK,IACDA,EAAMoB,KAAKC,UAAUrB,EAAK,KAAMG,EAAM,GAAKgB,SAAShB,EAAM,IAAM,EACpE,MACA,KAAK,IACDH,EAAMG,EAAM,GAAKH,EAAIsB,cAAcnB,EAAM,IAAMH,EAAIsB,eACvD,MACA,KAAK,IACDtB,EAAMG,EAAM,GAAKoB,WAAWvB,GAAKwB,QAAQrB,EAAM,IAAMoB,WAAWvB,EACpE,MACA,KAAK,IACDA,EAAMG,EAAM,GAAKoB,WAAWvB,GAAKyB,YAAYtB,EAAM,IAAMoB,WAAWvB,EACxE,MACA,KAAK,IACDA,EAAMA,EAAIrB,SAAS,EACvB,MACA,KAAK,IACDqB,GAAQA,EAAMiB,OAAOjB,KAASG,EAAM,GAAKH,EAAI0B,UAAU,EAAGvB,EAAM,IAAMH,CAC1E,MACA,KAAK,IACDA,KAAc,CAClB,MACA,KAAK,IACDA,EAAMA,EAAIrB,SAAS,GACvB,MACA,KAAK,IACDqB,EAAMA,EAAIrB,SAAS,IAAIgD,cAG3BxC,EAAGG,KAAKwB,KAAKX,EAAM,IACnBQ,EAAOA,EAAOF,QAAUT,IAGpBb,EAAGE,OAAOyB,KAAKX,EAAM,KAASS,IAAeT,EAAM,GAKnDN,EAAO,IAJPA,EAAOe,EAAc,IAAM,IAC3BZ,EAAMA,EAAIrB,WAAWiD,QAAQzC,EAAGU,KAAM,KAK1CQ,EAAgBF,EAAM,GAAkB,MAAbA,EAAM,GAAa,IAAMA,EAAM,GAAG0B,OAAO,GAAK,IACzEvB,EAAaH,EAAM,IAAMN,EAAOG,GAAKS,OACrCL,EAAMD,EAAM,IAAMG,EAAa,EAAIxB,EAAWuB,EAAeC,GAAoB,GACjFK,EAAOA,EAAOF,QAAUN,EAAM,GAAKN,EAAOG,EAAMI,EAAyB,MAAlBC,EAAwBR,EAAOO,EAAMJ,EAAMI,EAAMP,EAAOG,GAI3H,MAAOW,GAAOzB,KAAK,KAGvBnB,EAAQG,SAERH,EAAQK,MAAQ,SAAS0D,GAErB,IADA,GAAIC,GAAOD,EAAK3B,KAAYL,KAAiBkC,EAAY,EAClDD,GAAM,CACT,GAAqC,QAAhC5B,EAAQhB,EAAGK,KAAKyC,KAAKF,IACtBjC,EAAWA,EAAWW,QAAUN,EAAM,OAErC,IAAuC,QAAlCA,EAAQhB,EAAGM,OAAOwC,KAAKF,IAC7BjC,EAAWA,EAAWW,QAAU,QAE/B,CAAA,GAA4C,QAAvCN,EAAQhB,EAAGO,YAAYuC,KAAKF,IAgClC,KAAM,IAAIG,aAAY,mCA/BtB,IAAI/B,EAAM,GAAI,CACV6B,GAAa,CACb,IAAIG,MAAiBC,EAAoBjC,EAAM,GAAIkC,IACnD,IAAuD,QAAlDA,EAAclD,EAAGnB,IAAIiE,KAAKG,IAe3B,KAAM,IAAIF,aAAY,+CAbtB,KADAC,EAAWA,EAAW1B,QAAU4B,EAAY,GACwC,MAA5ED,EAAoBA,EAAkBV,UAAUW,EAAY,GAAG5B,UACnE,GAA8D,QAAzD4B,EAAclD,EAAGQ,WAAWsC,KAAKG,IAClCD,EAAWA,EAAW1B,QAAU4B,EAAY,OAE3C,CAAA,GAAgE,QAA3DA,EAAclD,EAAGS,aAAaqC,KAAKG,IAIzC,KAAM,IAAIF,aAAY,+CAHtBC,GAAWA,EAAW1B,QAAU4B,EAAY,GAUxDlC,EAAM,GAAKgC,MAGXH,IAAa,CAEjB,IAAkB,IAAdA,EACA,KAAM,IAAInB,OAAM,4EAEpBf,GAAWA,EAAWW,QAAUN,EAKpC4B,EAAOA,EAAKL,UAAUvB,EAAM,GAAGM,QAEnC,MAAOX,GAGX,IAAIwC,GAAW,SAASR,EAAK/B,EAAMwC,GAG/B,MAFAA,IAASxC,OAAYnB,MAAM,GAC3B2D,EAAMC,OAAO,EAAG,EAAGV,GACZ/D,EAAQ0E,MAAM,KAAMF,GAiBR,oBAAZG,UACPA,QAAQ3E,QAAUA,EAClB2E,QAAQJ,SAAWA,IAGnBxE,EAAOC,QAAUA,EACjBD,EAAOwE,SAAWA,EAEI,kBAAXK,SAAyBA,OAAOC,KACvCD,OAAO,WACH,OACI5E,QAASA,EACTuE,SAAUA,OAKT,mBAAXxE,QAAyB+E,KAAO/E"} \ No newline at end of file diff --git a/node_modules/sprintf-js/gruntfile.js b/node_modules/sprintf-js/gruntfile.js new file mode 100644 index 0000000..246e1c3 --- /dev/null +++ b/node_modules/sprintf-js/gruntfile.js @@ -0,0 +1,36 @@ +module.exports = function(grunt) { + grunt.initConfig({ + pkg: grunt.file.readJSON("package.json"), + + uglify: { + options: { + banner: "/*! <%= pkg.name %> | <%= pkg.author %> | <%= pkg.license %> */\n", + sourceMap: true + }, + build: { + files: [ + { + src: "src/sprintf.js", + dest: "dist/sprintf.min.js" + }, + { + src: "src/angular-sprintf.js", + dest: "dist/angular-sprintf.min.js" + } + ] + } + }, + + watch: { + js: { + files: "src/*.js", + tasks: ["uglify"] + } + } + }) + + grunt.loadNpmTasks("grunt-contrib-uglify") + grunt.loadNpmTasks("grunt-contrib-watch") + + grunt.registerTask("default", ["uglify", "watch"]) +} diff --git a/node_modules/sprintf-js/package.json b/node_modules/sprintf-js/package.json new file mode 100644 index 0000000..75f7eca --- /dev/null +++ b/node_modules/sprintf-js/package.json @@ -0,0 +1,22 @@ +{ + "name": "sprintf-js", + "version": "1.0.3", + "description": "JavaScript sprintf implementation", + "author": "Alexandru Marasteanu (http://alexei.ro/)", + "main": "src/sprintf.js", + "scripts": { + "test": "mocha test/test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/alexei/sprintf.js.git" + }, + "license": "BSD-3-Clause", + "readmeFilename": "README.md", + "devDependencies": { + "mocha": "*", + "grunt": "*", + "grunt-contrib-watch": "*", + "grunt-contrib-uglify": "*" + } +} diff --git a/node_modules/sprintf-js/src/angular-sprintf.js b/node_modules/sprintf-js/src/angular-sprintf.js new file mode 100644 index 0000000..9c69123 --- /dev/null +++ b/node_modules/sprintf-js/src/angular-sprintf.js @@ -0,0 +1,18 @@ +angular. + module("sprintf", []). + filter("sprintf", function() { + return function() { + return sprintf.apply(null, arguments) + } + }). + filter("fmt", ["$filter", function($filter) { + return $filter("sprintf") + }]). + filter("vsprintf", function() { + return function(format, argv) { + return vsprintf(format, argv) + } + }). + filter("vfmt", ["$filter", function($filter) { + return $filter("vsprintf") + }]) diff --git a/node_modules/sprintf-js/src/sprintf.js b/node_modules/sprintf-js/src/sprintf.js new file mode 100644 index 0000000..c0fc7c0 --- /dev/null +++ b/node_modules/sprintf-js/src/sprintf.js @@ -0,0 +1,208 @@ +(function(window) { + var re = { + not_string: /[^s]/, + number: /[diefg]/, + json: /[j]/, + not_json: /[^j]/, + text: /^[^\x25]+/, + modulo: /^\x25{2}/, + placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/, + key: /^([a-z_][a-z_\d]*)/i, + key_access: /^\.([a-z_][a-z_\d]*)/i, + index_access: /^\[(\d+)\]/, + sign: /^[\+\-]/ + } + + function sprintf() { + var key = arguments[0], cache = sprintf.cache + if (!(cache[key] && cache.hasOwnProperty(key))) { + cache[key] = sprintf.parse(key) + } + return sprintf.format.call(null, cache[key], arguments) + } + + sprintf.format = function(parse_tree, argv) { + var cursor = 1, tree_length = parse_tree.length, node_type = "", arg, output = [], i, k, match, pad, pad_character, pad_length, is_positive = true, sign = "" + for (i = 0; i < tree_length; i++) { + node_type = get_type(parse_tree[i]) + if (node_type === "string") { + output[output.length] = parse_tree[i] + } + else if (node_type === "array") { + match = parse_tree[i] // convenience purposes only + if (match[2]) { // keyword argument + arg = argv[cursor] + for (k = 0; k < match[2].length; k++) { + if (!arg.hasOwnProperty(match[2][k])) { + throw new Error(sprintf("[sprintf] property '%s' does not exist", match[2][k])) + } + arg = arg[match[2][k]] + } + } + else if (match[1]) { // positional argument (explicit) + arg = argv[match[1]] + } + else { // positional argument (implicit) + arg = argv[cursor++] + } + + if (get_type(arg) == "function") { + arg = arg() + } + + if (re.not_string.test(match[8]) && re.not_json.test(match[8]) && (get_type(arg) != "number" && isNaN(arg))) { + throw new TypeError(sprintf("[sprintf] expecting number but found %s", get_type(arg))) + } + + if (re.number.test(match[8])) { + is_positive = arg >= 0 + } + + switch (match[8]) { + case "b": + arg = arg.toString(2) + break + case "c": + arg = String.fromCharCode(arg) + break + case "d": + case "i": + arg = parseInt(arg, 10) + break + case "j": + arg = JSON.stringify(arg, null, match[6] ? parseInt(match[6]) : 0) + break + case "e": + arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential() + break + case "f": + arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg) + break + case "g": + arg = match[7] ? parseFloat(arg).toPrecision(match[7]) : parseFloat(arg) + break + case "o": + arg = arg.toString(8) + break + case "s": + arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg) + break + case "u": + arg = arg >>> 0 + break + case "x": + arg = arg.toString(16) + break + case "X": + arg = arg.toString(16).toUpperCase() + break + } + if (re.json.test(match[8])) { + output[output.length] = arg + } + else { + if (re.number.test(match[8]) && (!is_positive || match[3])) { + sign = is_positive ? "+" : "-" + arg = arg.toString().replace(re.sign, "") + } + else { + sign = "" + } + pad_character = match[4] ? match[4] === "0" ? "0" : match[4].charAt(1) : " " + pad_length = match[6] - (sign + arg).length + pad = match[6] ? (pad_length > 0 ? str_repeat(pad_character, pad_length) : "") : "" + output[output.length] = match[5] ? sign + arg + pad : (pad_character === "0" ? sign + pad + arg : pad + sign + arg) + } + } + } + return output.join("") + } + + sprintf.cache = {} + + sprintf.parse = function(fmt) { + var _fmt = fmt, match = [], parse_tree = [], arg_names = 0 + while (_fmt) { + if ((match = re.text.exec(_fmt)) !== null) { + parse_tree[parse_tree.length] = match[0] + } + else if ((match = re.modulo.exec(_fmt)) !== null) { + parse_tree[parse_tree.length] = "%" + } + else if ((match = re.placeholder.exec(_fmt)) !== null) { + if (match[2]) { + arg_names |= 1 + var field_list = [], replacement_field = match[2], field_match = [] + if ((field_match = re.key.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") { + if ((field_match = re.key_access.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + } + else if ((field_match = re.index_access.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + } + else { + throw new SyntaxError("[sprintf] failed to parse named argument key") + } + } + } + else { + throw new SyntaxError("[sprintf] failed to parse named argument key") + } + match[2] = field_list + } + else { + arg_names |= 2 + } + if (arg_names === 3) { + throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported") + } + parse_tree[parse_tree.length] = match + } + else { + throw new SyntaxError("[sprintf] unexpected placeholder") + } + _fmt = _fmt.substring(match[0].length) + } + return parse_tree + } + + var vsprintf = function(fmt, argv, _argv) { + _argv = (argv || []).slice(0) + _argv.splice(0, 0, fmt) + return sprintf.apply(null, _argv) + } + + /** + * helpers + */ + function get_type(variable) { + return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase() + } + + function str_repeat(input, multiplier) { + return Array(multiplier + 1).join(input) + } + + /** + * export to either browser or node.js + */ + if (typeof exports !== "undefined") { + exports.sprintf = sprintf + exports.vsprintf = vsprintf + } + else { + window.sprintf = sprintf + window.vsprintf = vsprintf + + if (typeof define === "function" && define.amd) { + define(function() { + return { + sprintf: sprintf, + vsprintf: vsprintf + } + }) + } + } +})(typeof window === "undefined" ? this : window); diff --git a/node_modules/sprintf-js/test/test.js b/node_modules/sprintf-js/test/test.js new file mode 100644 index 0000000..6f57b25 --- /dev/null +++ b/node_modules/sprintf-js/test/test.js @@ -0,0 +1,82 @@ +var assert = require("assert"), + sprintfjs = require("../src/sprintf.js"), + sprintf = sprintfjs.sprintf, + vsprintf = sprintfjs.vsprintf + +describe("sprintfjs", function() { + var pi = 3.141592653589793 + + it("should return formated strings for simple placeholders", function() { + assert.equal("%", sprintf("%%")) + assert.equal("10", sprintf("%b", 2)) + assert.equal("A", sprintf("%c", 65)) + assert.equal("2", sprintf("%d", 2)) + assert.equal("2", sprintf("%i", 2)) + assert.equal("2", sprintf("%d", "2")) + assert.equal("2", sprintf("%i", "2")) + assert.equal('{"foo":"bar"}', sprintf("%j", {foo: "bar"})) + assert.equal('["foo","bar"]', sprintf("%j", ["foo", "bar"])) + assert.equal("2e+0", sprintf("%e", 2)) + assert.equal("2", sprintf("%u", 2)) + assert.equal("4294967294", sprintf("%u", -2)) + assert.equal("2.2", sprintf("%f", 2.2)) + assert.equal("3.141592653589793", sprintf("%g", pi)) + assert.equal("10", sprintf("%o", 8)) + assert.equal("%s", sprintf("%s", "%s")) + assert.equal("ff", sprintf("%x", 255)) + assert.equal("FF", sprintf("%X", 255)) + assert.equal("Polly wants a cracker", sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants")) + assert.equal("Hello world!", sprintf("Hello %(who)s!", {"who": "world"})) + }) + + it("should return formated strings for complex placeholders", function() { + // sign + assert.equal("2", sprintf("%d", 2)) + assert.equal("-2", sprintf("%d", -2)) + assert.equal("+2", sprintf("%+d", 2)) + assert.equal("-2", sprintf("%+d", -2)) + assert.equal("2", sprintf("%i", 2)) + assert.equal("-2", sprintf("%i", -2)) + assert.equal("+2", sprintf("%+i", 2)) + assert.equal("-2", sprintf("%+i", -2)) + assert.equal("2.2", sprintf("%f", 2.2)) + assert.equal("-2.2", sprintf("%f", -2.2)) + assert.equal("+2.2", sprintf("%+f", 2.2)) + assert.equal("-2.2", sprintf("%+f", -2.2)) + assert.equal("-2.3", sprintf("%+.1f", -2.34)) + assert.equal("-0.0", sprintf("%+.1f", -0.01)) + assert.equal("3.14159", sprintf("%.6g", pi)) + assert.equal("3.14", sprintf("%.3g", pi)) + assert.equal("3", sprintf("%.1g", pi)) + assert.equal("-000000123", sprintf("%+010d", -123)) + assert.equal("______-123", sprintf("%+'_10d", -123)) + assert.equal("-234.34 123.2", sprintf("%f %f", -234.34, 123.2)) + + // padding + assert.equal("-0002", sprintf("%05d", -2)) + assert.equal("-0002", sprintf("%05i", -2)) + assert.equal(" <", sprintf("%5s", "<")) + assert.equal("0000<", sprintf("%05s", "<")) + assert.equal("____<", sprintf("%'_5s", "<")) + assert.equal("> ", sprintf("%-5s", ">")) + assert.equal(">0000", sprintf("%0-5s", ">")) + assert.equal(">____", sprintf("%'_-5s", ">")) + assert.equal("xxxxxx", sprintf("%5s", "xxxxxx")) + assert.equal("1234", sprintf("%02u", 1234)) + assert.equal(" -10.235", sprintf("%8.3f", -10.23456)) + assert.equal("-12.34 xxx", sprintf("%f %s", -12.34, "xxx")) + assert.equal('{\n "foo": "bar"\n}', sprintf("%2j", {foo: "bar"})) + assert.equal('[\n "foo",\n "bar"\n]', sprintf("%2j", ["foo", "bar"])) + + // precision + assert.equal("2.3", sprintf("%.1f", 2.345)) + assert.equal("xxxxx", sprintf("%5.5s", "xxxxxx")) + assert.equal(" x", sprintf("%5.1s", "xxxxxx")) + + }) + + it("should return formated strings for callbacks", function() { + assert.equal("foobar", sprintf("%s", function() { return "foobar" })) + assert.equal(Date.now(), sprintf("%s", Date.now)) // should pass... + }) +}) diff --git a/node_modules/ssri/LICENSE.md b/node_modules/ssri/LICENSE.md new file mode 100644 index 0000000..e335388 --- /dev/null +++ b/node_modules/ssri/LICENSE.md @@ -0,0 +1,16 @@ +ISC License + +Copyright 2021 (c) npm, Inc. + +Permission to use, copy, modify, and/or distribute this software for +any purpose with or without fee is hereby granted, provided that the +above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE COPYRIGHT HOLDER DISCLAIMS +ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR +CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE +USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/ssri/README.md b/node_modules/ssri/README.md new file mode 100644 index 0000000..6f46aa5 --- /dev/null +++ b/node_modules/ssri/README.md @@ -0,0 +1,528 @@ +# ssri [![npm version](https://img.shields.io/npm/v/ssri.svg)](https://npm.im/ssri) [![license](https://img.shields.io/npm/l/ssri.svg)](https://npm.im/ssri) [![Travis](https://img.shields.io/travis/npm/ssri.svg)](https://travis-ci.org/npm/ssri) [![AppVeyor](https://ci.appveyor.com/api/projects/status/github/npm/ssri?svg=true)](https://ci.appveyor.com/project/npm/ssri) [![Coverage Status](https://coveralls.io/repos/github/npm/ssri/badge.svg?branch=latest)](https://coveralls.io/github/npm/ssri?branch=latest) + +[`ssri`](https://github.com/npm/ssri), short for Standard Subresource +Integrity, is a Node.js utility for parsing, manipulating, serializing, +generating, and verifying [Subresource +Integrity](https://w3c.github.io/webappsec/specs/subresourceintegrity/) hashes. + +## Install + +`$ npm install --save ssri` + +## Table of Contents + +* [Example](#example) +* [Features](#features) +* [Contributing](#contributing) +* [API](#api) + * Parsing & Serializing + * [`parse`](#parse) + * [`stringify`](#stringify) + * [`Integrity#concat`](#integrity-concat) + * [`Integrity#merge`](#integrity-merge) + * [`Integrity#toString`](#integrity-to-string) + * [`Integrity#toJSON`](#integrity-to-json) + * [`Integrity#match`](#integrity-match) + * [`Integrity#pickAlgorithm`](#integrity-pick-algorithm) + * [`Integrity#hexDigest`](#integrity-hex-digest) + * Integrity Generation + * [`fromHex`](#from-hex) + * [`fromData`](#from-data) + * [`fromStream`](#from-stream) + * [`create`](#create) + * Integrity Verification + * [`checkData`](#check-data) + * [`checkStream`](#check-stream) + * [`integrityStream`](#integrity-stream) + +### Example + +```javascript +const ssri = require('ssri') + +const integrity = 'sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==?foo' + +// Parsing and serializing +const parsed = ssri.parse(integrity) +ssri.stringify(parsed) // === integrity (works on non-Integrity objects) +parsed.toString() // === integrity + +// Async stream functions +ssri.checkStream(fs.createReadStream('./my-file'), integrity).then(...) +ssri.fromStream(fs.createReadStream('./my-file')).then(sri => { + sri.toString() === integrity +}) +fs.createReadStream('./my-file').pipe(ssri.createCheckerStream(sri)) + +// Sync data functions +ssri.fromData(fs.readFileSync('./my-file')) // === parsed +ssri.checkData(fs.readFileSync('./my-file'), integrity) // => 'sha512' +``` + +### Features + +* Parses and stringifies SRI strings. +* Generates SRI strings from raw data or Streams. +* Strict standard compliance. +* `?foo` metadata option support. +* Multiple entries for the same algorithm. +* Object-based integrity hash manipulation. +* Small footprint: no dependencies, concise implementation. +* Full test coverage. +* Customizable algorithm picker. + +### Contributing + +The ssri team enthusiastically welcomes contributions and project participation! +There's a bunch of things you can do if you want to contribute! The [Contributor +Guide](CONTRIBUTING.md) has all the information you need for everything from +reporting bugs to contributing entire new features. Please don't hesitate to +jump in if you'd like to, or even ask us questions if something isn't clear. + +### API + +#### `> ssri.parse(sri, [opts]) -> Integrity` + +Parses `sri` into an `Integrity` data structure. `sri` can be an integrity +string, an `Hash`-like with `digest` and `algorithm` fields and an optional +`options` field, or an `Integrity`-like object. The resulting object will be an +`Integrity` instance that has this shape: + +```javascript +{ + 'sha1': [{algorithm: 'sha1', digest: 'deadbeef', options: []}], + 'sha512': [ + {algorithm: 'sha512', digest: 'c0ffee', options: []}, + {algorithm: 'sha512', digest: 'bad1dea', options: ['foo']} + ], +} +``` + +If `opts.single` is truthy, a single `Hash` object will be returned. That is, a +single object that looks like `{algorithm, digest, options}`, as opposed to a +larger object with multiple of these. + +If `opts.strict` is truthy, the resulting object will be filtered such that +it strictly follows the Subresource Integrity spec, throwing away any entries +with any invalid components. This also means a restricted set of algorithms +will be used -- the spec limits them to `sha256`, `sha384`, and `sha512`. + +Strict mode is recommended if the integrity strings are intended for use in +browsers, or in other situations where strict adherence to the spec is needed. + +##### Example + +```javascript +ssri.parse('sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==?foo') // -> Integrity object +``` + +#### `> ssri.stringify(sri, [opts]) -> String` + +This function is identical to [`Integrity#toString()`](#integrity-to-string), +except it can be used on _any_ object that [`parse`](#parse) can handle -- that +is, a string, an `Hash`-like, or an `Integrity`-like. + +The `opts.sep` option defines the string to use when joining multiple entries +together. To be spec-compliant, this _must_ be whitespace. The default is a +single space (`' '`). + +If `opts.strict` is true, the integrity string will be created using strict +parsing rules. See [`ssri.parse`](#parse). + +##### Example + +```javascript +// Useful for cleaning up input SRI strings: +ssri.stringify('\n\rsha512-foo\n\t\tsha384-bar') +// -> 'sha512-foo sha384-bar' + +// Hash-like: only a single entry. +ssri.stringify({ + algorithm: 'sha512', + digest:'9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==', + options: ['foo'] +}) +// -> +// 'sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==?foo' + +// Integrity-like: full multi-entry syntax. Similar to output of `ssri.parse` +ssri.stringify({ + 'sha512': [ + { + algorithm: 'sha512', + digest:'9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==', + options: ['foo'] + } + ] +}) +// -> +// 'sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==?foo' +``` + +#### `> Integrity#concat(otherIntegrity, [opts]) -> Integrity` + +Concatenates an `Integrity` object with another IntegrityLike, or an integrity +string. + +This is functionally equivalent to concatenating the string format of both +integrity arguments, and calling [`ssri.parse`](#ssri-parse) on the new string. + +If `opts.strict` is true, the new `Integrity` will be created using strict +parsing rules. See [`ssri.parse`](#parse). + +##### Example + +```javascript +// This will combine the integrity checks for two different versions of +// your index.js file so you can use a single integrity string and serve +// either of these to clients, from a single ` + + + +
+ {% include "partials/header.njk" %} +
+

{{ title }}

+
+ {{ content | safe }} +
+
+ {% include "partials/footer.njk" %} +
+ + diff --git a/src/_includes/layouts/posts.njk b/src/_includes/layouts/posts.njk new file mode 100644 index 0000000..abee4cb --- /dev/null +++ b/src/_includes/layouts/posts.njk @@ -0,0 +1,22 @@ +--- +layout: /layouts/base.njk +--- + +
+ {{ page.date | string | truncate(15, true, "") }} + minutes read +
+ +
+ {{ content | safe }} +
+ \ No newline at end of file diff --git a/src/_includes/partials/footer.njk b/src/_includes/partials/footer.njk new file mode 100644 index 0000000..5879446 --- /dev/null +++ b/src/_includes/partials/footer.njk @@ -0,0 +1,19 @@ + \ No newline at end of file diff --git a/src/_includes/partials/header.njk b/src/_includes/partials/header.njk new file mode 100644 index 0000000..9c8bc60 --- /dev/null +++ b/src/_includes/partials/header.njk @@ -0,0 +1,13 @@ +
+

{{ headtitle | default("nihil's wretched abode :3") }}

+ +
\ No newline at end of file diff --git a/src/assets/css/tailwind.css b/src/assets/css/tailwind.css new file mode 100644 index 0000000..d0716eb --- /dev/null +++ b/src/assets/css/tailwind.css @@ -0,0 +1,79 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; + +@font-face { + font-family: "Gaegu"; + src: + local("Gaegu-Regular"), + url('../fonts/Gaegu-Regular.ttf') format("truetype"); +} + +@font-face { + font-family: "Darumadrop One"; + src: + local("DarumadropOne-Regular"), + url('../fonts/DarumadropOne.ttf') format("truetype"); +} + +@font-face { + font-family: "Pangolin"; + src: + local("Pangolin-Regular"), + url('../fonts/Pangolin-Regular.ttf') format("truetype"); +} + +#embed-container { + position: relative; + overflow: hidden; + width: 100%; + padding-top: 56.25%; +} + +#responsive-frame { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + width: 100%; + height: 100%; +} + + + +.hr-main { + @apply m-5 bg-slate-600 rounded h-0.5 mx-auto w-2/3 lg:w-3/5 opacity-80; +} + +.btn-link { + @apply flex justify-center items-center h-20 w-20 hover:h-24 hover:w-24 text-white text-center bg-amber-400 border-current hover:border-4 hover:bg-transparent hover:text-amber-400 hover:border-amber-400 rounded-lg font-heading hover:animate-wiggle-strong group-hover/link-btns:animate-wiggle-soft transition-all duration-300; +} + +.nav-link { + @apply text-pink-200 mx-4 transition-all duration-200 hover:text-pink-600 hover:animate-bounce; +} + +main a { + @apply hover:animate-text-shadow-pop-sm; +} + +ul { + @apply list-disc list-inside text-justify inline-flex flex-col; +} + +a { + @apply text-purple-500 hover:text-pink-500; +} + +h1 { + @apply text-4xl lg:text-5xl font-heading text-off-white text-center; +} + +h2 { + @apply text-3xl lg:text-4xl font-heading text-pink-400 text-center; +} + +h3 { + @apply text-2xl lg:text-3xl font-body font-black text-pink-400 text-center; +} diff --git a/src/index.html b/src/index.html new file mode 100755 index 0000000..ce93620 --- /dev/null +++ b/src/index.html @@ -0,0 +1,47 @@ +--- +layout: layouts/base.njk +title: "omg haii :3" +--- +
+
+

+ welcome to my little horrible abode :3 +
+ here is a list of links to the services on this server, all of which are invite only, sorry >_< +

+
+
+ \ No newline at end of file diff --git a/src/output.css b/src/output.css new file mode 100644 index 0000000..2b1cc73 --- /dev/null +++ b/src/output.css @@ -0,0 +1,555 @@ +*, ::before, ::after { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; + --tw-translate-x: 0; + --tw-translate-y: 0; + --tw-rotate: 0; + --tw-skew-x: 0; + --tw-skew-y: 0; + --tw-scale-x: 1; + --tw-scale-y: 1; + --tw-pan-x: ; + --tw-pan-y: ; + --tw-pinch-zoom: ; + --tw-scroll-snap-strictness: proximity; + --tw-gradient-from-position: ; + --tw-gradient-via-position: ; + --tw-gradient-to-position: ; + --tw-ordinal: ; + --tw-slashed-zero: ; + --tw-numeric-figure: ; + --tw-numeric-spacing: ; + --tw-numeric-fraction: ; + --tw-ring-inset: ; + --tw-ring-offset-width: 0px; + --tw-ring-offset-color: #fff; + --tw-ring-color: rgb(59 130 246 / 0.5); + --tw-ring-offset-shadow: 0 0 #0000; + --tw-ring-shadow: 0 0 #0000; + --tw-shadow: 0 0 #0000; + --tw-shadow-colored: 0 0 #0000; + --tw-blur: ; + --tw-brightness: ; + --tw-contrast: ; + --tw-grayscale: ; + --tw-hue-rotate: ; + --tw-invert: ; + --tw-saturate: ; + --tw-sepia: ; + --tw-drop-shadow: ; + --tw-backdrop-blur: ; + --tw-backdrop-brightness: ; + --tw-backdrop-contrast: ; + --tw-backdrop-grayscale: ; + --tw-backdrop-hue-rotate: ; + --tw-backdrop-invert: ; + --tw-backdrop-opacity: ; + --tw-backdrop-saturate: ; + --tw-backdrop-sepia: ; + --tw-contain-size: ; + --tw-contain-layout: ; + --tw-contain-paint: ; + --tw-contain-style: ; +} + +::backdrop { + --tw-border-spacing-x: 0; + --tw-border-spacing-y: 0; + --tw-translate-x: 0; + --tw-translate-y: 0; + --tw-rotate: 0; + --tw-skew-x: 0; + --tw-skew-y: 0; + --tw-scale-x: 1; + --tw-scale-y: 1; + --tw-pan-x: ; + --tw-pan-y: ; + --tw-pinch-zoom: ; + --tw-scroll-snap-strictness: proximity; + --tw-gradient-from-position: ; + --tw-gradient-via-position: ; + --tw-gradient-to-position: ; + --tw-ordinal: ; + --tw-slashed-zero: ; + --tw-numeric-figure: ; + --tw-numeric-spacing: ; + --tw-numeric-fraction: ; + --tw-ring-inset: ; + --tw-ring-offset-width: 0px; + --tw-ring-offset-color: #fff; + --tw-ring-color: rgb(59 130 246 / 0.5); + --tw-ring-offset-shadow: 0 0 #0000; + --tw-ring-shadow: 0 0 #0000; + --tw-shadow: 0 0 #0000; + --tw-shadow-colored: 0 0 #0000; + --tw-blur: ; + --tw-brightness: ; + --tw-contrast: ; + --tw-grayscale: ; + --tw-hue-rotate: ; + --tw-invert: ; + --tw-saturate: ; + --tw-sepia: ; + --tw-drop-shadow: ; + --tw-backdrop-blur: ; + --tw-backdrop-brightness: ; + --tw-backdrop-contrast: ; + --tw-backdrop-grayscale: ; + --tw-backdrop-hue-rotate: ; + --tw-backdrop-invert: ; + --tw-backdrop-opacity: ; + --tw-backdrop-saturate: ; + --tw-backdrop-sepia: ; + --tw-contain-size: ; + --tw-contain-layout: ; + --tw-contain-paint: ; + --tw-contain-style: ; +} + +/* +! tailwindcss v3.4.14 | MIT License | https://tailwindcss.com +*/ + +/* +1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) +2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116) +*/ + +*, +::before, +::after { + box-sizing: border-box; + /* 1 */ + border-width: 0; + /* 2 */ + border-style: solid; + /* 2 */ + border-color: #e5e7eb; + /* 2 */ +} + +::before, +::after { + --tw-content: ''; +} + +/* +1. Use a consistent sensible line-height in all browsers. +2. Prevent adjustments of font size after orientation changes in iOS. +3. Use a more readable tab size. +4. Use the user's configured `sans` font-family by default. +5. Use the user's configured `sans` font-feature-settings by default. +6. Use the user's configured `sans` font-variation-settings by default. +7. Disable tap highlights on iOS +*/ + +html, +:host { + line-height: 1.5; + /* 1 */ + -webkit-text-size-adjust: 100%; + /* 2 */ + -moz-tab-size: 4; + /* 3 */ + -o-tab-size: 4; + tab-size: 4; + /* 3 */ + font-family: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; + /* 4 */ + font-feature-settings: normal; + /* 5 */ + font-variation-settings: normal; + /* 6 */ + -webkit-tap-highlight-color: transparent; + /* 7 */ +} + +/* +1. Remove the margin in all browsers. +2. Inherit line-height from `html` so users can set them as a class directly on the `html` element. +*/ + +body { + margin: 0; + /* 1 */ + line-height: inherit; + /* 2 */ +} + +/* +1. Add the correct height in Firefox. +2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655) +3. Ensure horizontal rules are visible by default. +*/ + +hr { + height: 0; + /* 1 */ + color: inherit; + /* 2 */ + border-top-width: 1px; + /* 3 */ +} + +/* +Add the correct text decoration in Chrome, Edge, and Safari. +*/ + +abbr:where([title]) { + -webkit-text-decoration: underline dotted; + text-decoration: underline dotted; +} + +/* +Remove the default font size and weight for headings. +*/ + +h1, +h2, +h3, +h4, +h5, +h6 { + font-size: inherit; + font-weight: inherit; +} + +/* +Reset links to optimize for opt-in styling instead of opt-out. +*/ + +a { + color: inherit; + text-decoration: inherit; +} + +/* +Add the correct font weight in Edge and Safari. +*/ + +b, +strong { + font-weight: bolder; +} + +/* +1. Use the user's configured `mono` font-family by default. +2. Use the user's configured `mono` font-feature-settings by default. +3. Use the user's configured `mono` font-variation-settings by default. +4. Correct the odd `em` font sizing in all browsers. +*/ + +code, +kbd, +samp, +pre { + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + /* 1 */ + font-feature-settings: normal; + /* 2 */ + font-variation-settings: normal; + /* 3 */ + font-size: 1em; + /* 4 */ +} + +/* +Add the correct font size in all browsers. +*/ + +small { + font-size: 80%; +} + +/* +Prevent `sub` and `sup` elements from affecting the line height in all browsers. +*/ + +sub, +sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; +} + +sub { + bottom: -0.25em; +} + +sup { + top: -0.5em; +} + +/* +1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297) +2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016) +3. Remove gaps between table borders by default. +*/ + +table { + text-indent: 0; + /* 1 */ + border-color: inherit; + /* 2 */ + border-collapse: collapse; + /* 3 */ +} + +/* +1. Change the font styles in all browsers. +2. Remove the margin in Firefox and Safari. +3. Remove default padding in all browsers. +*/ + +button, +input, +optgroup, +select, +textarea { + font-family: inherit; + /* 1 */ + font-feature-settings: inherit; + /* 1 */ + font-variation-settings: inherit; + /* 1 */ + font-size: 100%; + /* 1 */ + font-weight: inherit; + /* 1 */ + line-height: inherit; + /* 1 */ + letter-spacing: inherit; + /* 1 */ + color: inherit; + /* 1 */ + margin: 0; + /* 2 */ + padding: 0; + /* 3 */ +} + +/* +Remove the inheritance of text transform in Edge and Firefox. +*/ + +button, +select { + text-transform: none; +} + +/* +1. Correct the inability to style clickable types in iOS and Safari. +2. Remove default button styles. +*/ + +button, +input:where([type='button']), +input:where([type='reset']), +input:where([type='submit']) { + -webkit-appearance: button; + /* 1 */ + background-color: transparent; + /* 2 */ + background-image: none; + /* 2 */ +} + +/* +Use the modern Firefox focus style for all focusable elements. +*/ + +:-moz-focusring { + outline: auto; +} + +/* +Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737) +*/ + +:-moz-ui-invalid { + box-shadow: none; +} + +/* +Add the correct vertical alignment in Chrome and Firefox. +*/ + +progress { + vertical-align: baseline; +} + +/* +Correct the cursor style of increment and decrement buttons in Safari. +*/ + +::-webkit-inner-spin-button, +::-webkit-outer-spin-button { + height: auto; +} + +/* +1. Correct the odd appearance in Chrome and Safari. +2. Correct the outline style in Safari. +*/ + +[type='search'] { + -webkit-appearance: textfield; + /* 1 */ + outline-offset: -2px; + /* 2 */ +} + +/* +Remove the inner padding in Chrome and Safari on macOS. +*/ + +::-webkit-search-decoration { + -webkit-appearance: none; +} + +/* +1. Correct the inability to style clickable types in iOS and Safari. +2. Change font properties to `inherit` in Safari. +*/ + +::-webkit-file-upload-button { + -webkit-appearance: button; + /* 1 */ + font: inherit; + /* 2 */ +} + +/* +Add the correct display in Chrome and Safari. +*/ + +summary { + display: list-item; +} + +/* +Removes the default spacing and border for appropriate elements. +*/ + +blockquote, +dl, +dd, +h1, +h2, +h3, +h4, +h5, +h6, +hr, +figure, +p, +pre { + margin: 0; +} + +fieldset { + margin: 0; + padding: 0; +} + +legend { + padding: 0; +} + +ol, +ul, +menu { + list-style: none; + margin: 0; + padding: 0; +} + +/* +Reset default styling for dialogs. +*/ + +dialog { + padding: 0; +} + +/* +Prevent resizing textareas horizontally by default. +*/ + +textarea { + resize: vertical; +} + +/* +1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300) +2. Set the default placeholder color to the user's configured gray 400 color. +*/ + +input::-moz-placeholder, textarea::-moz-placeholder { + opacity: 1; + /* 1 */ + color: #9ca3af; + /* 2 */ +} + +input::placeholder, +textarea::placeholder { + opacity: 1; + /* 1 */ + color: #9ca3af; + /* 2 */ +} + +/* +Set the default cursor for buttons. +*/ + +button, +[role="button"] { + cursor: pointer; +} + +/* +Make sure disabled buttons don't get the pointer cursor. +*/ + +:disabled { + cursor: default; +} + +/* +1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14) +2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210) + This can trigger a poorly considered lint error in some tools but is included by design. +*/ + +img, +svg, +video, +canvas, +audio, +iframe, +embed, +object { + display: block; + /* 1 */ + vertical-align: middle; + /* 2 */ +} + +/* +Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14) +*/ + +img, +video { + max-width: 100%; + height: auto; +} + +/* Make elements with the HTML hidden attribute stay hidden by default */ + +[hidden]:where(:not([hidden="until-found"])) { + display: none; +} diff --git a/src/posts/index.html b/src/posts/index.html new file mode 100644 index 0000000..f4a0fe6 --- /dev/null +++ b/src/posts/index.html @@ -0,0 +1,48 @@ +--- +layout: layouts/base.njk +title: "Posts :3" +override:tags: [] +templateEngineOverride: 'njk' +pagination: + data: collections.post + size: 6 + alias: posts +--- + +
+
+ {% for post in posts %} +
+ +

{{ post.data.title }}

+
{{ post.templateContent | striptags(true) | truncatewords(20) | safe }}
+

{{ post.date | string | truncate(15, true, "")}}

+
+
+ {% if not loop.last %} +
+ {% endif %} + {% endfor %} +
+
+ {% if pagination.pageNumber >= 2 %} + 1 + {% if pagination.pageNumber > 2 %} + + {% endif %} + {% endif %} + {% if pagination.pageNumber >= 1 %} + + {% endif %} + {{ pagination.pageNumber + 1 }} + {% if pagination.page.next %} + + {% if pagination.pageNumber + 2 < pagination.pages.length %} + {% if pagination.pageNumber + 3 < pagination.pages.length %} + + {% endif %} + {{ pagination.pages.length }} + {% endif %} + {% endif %} +
+
\ No newline at end of file diff --git a/src/posts/posts.json b/src/posts/posts.json new file mode 100755 index 0000000..d0fe296 --- /dev/null +++ b/src/posts/posts.json @@ -0,0 +1,4 @@ +{ + "layout": "layouts/posts.njk", + "tags": "post" +} \ No newline at end of file diff --git a/tailwind.config.js b/tailwind.config.js new file mode 100644 index 0000000..36ae708 --- /dev/null +++ b/tailwind.config.js @@ -0,0 +1,82 @@ +/** @type {import('tailwindcss').Config} */ +export default { + content: ["./src/**/*.{njk,html,md}"], + theme: { + fontFamily: { + sans: ['Cantarell', 'sans-serif'], + serif: ['Junicode', 'serif'], + heading: ['Darumadrop One', 'cursive'], + body: ['Pangolin', 'sans'] + }, + extend: { + keyframes: { + bounce: { + '50%': { + transform: 'translateY(-25%)', + 'animation-timing-function': 'cubic-bezier(0.8, 0, 1, 1)', + }, + '0%, 100%': { + transform: 'translateY(0)', + 'animation-timing-function': 'cubic-bezier(0, 0, 0.2, 1)' + } + }, + 'wiggle-strong': { + '0%, 100%': { + transform: 'rotate(-5deg)' + }, + '50%': { + transform: 'rotate(5deg)' + } + }, + 'wiggle-soft': { + '0%, 100%': { + transform: 'rotate(-1deg)' + }, + '50%': { + transform: 'rotate(1deg)' + } + }, + 'text-shadow-pop': { + '0%': { + 'text-shadow': '0 0 #555555, 0 0 #555555, 0 0 #555555, 0 0 #555555, 0 0 #555555, 0 0 #555555, 0 0 #555555, 0 0 #555555', + '-webkit-transform': 'translateX(0) translateY(0)', + transform: 'translateX(0) translateY(0)', + }, + '100%': { + 'text-shadow': '1px -1px #555555, 2px -2px #555555, 3px -3px #555555, 4px -4px #555555, 5px -5px #555555, 6px -6px #555555, 7px -7px #555555, 8px -8px #555555', + '-webkit-transform': 'translateX(-8px) translateY(8px)', + 'transform': 'translateX(-8px) translateY(8px)', + } + }, + 'text-shadow-pop-sm': { + '0%': { + 'text-shadow': '0 0 #555555, 0 0 #555555, 0 0 #555555, 0 0 #555555', + '-webkit-transform': 'translateX(0) translateY(0)', + transform: 'translateX(0) translateY(0)', + }, + '100%': { + 'text-shadow': '1px -1px #555555, 2px -2px #555555, 3px -3px #555555, 4px -4px #555555', + '-webkit-transform': 'translateX(-4px) translateY(4px)', + 'transform': 'translateX(-4px) translateY(4px)', + } + }, + }, + animation: { + 'wiggle-strong': 'wiggle-strong 0.3s ease-in-out infinite', + 'wiggle-soft': 'wiggle-soft 0.263s ease-in-out infinite', + bounce: 'bounce 0.8s infinite', + 'text-shadow-pop': 'text-shadow-pop 0.6s both', + 'text-shadow-pop-sm': 'text-shadow-pop-sm 0.6s both' + }, + colors: { + 'deep-purple': '#1b0035', + 'off-white': '#fff7fa', + 'sun': '#f5ac2e', + }, + }, + }, + plugins: [ + require('@tailwindcss/typography'), + ], +} +