commit 38940436a7266b27065caba017639cf5f8545e5b Author: Lee Cattarin Date: Tue Mar 31 16:38:22 2026 -0700 first diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/COPYING @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 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 Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7942b72 --- /dev/null +++ b/LICENSE @@ -0,0 +1,15 @@ + +Copyright (C) 2026 Lee Cattarin + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . diff --git a/_config/filters.js b/_config/filters.js new file mode 100644 index 0000000..1153349 --- /dev/null +++ b/_config/filters.js @@ -0,0 +1,29 @@ +export default function (eleventyConfig) { + + /* Create a single alt string from a multi-string alt object */ + eleventyConfig.addFilter("createAlt", (altObject) => { + let alt; + + if (altObject.length > 1) + alt = `a ${altObject.length} picture collage.`; + for (let i = 0; i < altObject.length; i++) + alt += ` Image ${i + 1} is ${altObject[i]}`; + + return alt; + }); + + /* What it says on the tin */ + eleventyConfig.addFilter("randomize", function(array) { + // Create a copy of the array to avoid modifying the original + let shuffledArray = array.slice(); + + // Fisher-Yates shuffle algorithm + for (let i = shuffledArray.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]]; + } + + return shuffledArray; + }); + +}; diff --git a/_data/metadata.js b/_data/metadata.js new file mode 100644 index 0000000..f715f7a --- /dev/null +++ b/_data/metadata.js @@ -0,0 +1,6 @@ +export default { + title: "the historic Beall Greenhouses", + description: "the historic Beall Greenhouses", + url: "https://beall-greenhouses.com", + author: "Lee Cattarin" +} diff --git a/_includes/artistlist.njk b/_includes/artistlist.njk new file mode 100644 index 0000000..eb918a7 --- /dev/null +++ b/_includes/artistlist.njk @@ -0,0 +1,31 @@ +{% css %}{% include "css/artist-market.css" %}{% endcss %} + +
    + {% for artist in artists | randomize %} +
  • + {% if artist.data.img.src and artist.data.img.alt %} +
    + {{ artist.data.img.alt | createAlt }} +
    + {% endif %} +

    {{ artist.data.title }}

    +
    + {% for paragraph in artist.data.bio %} +

    {{ paragraph }}

    + {% endfor %} + + {% if artist.data.contacts %} + + {% endif %} +
    +
  • + {% endfor %} +
diff --git a/_includes/directory.njk b/_includes/directory.njk new file mode 100644 index 0000000..732500e --- /dev/null +++ b/_includes/directory.njk @@ -0,0 +1,14 @@ +{% css %}{% include "css/directory.css" %}{% endcss %} + +
    +{% for item in items %} +
  1. + +

    {{ item.data.shortTitle or item.data.title }}

    + {% if item.data.img.src and item.data.img.alt %} + {{ item.data.img.alt }} + {% endif %} +
    +
  2. +{% endfor %} +
diff --git a/_includes/footer.njk b/_includes/footer.njk new file mode 100644 index 0000000..f53c212 --- /dev/null +++ b/_includes/footer.njk @@ -0,0 +1,7 @@ + diff --git a/_includes/head.njk b/_includes/head.njk new file mode 100644 index 0000000..0b693d4 --- /dev/null +++ b/_includes/head.njk @@ -0,0 +1,37 @@ + + {% if title %} + {% set pageTitle %}{{ title }} | {{ metadata.title }}{% endset %} + {% else %} + {% set pageTitle = metadata.title %} + {% endif %} + {{ pageTitle }} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/_includes/header.njk b/_includes/header.njk new file mode 100644 index 0000000..82ce15e --- /dev/null +++ b/_includes/header.njk @@ -0,0 +1,24 @@ +
+ +
diff --git a/_includes/layouts/base.njk b/_includes/layouts/base.njk new file mode 100644 index 0000000..c3cfb82 --- /dev/null +++ b/_includes/layouts/base.njk @@ -0,0 +1,16 @@ + + +{% include "head.njk" %} + +
+ {% include "header.njk" %} + +
+ {{ content | safe }} +
+
+ + {% include "footer.njk" %} + + + diff --git a/_includes/layouts/page.njk b/_includes/layouts/page.njk new file mode 100644 index 0000000..44515f9 --- /dev/null +++ b/_includes/layouts/page.njk @@ -0,0 +1,7 @@ +--- +layout: base.njk +--- + +

{{ title }}

+ +{{ content | safe }} diff --git a/_includes/layouts/resident.njk b/_includes/layouts/resident.njk new file mode 100644 index 0000000..8761a3c --- /dev/null +++ b/_includes/layouts/resident.njk @@ -0,0 +1,6 @@ +--- +layout: base.njk +--- +{% css %}{% include "css/artist-resident.css" %}{% endcss %} + +{{ content | safe }} diff --git a/_live/about/index.html b/_live/about/index.html new file mode 100644 index 0000000..18e2323 --- /dev/null +++ b/_live/about/index.html @@ -0,0 +1,428 @@ + + + + + + + About the Beall Greenhouses | the historic Beall Greenhouses + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+ + +
+ +

About the Beall Greenhouses

+ + + + + +
+
+ + + + + + diff --git a/_live/artists/index.html b/_live/artists/index.html new file mode 100644 index 0000000..c4a6b1e --- /dev/null +++ b/_live/artists/index.html @@ -0,0 +1,500 @@ + + + + + + + Artists in residence at the Beall Greenhouses | the historic Beall Greenhouses + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+ + +
+ +

Artists in residence at the Beall Greenhouses

+ + + + + +
    + +
  1. + +

    Jennifer Hawke

    + + jennifer hawke, the artist, a white person with a beard and knowing eyes. the top half of their face is painted blue with a white heart, and they are wearing a huge elaborate flower crown, a red shawl, and several chunky pendants. + +
    +
  2. + +
+ + + +
+
+ + + + + + diff --git a/_live/artists/jennifer-hawke/index.html b/_live/artists/jennifer-hawke/index.html new file mode 100644 index 0000000..3795b12 --- /dev/null +++ b/_live/artists/jennifer-hawke/index.html @@ -0,0 +1,545 @@ + + + + + + + Jennifer Hawke | the historic Beall Greenhouses + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+ + +
+ + + +
+ jennifer hawke, the artist, a white person with a beard and knowing eyes. the top half of their face is painted blue with a white heart, and they are wearing a huge elaborate flower crown, a red shawl, and several chunky pendants. +

Jennifer Hawke

+
+

Jennifer Hawke hails from Billings, Montana where they got their degree in Cast Metals and Painting. They have been on Vashon Island for about 18 years and love doing the Bearded Lady Road Report. They have had their Studio at the Beall Greenhouses for about 8 years and only recently started opening to the public. Their space is warmed by a singular woodstove & all the ephemera that comes with being the child of an antique dealer.

+
+
+ +
+

Get in touch...

+ +
+ + +
+
+ + + + + + diff --git a/_live/attribution/index.html b/_live/attribution/index.html new file mode 100644 index 0000000..27ae31c --- /dev/null +++ b/_live/attribution/index.html @@ -0,0 +1,442 @@ + + + + + + + Attribution | the historic Beall Greenhouses + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+ + +
+ +

Attribution

+ + +
+

This website is created and maintained by + Lee Cattarin. + Markets at the Beall Greenhouses are coordinated by + Jennifer Hawke. +

+

+ Much thanks to all the participating artists, both + artists in residence + and market artists. +

+

+ This site is created with + Eleventy v3.1.5 + and built + + without the use of generative AI. +

+
+ + +
+
+ + + + + + diff --git a/_live/events/2025-solstice/index.html b/_live/events/2025-solstice/index.html new file mode 100644 index 0000000..6c6bf5e --- /dev/null +++ b/_live/events/2025-solstice/index.html @@ -0,0 +1,838 @@ + + + + + + + Solstice 2025 Market at the Beall Greenhouses | the historic Beall Greenhouses + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+ + +
+ +

Solstice 2025 Market at the Beall Greenhouses

+ + +

When?

+

.

+ +

Where?

+

Studios in the former cold storage facility at the old Beall Greenhouses: + 18527 Beall Rd SW, Vashon, WA 98070 +

+ +

What else?

+

There will be popcorn, cookies, fresh hot coffee from + Zenbellies Coffee Co., + and a warm fire. +

+ +

Who?

+ + + + +
    + +
  • + +
    + undefined Image 1 is 3 picture collage of a white brunette woman. in picture one, she sits on a tall stool with her leg pulled up, holding paintbrushes. in picture 2 she stares at the camera with chanterelles held up to her ears. picture 3, she aims a camera at the camera. +
    + +

    Hope Black

    +
    + +

    Hope Black is a conceptual portrait photographer and multi-media artist based on Vashon Island, WA. Her work blends fine-art portraiture with macabre photo editing, and she draws on mixed-media illustrations, varied textures, and found-objects to create portraits and paintings that feel symbolic and dream-like. Her images echo the archetypes found in the tarot and the emotional undercurrents of womanhood -- inviting viewers into a world that is both haunting and deeply human.

    + + + + + +
    +
  • + +
  • + +
    + a 4 picture collage. Image 1 is Coulter pinecone with dried oranges, & apples, dried flowers, & bay leaves. Image 2 is a collage titled 'when the black rock opens'. artist statement on the piece Intentional Collage, seeds have been planted in the line of the future. There is a promise of what will be growing when it is time for us to understand. Image 3 is Coulter pinecone with feathers, moon, snail shell, dried flowers, spices, bay leaves, and found sculpted porcelain face. Image 4 is jennifer hawke, the artist, a white person with a beard and knowing eyes. the top half of their face is painted blue with a white heart, and they are wearing a huge elaborate flower crown, a red shawl, and several chunky pendants. +
    + +

    Jennifer Hawke

    +
    + +

    Jennifer Hawke hails from Billings, Montana where they got their degree in Cast Metals and Painting. They have been on Vashon Island for about 18 years and love doing the Bearded Lady Road Report. They have had their Studio at the Beall Greenhouses for about 8 years and only recently started opening to the public. Their space is warmed by a singular woodstove & all the ephemera that comes with being the child of an antique dealer.

    + + + + + +
    +
  • + +
  • + +
    + a 5 picture collage. Image 1 is moon jellyfish on dark background. Image 2 is Spruce trees in mist. Image 3 is Opalescent nudibranch. Image 4 is Salmon troller in front of alaskan volcano. Image 5 is Underwater photo of bull kelp. +
    + +

    Logan Price Photography

    +
    + +

    Unique underwater photographs of local northwest sea creatures taken while freediving, and stunning large format land-and-seascapes from Southeast Alaska.

    + + + + + +
    +
  • + +
  • + +
    + a 312 picture collage. Image 1 is 4 Image 2 is   Image 3 is p Image 4 is h Image 5 is o Image 6 is t Image 7 is o Image 8 is   Image 9 is c Image 10 is o Image 11 is l Image 12 is l Image 13 is a Image 14 is g Image 15 is e Image 16 is . Image 17 is   Image 18 is c Image 19 is l Image 20 is o Image 21 is c Image 22 is k Image 23 is w Image 24 is i Image 25 is s Image 26 is e Image 27 is   Image 28 is f Image 29 is r Image 30 is o Image 31 is m Image 32 is   Image 33 is t Image 34 is o Image 35 is p Image 36 is   Image 37 is l Image 38 is e Image 39 is f Image 40 is t Image 41 is , Image 42 is   Image 43 is K Image 44 is a Image 45 is r Image 46 is e Image 47 is n Image 48 is , Image 49 is   Image 50 is a Image 51 is n Image 52 is   Image 53 is o Image 54 is l Image 55 is d Image 56 is e Image 57 is r Image 58 is   Image 59 is w Image 60 is h Image 61 is i Image 62 is t Image 63 is e Image 64 is   Image 65 is w Image 66 is o Image 67 is m Image 68 is a Image 69 is n Image 70 is , Image 71 is   Image 72 is s Image 73 is m Image 74 is i Image 75 is l Image 76 is e Image 77 is s Image 78 is   Image 79 is a Image 80 is t Image 81 is   Image 82 is t Image 83 is h Image 84 is e Image 85 is   Image 86 is c Image 87 is a Image 88 is m Image 89 is e Image 90 is r Image 91 is a Image 92 is   Image 93 is w Image 94 is h Image 95 is i Image 96 is l Image 97 is e Image 98 is   Image 99 is h Image 100 is o Image 101 is l Image 102 is d Image 103 is i Image 104 is n Image 105 is g Image 106 is   Image 107 is a Image 108 is   Image 109 is s Image 110 is t Image 111 is e Image 112 is a Image 113 is m Image 114 is   Image 115 is p Image 116 is r Image 117 is e Image 118 is s Image 119 is s Image 120 is   Image 121 is p Image 122 is r Image 123 is i Image 124 is n Image 125 is t Image 126 is   Image 127 is o Image 128 is f Image 129 is   Image 130 is l Image 131 is e Image 132 is a Image 133 is v Image 134 is e Image 135 is s Image 136 is ; Image 137 is   Image 138 is r Image 139 is o Image 140 is w Image 141 is s Image 142 is   Image 143 is o Image 144 is f Image 145 is   Image 146 is f Image 147 is r Image 148 is a Image 149 is g Image 150 is r Image 151 is a Image 152 is n Image 153 is c Image 154 is e Image 155 is - Image 156 is f Image 157 is r Image 158 is e Image 159 is e Image 160 is   Image 161 is g Image 162 is o Image 163 is a Image 164 is t Image 165 is   Image 166 is m Image 167 is i Image 168 is l Image 169 is k Image 170 is   Image 171 is s Image 172 is o Image 173 is a Image 174 is p Image 175 is ; Image 176 is   Image 177 is K Image 178 is a Image 179 is r Image 180 is e Image 181 is n Image 182 is   Image 183 is s Image 184 is i Image 185 is t Image 186 is s Image 187 is   Image 188 is i Image 189 is n Image 190 is   Image 191 is a Image 192 is   Image 193 is g Image 194 is r Image 195 is e Image 196 is e Image 197 is n Image 198 is h Image 199 is o Image 200 is u Image 201 is s Image 202 is e Image 203 is   Image 204 is h Image 205 is o Image 206 is l Image 207 is d Image 208 is i Image 209 is n Image 210 is g Image 211 is   Image 212 is a Image 213 is   Image 214 is s Image 215 is q Image 216 is u Image 217 is a Image 218 is s Image 219 is h Image 220 is   Image 221 is a Image 222 is n Image 223 is d Image 224 is   Image 225 is g Image 226 is r Image 227 is i Image 228 is n Image 229 is s Image 230 is   Image 231 is w Image 232 is i Image 233 is d Image 234 is e Image 235 is l Image 236 is y Image 237 is ; Image 238 is   Image 239 is b Image 240 is a Image 241 is g Image 242 is s Image 243 is   Image 244 is o Image 245 is f Image 246 is   Image 247 is d Image 248 is a Image 249 is r Image 250 is k Image 251 is   Image 252 is c Image 253 is h Image 254 is o Image 255 is c Image 256 is o Image 257 is l Image 258 is a Image 259 is t Image 260 is e Image 261 is   Image 262 is p Image 263 is e Image 264 is c Image 265 is a Image 266 is n Image 267 is   Image 268 is t Image 269 is o Image 270 is f Image 271 is f Image 272 is e Image 273 is e Image 274 is   Image 275 is a Image 276 is n Image 277 is d Image 278 is   Image 279 is c Image 280 is r Image 281 is i Image 282 is s Image 283 is p Image 284 is y Image 285 is   Image 286 is m Image 287 is o Image 288 is l Image 289 is a Image 290 is s Image 291 is s Image 292 is e Image 293 is s Image 294 is   Image 295 is c Image 296 is r Image 297 is i Image 298 is s Image 299 is p Image 300 is s Image 301 is   Image 302 is o Image 303 is n Image 304 is   Image 305 is a Image 306 is   Image 307 is t Image 308 is a Image 309 is b Image 310 is l Image 311 is e Image 312 is . +
    + +

    Karen Biondo

    +
    + +

    I am a farmer, chef, creator. I make fun, delicious and sometimes useful items from what inspires me in the world around me.

    + + + + + +
    +
  • + +
  • + +
    + undefined Image 1 is a triptych of photos of the artist wearing jackets of her own creation. the first jacket is orange and teal wool with a stag graphic appliqued onto the back panel. the second jacket is a woody green leather jacket with fur collar accent, snap epaulettes, and a front lapel detail created from colorful angular leather scraps. the third is a white denim jacket with a central linocut patch stitched in place with intricate topwork and embroidery. pink silk accents, flower details, and direct print work frame the central piece. +
    + +

    Brooke Osment

    +
    + +

    found art jackets, stitchwork, visible mending

    + + + + + +
    +
  • + +
  • + +
    + undefined Image 1 is a 3 picture collage. the first shows a miniature dress with white lace, pink bows and rosettes, and tiny maple leaves. the second shows mags, the artist, a white person with shaggy green hair, smiling slightly. third shows a natural-art sculpture with tiny mushroom figures added to real wood and lichen. +
    + +

    Mags (Mary) McGinnis

    +
    + +

    Eclectic creator working with natural materials and found objects.

    + + + + + +
    +
  • + +
  • + +
    + undefined Image 1 is Bag of ZenBellies coffee on the counter in front of a coffee station. +
    + +

    Gary of Zenbellies Coffee Co.

    +
    + +

    I will be serving up delicious pour-overs of my hand-picked locally roasted coffee, honoring the rich flavor tradition of the Pacific Northwest.

    + + + + + +
    +
  • + +
  • + +
    + undefined Image 1 is 2 image collage showing a cast concrete votive candle holder with candle, and a bottle of a tincture made from foraged red belted conk and artist conk mushrooms. +
    + +

    Jon Haaland

    +
    + +

    Jon Haaland is a mixed media artist, photographer and designer hailing from the Pacific Northwest. With an innate passion for blending mediums and exploring the interplay between man and nature, Jon draws his inspiration from the intrinsic harmony of nature and the pressures of man. Through his mixed media creations, he intertwines natural elements constructing a unique narrative that speaks to the deep interplay between civilization and the environment.

    + + + + + +
    +
  • + +
  • + +
    + undefined Image 1 is a 3 picture collage. 2 pictures show the case and cards of a tarot deck created by Rachel. The third shows Rachel, a white person with turquoise hair, cat eye glasses, and contrasting striped jacket and dress, standing in front of paintings of shorelines. +
    + +

    Rachel Guinevere LordKenaga

    +
    + +

    I am an artist and art therapist living on Vashon. I'm most interested in evoking feelings and memory with my work. I will have my handmade Tarot deck and small oil paintings. I'll offer 1 card pulls for $20.

    + + + + + +
    +
  • + +
  • + +
    + undefined Image 1 is a four picture collage. two pictures show lee, a white person with curly hair and glasses; in one picture, wearing a colorful knit shawl. the other two frames show lee's work. 1, two leather card wallets with an elegant swoop on the back in vivid colors of leather; 2, a pile of greeting cards with a block-printed loon spread across front and back of the cards. +
    + +

    Lee Cattarin

    +
    + +

    multidisciplinary artist and birder

    + + + + + +
    +
  • + +
+ + + +
+
+ + + + + + diff --git a/_live/events/2026-imbolc/index.html b/_live/events/2026-imbolc/index.html new file mode 100644 index 0000000..d74bf08 --- /dev/null +++ b/_live/events/2026-imbolc/index.html @@ -0,0 +1,976 @@ + + + + + + + Imbolc 2026 Celebration and Market at the Beall Greenhouses | the historic Beall Greenhouses + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+ + +
+ +

Imbolc 2026 Celebration and Market at the Beall Greenhouses

+ + +
+
+

Join us to celebrate the returning of the light on + .

+

Find us in studios in the former cold storage facility at the old Beall Greenhouses — + 18527 Beall Rd SW, Vashon, WA 98070 + — as well as Quartermaster Press, located directly back from the same parking lot. +

+

There will be a workshop on making your own Brigid's Cross, a traditional symbol of Imbolc, led by + Katt Rouse-Riley. +

+

Hot mulled cider (non-alcoholic) will be served. We'll also have a coffee vendor, + Gary of Zenbellies Coffee Co.

+
+ + a black and white flyer for the Imbolc event that reads: Imbolc Celebration and Market at the Beall Greenhouses. Crafting and art, open studios. It then lists the address, time, and website. The text is overlaid on a darkened image of a dilapidated greenhouse, and the site's hummingbird logo is inset. +
+ +

Artists and vendors

+ + + + +
    + +
  • + +
    + undefined Image 1 is Bag of ZenBellies coffee on the counter in front of a coffee station. +
    + +

    Gary of Zenbellies Coffee Co.

    +
    + +

    I will be serving up delicious pour-overs of my hand-picked locally roasted coffee, honoring the rich flavor tradition of the Pacific Northwest.

    + + + + + +
    +
  • + +
  • + +
    + undefined Image 1 is a four picture collage. two pictures show lee, a white person with curly hair and glasses; in one picture, wearing a colorful knit shawl. the other two frames show lee's work. 1, two leather card wallets with an elegant swoop on the back in vivid colors of leather; 2, a pile of greeting cards with a block-printed loon spread across front and back of the cards. +
    + +

    Lee Cattarin

    +
    + +

    multidisciplinary artist and birder

    + + + + + +
    +
  • + +
  • + +
    + a 2 picture collage. Image 1 is A young woman standing in the trees with blue hair, red glasses, and a rainbow shirt. She is looking very thoughtful. Image 2 is A hand holding a three point weaving of green reeds against an old red building +
    + +

    Katt Rouse-Riley

    +
    + +

    Katt Rouse-Riley hails from Arizona and developed her eclectic tastes from growing up all over the US, finally landing on Vashon Island with her family in 2012. Katt has had the chance to study religions of many forms, becoming what she would recognize to be Wicca 33 years ago. She is a Priestess that has performed marriages and found an affinity to using nature in her practice and art. She has led some Earth Art classes, and looks forward to doing so again.

    + +

    Katt will have materials on hand to make your own Brigid's cross!

    + +

    Come learn a little bit about Imbolc, the Goddess Brigid, and take home this beautiful symbol crafted by your own hands.

    + + + + + +
    +
  • + +
  • + +
    + a 5 picture collage. Image 1 is Photogravure print of a sunflower with watercolor. Image 2 is Linocut print of coffee cups on a table, with the words good trouble shown on the wall above. Image 3 is Fused glass garden art, a light filtering rectangle composed of multicolored blue and yellow stripes. Image 4 is Red ornamented fused glass sushi plate with two matching condiment plates. Image 5 is Mint green fused glass shallow bowl with dotted ornament. +
    + +

    Rachael Osborn

    +
    + +

    Rachael will be selling hand-pulled prints and glasswork at the Quartermaster Press Studio at Beall Greenhouses.

    + + + + + +
    +
  • + +
  • + +
    + a 3 picture collage. Image 1 is A small piece of wood covered in dried lichen and moss, with what appears to be glass like white mushrooms. The stems of the mushrooms are created over wire fairy lights. When lit, the caps emit a warm magical light. Sculpture embellished with locally gathered acorns and eucalyptus seeds. Image 2 is An older white person with long green and light brown hair and bangs. They are looking looking sideways with a slight smile. Image 3 is This golden yellow satin dress is mounted on a wooden base and dress form that lights from inside. Constructed from several dresses and embellished with vintage hand dyed ribbon and mulberry paper leaves in different shades of green. The bodice is fitted in trimmed in ribbon. The skirt is filled out with a handmade crinoline under skirt. Excluding the wings made of skeletonized leaves, this fantasy dress on the stand is about 12 inches tall. +
    + +

    Mags McGinnis

    +
    + +

    I've been collecting bits and bobs and tiny shiny things for many years. I make small odd little things out of found objects, embellished with things from my collection. This market I will also be offering bathing salts (pre-made or mix your own) in the spirit of Imbolc and spring cleaning.

    + + + + + +
    +
  • + +
  • + +
    + a 5 picture collage. Image 1 is moon jellyfish on dark background. Image 2 is Spruce trees in mist. Image 3 is Opalescent nudibranch. Image 4 is Salmon troller in front of alaskan volcano. Image 5 is Underwater photo of bull kelp. +
    + +

    Logan Price Photography

    +
    + +

    Unique underwater photographs of local northwest sea creatures taken while freediving, and stunning large format land-and-seascapes from Southeast Alaska.

    + + + + + +
    +
  • + +
  • + +
    + a 2 picture collage. Image 1 is Cast from concrete and shaped by intention, these votive candle holders evoke post-industrial rubble, as if salvaged from the ruins of a failed civilization. Their fractured forms and raw textures suggest remnants of structures once built for permanence, now repurposed to hold light. Each piece bears subtle fire-kissed colorations, with scorched tones and darkened edges that hint at having endured extreme heat. Traces of rust emerge like archaeological evidence, reinforcing the sense of age, collapse, and survival. Together, they transform ruin into ritual, offering a quiet promise of illumination and renewal. Image 2 is Mithran is a small-batch, dual-extracted mushroom tonic made from foraged Red Belted Conk (Fomitopsis pinicola) and Artist’s Conk (Ganoderma applanatum). Using both alcohol and water extraction, it captures a wide range of traditionally valued compounds, including polysaccharides, triterpenes, phenolics, and bitter terpenoids. Mithran has a long history of folk use for supporting inflammation balance, immune function, digestion, and liver health. Research on these conks shows antioxidant activity and alcohol-soluble compounds with activity against cancer cells and tumor growth in laboratory settings. +
    + +

    Jon Haaland

    +
    + +

    Jon Haaland is a mixed media artist, photographer and designer hailing from the Pacific Northwest. With an innate passion for blending mediums and exploring the interplay between man and nature, Jon draws his inspiration from the intrinsic harmony of nature and the pressures of man. Through his mixed media creations, he intertwines natural elements constructing a unique narrative that speaks to the deep interplay between civilization and the environment.

    + + + + + +
    +
  • + +
  • + +
    + a 5 picture collage. Image 1 is A woman smiling in front of a backdrop while holding her red glasses Image 2 is A man in a suit with microphone in front of a las vegas backdrop Image 3 is A smiling woman in a blue business suit Image 4 is A young woman in a hat sweater wearing pink pastel goth style Image 5 is A young man holding a guitar in front of several road cases +
    + +

    Steve Rocketkar

    +
    + +

    Steve Rocketkar is a journalist turned designer turned photographer living and working on Vashon Island. His photo and video practice, Rocketkar Studios, seeks to help each person be seen the way they want to be seen. This market he'll be offering headshot mini photo sessions for the new year, as well as in-person specials on Valentine's Day couples' sessions.

    + + + + + +
    +
  • + +
  • + +
    + undefined Image 1 is 3 picture collage of a white brunette woman. in picture one, she sits on a tall stool with her leg pulled up, holding paintbrushes. in picture 2 she stares at the camera with chanterelles held up to her ears. picture 3, she aims a camera at the camera. +
    + +

    Hope Black

    +
    + +

    Hope Black is a conceptual portrait photographer and multi-media artist based on Vashon Island, WA. Her work blends fine-art portraiture with macabre photo editing, and she draws on mixed-media illustrations, varied textures, and found-objects to create portraits and paintings that feel symbolic and dream-like. Her images echo the archetypes found in the tarot and the emotional undercurrents of womanhood -- inviting viewers into a world that is both haunting and deeply human.

    + + + + + +
    +
  • + +
  • + +
    + a 5 picture collage. Image 1 is A green feather emerging from cracked earth, curled in a spiral. Image 2 is Two crane figures with their beaks meeting in the middle where a large circle is suspended in the air. The sky behind it is stormy and full of clouds. The hill they are standing on has a large crack running down the center, with ancient carved stone animal heads around the crack. Image 3 is A vintage map of the Bremerton area. Super imposed throughout the map is a sacred geometry pattern called the Flower of Life. A red Octopus is emerging from the pattern. Image 4 is A bear curled up in a ball with its paw over its eyes. The ground is covered in snow and there are bird tracks in between stones poking out. In the sky above, there is a comet amongst the stars. Image 5 is A vintage map of the Bremerton area. Super imposed throughout the map is a sacred geometry pattern called the Flower of Life. A Dungeness crab is emerging from the pattern. +
    + +

    Jennifer Hawke

    +
    + +

    Jennifer Hawke came to Vashon Island about 20 years ago from Billings, Montana.

    + +

    Hawke has a studio at the Beall Greenhouses, and has participated in the Vashon Studio Tour for the last four seasons. They also paint large Sacred Geometry installations on the road during the First Friday Art Walks in the summer months.

    + +

    Hawke has a degree in Painting and Cast Metals from Montana State University, but they work in many different mediums. Their primary studio work is assemblage using vintage detritus and beach trash.

    + +

    You may also know Hawke through the Bearded Lady Road Reports, a live broadcast on Facebook dedicated to reporting on road conditions during inclement weather.

    + + + + + +
    +
  • + +
  • + +
    + a 2 picture collage. Image 1 is Hand spun yard in beautiful spring hues, marled. Image 2 is knitting made from hand spun yarn. +
    + +

    Julie Shannon

    +
    + +

    Hand-dyed and hand-spun yarns, rustic soaps, spa cloths, and Julie's Amazing Sweet 'n Sassy Nuts.

    + + + + + +
    +
  • + +
  • + +
    + a 5 picture collage. Image 1 is “Paradise Dreams” Egret by the ocean under a tree. Collagraph. Image 2 is “Chachalaca Morning” Chachalaca bird sitting on a tree branch.  Collagraph. Image 3 is “Winter’s Flock” Bare trees in a field with crows flying. Collagraph. Image 4 is “The Meeting” A crow and doves are having a meeting at an old oak tree. Etching. Image 5 is “Misty Mourning” Bare trees with morning sun and autumn leaves on the ground. Monotype. +
    + +

    Christina Nichols

    +
    + +

    I have been a professional artist for 40 years, living on Vashon Island in the Pacific Northwest.

    + +

    My work is mostly inspired by nature. I also like to mix modern and ancient sources in an attempt to elicit images of the collective unconscious.

    + +

    I currently like to use many hand-pulled printing processes, for example—etchings, collagraphs, monoprints and linoleum block prints. I have been a member of Quartermaster Press at Beall Greenhouses since 2011.

    + + + + + +
    +
  • + +
  • + +
    + undefined Image 1 is a triptych of photos of the artist wearing jackets of her own creation. the first jacket is orange and teal wool with a stag graphic appliqued onto the back panel. the second jacket is a woody green leather jacket with fur collar accent, snap epaulettes, and a front lapel detail created from colorful angular leather scraps. the third is a white denim jacket with a central linocut patch stitched in place with intricate topwork and embroidery. pink silk accents, flower details, and direct print work frame the central piece. +
    + +

    Brooke Osment

    +
    + +

    found art jackets, stitchwork, visible mending

    + + + + + +
    +
  • + +
+ + + +
+
+ + + + + + diff --git a/_live/events/index.html b/_live/events/index.html new file mode 100644 index 0000000..41edbf4 --- /dev/null +++ b/_live/events/index.html @@ -0,0 +1,509 @@ + + + + + + + Events at the Beall Greenhouses | the historic Beall Greenhouses + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+ + +
+ +

Events at the Beall Greenhouses

+ + + + + +
    + +
  1. + +

    2026 Imbolc

    + + part of the Imbolc 2026 market flyer. in the background, a greenhouse in black and white; in the foreground, text reading Celebration and Market at the Beall Greenhouses; Crafting and Art; Open Studios. inset in the lower left is the top of the site's logo, a hummingbird in flight. + +
    +
  2. + +
  3. + +

    2025 Solstice

    + + group photo of all eight artists of the Solstice 2025 market. + +
    +
  4. + +
+ + + +
+
+ + + + + + diff --git a/_live/favicon.ico b/_live/favicon.ico new file mode 100755 index 0000000..76efaa7 Binary files /dev/null and b/_live/favicon.ico differ diff --git a/_live/greenhouse.jpg b/_live/greenhouse.jpg new file mode 100755 index 0000000..a9ca78f Binary files /dev/null and b/_live/greenhouse.jpg differ diff --git a/_live/index.html b/_live/index.html new file mode 100644 index 0000000..5a33102 --- /dev/null +++ b/_live/index.html @@ -0,0 +1,489 @@ + + + + + + + The Beall Greenhouses | the historic Beall Greenhouses + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+ + +
+ +

The Beall Greenhouses

+ + + + + + + +

Imbolc creates community

+

Our Imbolc + Celebration & Market was fantastic. + Visitors could learn to make a Brigid's Cross, and dog photographs meant + an abundance of furry friends.

+ +

A successful Solstice

+

Our inaugural Solstice Market was a rousing + success.

+ +
+
+ + +
+
+ + + + + + diff --git a/_live/palette/index.html b/_live/palette/index.html new file mode 100644 index 0000000..f480340 --- /dev/null +++ b/_live/palette/index.html @@ -0,0 +1,465 @@ + + + + + + + Site palette | the historic Beall Greenhouses + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+ + +
+ +

Site palette

+ + + +
+

#e5e0c7

+

#d1cbab

+

#142b15

+

#1a3b1b

+

#4ba19e

+

#0c6a74

+
+ + +
+
+ + + + + + diff --git a/css/artist-market.css b/css/artist-market.css new file mode 100644 index 0000000..8dc7e8d --- /dev/null +++ b/css/artist-market.css @@ -0,0 +1,96 @@ +.artist { + width: 100%; + margin: 2rem 0; + display: grid; + scroll-margin-top: 1rem; +} + +.artist:nth-child(odd) { + grid-template: + 'imgs h3' + 'imgs desc' + 'imgs .'; + grid-template-columns: 45% auto; +} + +.artist:nth-child(even) { + grid-template: + 'h3 imgs' + 'desc imgs' + '. imgs'; + grid-template-columns: auto 45%; +} + +@media (max-width: 950px) { + .artist:nth-child(n) { + grid-template: + 'imgs' + 'h3' + 'desc'; + } +} + +.fit-contain { + object-fit: contain; + grid-area: imgs; +} + +.artist img { + max-height: 100%; + max-width: 100%; + border-radius: 1rem; +} + +@media (max-width: 950px) { + .artist img { + border-radius: 1rem 1rem 0 0; + border-bottom: .25rem solid var(--color-accent); + } +} + +.artist h3 { + grid-area: h3; + text-transform: uppercase; + line-height: 2rem; +} + +.artist:nth-child(odd) h3 { + padding-left: .5rem; +} + +.artist:nth-child(even) h3 { + padding-right: .5rem; + text-align: right; +} + +@media (max-width: 1050px) { + .artist:nth-child(n) h3 { + padding: 0; + } +} + +.description { + grid-area: desc; + background-color: var(--color-bg-alt); + border-radius: 0 0 1rem 1rem; +} + +.artist:nth-child(odd) .description { + margin-left: 1.75rem; +} + +.artist:nth-child(even) .description { + margin-right: 1.75rem; +} + +@media (max-width: 950px) { + .artist:nth-child(odd) .description, + .artist:nth-child(even) .description { + margin: 0; + } +} + +.description p:last-child { + text-align: center; + padding-bottom: 1rem; +} diff --git a/css/artist-resident.css b/css/artist-resident.css new file mode 100644 index 0000000..033083c --- /dev/null +++ b/css/artist-resident.css @@ -0,0 +1,101 @@ +.topic { + margin: 4rem auto; + display: grid; +} + +.topic:nth-child(odd) { + grid-template: + 'img h' + 'img desc' + 'img .'; + grid-template-columns: 45% auto; +} + +.topic:nth-child(even) { + grid-template: + 'h img' + 'desc img' + '. img'; + grid-template-columns: auto 45%; +} + +@media (max-width: 950px) { + .topic:nth-child(odd), + .topic:nth-child(even) { + grid-template: + 'img' + 'h' + 'desc'; + } +} + +.topic img { + grid-area: img; + border-radius: 1rem; +} + +@media (max-width: 950px) { + .topic img { + border-radius: 1rem 1rem 0 0; + border-bottom: .25rem solid var(--color-accent); + } +} + +.topic h1, +.topic h2 { + margin: 0; + grid-area: h; + border-bottom: .25rem solid var(--color-accent); + padding: .25rem; +} + +.topic:nth-child(odd) h2 { + padding-left: .75rem; +} + +.topic:nth-child(even) h2 { + text-align: right; + padding-right: .75rem; +} + +@media (max-width: 950px) { + .topic:nth-child(odd) h2, + .topic:nth-child(even) h2 { + padding: .25rem 0; + } +} + +.topic .desc { + grid-area: desc; + background-color: var(--color-bg-alt); + border-radius: 0 0 1rem 1rem; +} + +.topic:nth-child(odd) .desc { + margin-left: 1.5rem; +} + +.topic:nth-child(even) .desc { + margin-right: 1.5rem; +} + +@media (max-width: 950px) { + .topic:nth-child(odd) .desc, + .topic:nth-child(even) .desc { + margin: 0; + } +} + +.contact ul { + background-color: var(--color-bg-alt); + border-radius: 0 0 1rem 1rem; +} + +.contact { + margin-top: 4rem; + text-align: center; +} + +.contact li { + list-style: none; +} diff --git a/css/directory.css b/css/directory.css new file mode 100644 index 0000000..93e96d1 --- /dev/null +++ b/css/directory.css @@ -0,0 +1,61 @@ +#directory { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 3rem; + margin: 0 .5rem; +} + +@media (max-width: 1050px) { + #directory { + grid-template-columns: 1fr; + } +} + +ul#directory, +ol#directory { + background-color: var(--color-bg); + padding: 0; +} + +#directory li { + list-style: none; + border: solid .25rem var(--color-accent); + border-radius: .75rem; + outline-offset: .25rem; + margin: 0; + padding: 0; +} + +@media (any-hover: hover) { + #directory li:hover { + background-color: var(--color-text); + } + + #directory li:hover h2 { + color: var(--color-bg); + border-color: var(--color-accent-flipped); + } +} + +#directory li:focus-within { + outline: solid .25rem var(--color-accent); +} + +#directory a { + text-decoration: none; + margin: 0; +} + +#directory a:focus-visible { + outline: none; /* outline handled by li:focus-within */ +} + +#directory h2 { + text-align: center; + margin-top: 1rem; +} + +#directory img { + margin: 0; + border-radius: 0 0 .5rem .5rem; +} diff --git a/css/main.css b/css/main.css new file mode 100644 index 0000000..126a149 --- /dev/null +++ b/css/main.css @@ -0,0 +1,179 @@ +:root { + color-scheme: light dark; + + --color-concrete: #e5e0c7; + --color-concrete-alt: #d1cbab; + --color-green: #142b15; + --color-green-alt: #1a3b1b; + --color-teal-light: #4ba19e; + --color-teal-dark: #0c6a74; + + --color-bg: light-dark(var(--color-concrete), var(--color-green)); + --color-text: light-dark(var(--color-green), var(--color-concrete)); + --color-bg-alt: light-dark(var(--color-concrete-alt), var(--color-green-alt)); + --color-text-alt: light-dark(var(--color-green-alt), var(--color-concrete-alt)); + --color-accent: light-dark(var(--color-teal-dark), var(--color-teal-light)); + --color-accent-flipped: light-dark(var(--color-teal-light), var(--color-teal-dark)); +} + +* { + box-sizing: border-box; + margin: 0; + padding: 0; +} + +body { + background-color: var(--color-text); + color: var(--color-bg); + display: flex; + flex-direction: column; + font-family: Arial, Helvetica, sans-serif; + min-height: 100vh; +} + +#content { + background-color: var(--color-bg); + color: var(--color-text); + width: 100%; + flex-grow: 1; + border-radius: 0 0 2rem 2rem; + padding: 1rem 0 2rem; +} + +@media (prefers-color-scheme: light) { + .dark-mode { + display: none; + } +} + +@media (prefers-color-scheme: dark) { + .light-mode { + display: none; + } +} + +header, +main { + width: 65%; + margin: 0 auto 1rem; +} + +@media (max-width: 750px) { + header, + main { + width: 92%; + } +} + +@media (min-width: 2000px) { + header, + main { + width: 45%; + } +} + +img { + display: block; + max-width: 100%; + height: auto; +} + +h1, h2, h3, h4, h5, h6 { + color: var(--color-text-alt); +} + +h1, +h2 { + font-family: 'Bellota', Arial, Helvetica, sans-serif; +} + +h1 { + text-align: center; + margin: 2rem 0; + font-size: 2.2rem; +} + +h2 { + margin: 2rem 0 0; + font-size: 1.65rem; +} + +h2, +h3 { + border-bottom: .25rem solid var(--color-accent); +} + +a { + color: var(--color-text); + font-weight: bold; + text-decoration: underline; + text-decoration-style: solid; + text-decoration-thickness: .25rem; + text-decoration-color: var(--color-accent); + transition: text-decoration-thickness .5s; + border-radius: .1rem; + outline-offset: .1rem; +} + +a:hover, +a:active { + text-decoration-thickness: .5rem; +} + +a:focus-visible { + text-decoration: none; + outline: solid .25rem var(--color-accent); +} + +main p, +main ul { + padding: .8rem; + line-height: 1.5rem; +} + +main li { + margin-left: 1rem; +} + +main li:not(:last-child) { + padding: 0 0 .5rem; +} + +/* styles for sets of

s under an h2/3/etc vs alone +this is done as a class rather than just h2 + p to accomodate +for multi-

segments which can then be wrapped in

s */ +.under-header, +.no-header { + background-color: var(--color-bg-alt); +} + +.under-header { + border-radius: 0 0 1rem 1rem; + margin-left: 2.5rem; +} + +@media (max-width: 750px) { + .under-header { + margin-left: 1.25rem; + } +} + +.no-header { + border-radius: 1rem; +} + +.two-col { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 1rem; +} + +.two-col > * { + place-self: start center; +} + +@media (max-width: 950px) { + .two-col { + grid-template-columns: 1fr; + } +} diff --git a/css/ml-embed.css b/css/ml-embed.css new file mode 100644 index 0000000..7c57b8c --- /dev/null +++ b/css/ml-embed.css @@ -0,0 +1,41 @@ +.ml-embedded { + margin: 4rem auto 2rem; + border-top: .25rem solid var(--color-accent); +} + +.ml-embedded p { + padding: 0; +} + +.ml-form-embedWrapper { + border-top-left-radius: 0 !important; + border-top-right-radius: 0 !important; +} + +.ml-form-embedContent h4 { + font-family: 'Bellota', Arial, Helvetica, sans-serif !important; +} + +#mlb2-37153427.ml-form-embedContainer .ml-form-embedWrapper .ml-form-embedBody .ml-form-fieldRow input:hover, +#mlb2-37153313.ml-form-embedContainer .ml-form-embedWrapper .ml-form-embedBody .ml-form-fieldRow input:hover { + border-color: var(--color-accent-flipped); + outline-offset: 0; + outline: .25rem solid var(--color-accent); +} + +#mlb2-37153427.ml-form-embedContainer .ml-form-embedWrapper .ml-form-embedBody .ml-form-fieldRow input:focus-visible, +#mlb2-37153313.ml-form-embedContainer .ml-form-embedWrapper .ml-form-embedBody .ml-form-fieldRow input:focus-visible { + outline-offset: .25rem; + outline: solid .25rem var(--color-accent); +} + +#mlb2-37153427.ml-form-embedContainer .ml-form-embedWrapper .ml-form-embedBody .ml-form-embedSubmit button:hover, +#mlb2-37153313.ml-form-embedContainer .ml-form-embedWrapper .ml-form-embedBody .ml-form-embedSubmit button:hover { + color: var(--color-text) !important; +} + +#mlb2-37153427.ml-form-embedContainer .ml-form-embedWrapper .ml-form-embedBody .ml-form-embedSubmit button:focus-visible, +#mlb2-37153313.ml-form-embedContainer .ml-form-embedWrapper .ml-form-embedBody .ml-form-embedSubmit button:focus-visible { + outline-offset: .25rem; + outline: solid .25rem var(--color-accent); +} diff --git a/css/nav.css b/css/nav.css new file mode 100644 index 0000000..64a37f9 --- /dev/null +++ b/css/nav.css @@ -0,0 +1,149 @@ +/* top nav */ +nav { + position: relative; + margin: 0 auto 1.5rem; + display: grid; + grid-template: "logo nav"; + grid-template-rows: 7rem; + grid-template-columns: 7rem auto; + background-image: url("/greenhouse.jpg"); + background-size: cover; + background-repeat: no-repeat; + border-radius: 2rem .25rem .25rem 2rem; +} + +nav a { + margin: 0; +} + +nav a:not(:has(img)) { + display: inline-block; + text-decoration: none; + font-size: 1.2rem; + padding: 0 .25rem; + border: solid .125rem var(--color-accent); + border-radius: .25rem; + background-color: var(--color-bg); +} + +@media (any-hover: hover) { + nav a:not(:has(img)):hover { + color: var(--color-bg); + background-color: var(--color-text-alt); + border-color: var(--color-accent-flipped); + outline: .125rem solid var(--color-accent); + outline-offset: 0; + } +} + +nav a:not(:has(img)):focus-visible { + outline: solid .125rem var(--color-accent); + outline-offset: .125rem; +} + +#skip { + left: -999px; + position: absolute; + top: auto; + width: 1px; + height: 1px; + overflow: hidden; + z-index: -99; +} + +#skip:focus-visible { + left: -6rem; + width: auto; + height: auto; + overflow: auto; + z-index: 999; +} + +@media (max-width: 750px) { + #skip:focus-visible { + left: 5rem; + } +} + +nav img { + max-height: 100%; + margin: 0; + border-radius: 2rem; + border: .2rem solid var(--color-accent); +} + +@media (any-hover: hover) { + nav img:hover { + border-color: var(--color-accent-flipped); + outline-offset: 0; + outline: .2rem solid var(--color-accent); + } +} + +nav a:has(img) { + grid-area: logo; + justify-self: start; +} + +nav a:has(img):focus-visible { + border-radius: 2rem; + outline-offset: .2rem; + outline: .2rem solid var(--color-accent); +} + +nav a:has(img):focus-visible img { + outline: none; +} + +nav ul { + grid-area: nav; + display: flex; + justify-content: space-between; + align-items: flex-end; + flex-flow: column nowrap; +} + +nav li { + list-style: none; +} + +/* footer */ +footer { + width: 95%; + margin: 0 auto; + padding: 1rem 0; + display: flex; + justify-content: center; +} + +@media (max-width: 750px) { + footer { + flex-flow: column; + } +} + +footer p { + background-color: var(--color-text); + color: var(--color-bg); + text-align: center; + font-size: .9rem; + padding: .25rem; +} + +@media (min-width: 751px) { + footer p:nth-child(2)::before { + content: "● " / ""; + } + footer p:nth-child(2)::after { + content: " ●" / ""; + } +} + +footer a { + color: var(--color-bg); + text-decoration-color: var(--color-accent-flipped); +} + +footer a:focus-visible { + outline-color: var(--color-accent-flipped); +} diff --git a/css/palette.css b/css/palette.css new file mode 100644 index 0000000..e702aab --- /dev/null +++ b/css/palette.css @@ -0,0 +1,33 @@ +.color p { + width: 50%; + margin: 1rem auto; + border: .25rem solid var(--color-text); + border-radius: 1rem; + text-align: center; + font-weight: bold; +} + +@media (max-width: 550px) { + .color p { + width: 100%; + } +} + +#concrete { background-color: var(--color-concrete); } +#concrete-alt { background-color: var(--color-concrete-alt); } +#green { background-color: var(--color-green); } +#green-alt { background-color: var(--color-green-alt); } +#teal-light {background-color: var(--color-teal-light); } +#teal-dark { background-color: var(--color-teal-dark); } + +#concrete, +#concrete-alt, +#teal-light { + color: var(--color-green); +} + +#green, +#green-alt, +#teal-dark { + color: var(--color-concrete); +} diff --git a/eleventy.config.js b/eleventy.config.js new file mode 100644 index 0000000..af6d648 --- /dev/null +++ b/eleventy.config.js @@ -0,0 +1,72 @@ +import { attrs } from "@mdit/plugin-attrs"; +import { eleventyImageTransformPlugin } from "@11ty/eleventy-img"; +import eleventyNavigationPlugin from "@11ty/eleventy-navigation"; + +import pluginFilters from "./_config/filters.js"; + +export default async function(eleventyConfig) { + /* Markdown HTML attribute parsing */ + eleventyConfig.amendLibrary("md", (mdLib) => mdLib.use(attrs)); + + /* Bundles */ + /* CSS */ + eleventyConfig.addBundle("css", { + toFileDirectory: "dist", + bundleHtmlContentFromSelector: "style", + }); + + /* Javascript */ + eleventyConfig.addBundle("js", { + toFileDirectory: "dist", + bundleHtmlContentFromSelector: "script", + }); + + /* Passthroughs */ + eleventyConfig + .addPassthroughCopy("./greenhouse.jpg") + .addPassthroughCopy("./favicon.ico"); + + /* Images */ + eleventyConfig.addPlugin(eleventyImageTransformPlugin, { + // output image formats + formats: ["auto"], + + // output image widths + widths: ["auto"], + + // optional, attributes assigned on nodes override these values + htmlOptions: { + imgAttributes: { + loading: "lazy", + decoding: "async", + }, + }, + }); + + /* Navigation */ + eleventyConfig.addPlugin(eleventyNavigationPlugin); + + /* All filters from _config/filters.js */ + eleventyConfig.addPlugin(pluginFilters); + + + /* Shortcodes */ + eleventyConfig.addShortcode("currentBuildDate", () => { + return (new Date()).toISOString(); + }); + + /* Watch when serving */ + eleventyConfig.addWatchTarget("css"); +} + +export const config = { + dir: { + input: "src", + includes: "../_includes", + layouts: "../_includes/layouts", + data: "../_data" + }, + markdownTemplateEngine: "njk", + htmlTemplateEngine: "njk", + templateFormats: ["html", "md", "njk"], +}; diff --git a/favicon.ico b/favicon.ico new file mode 100755 index 0000000..76efaa7 Binary files /dev/null and b/favicon.ico differ diff --git a/greenhouse.jpg b/greenhouse.jpg new file mode 100755 index 0000000..a9ca78f Binary files /dev/null and b/greenhouse.jpg differ 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/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/image-size b/node_modules/.bin/image-size new file mode 120000 index 0000000..f575317 --- /dev/null +++ b/node_modules/.bin/image-size @@ -0,0 +1 @@ +../image-size/bin/image-size.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/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/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/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..600198e --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,2018 @@ +{ + "name": "beall-eleventy", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@11ty/dependency-tree": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@11ty/dependency-tree/-/dependency-tree-4.0.2.tgz", + "integrity": "sha512-RTF6VTZHatYf7fSZBUN3RKwiUeJh5dhWV61gDPrHhQF2/gzruAkYz8yXuvGLx3w3ZBKreGrR+MfYpSVkdbdbLA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@11ty/eleventy-utils": "^2.0.1" + } + }, + "node_modules/@11ty/dependency-tree-esm": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@11ty/dependency-tree-esm/-/dependency-tree-esm-2.0.4.tgz", + "integrity": "sha512-MYKC0Ac77ILr1HnRJalzKDlb9Z8To3kXQCltx299pUXXUFtJ1RIONtULlknknqW8cLe19DLVgmxVCtjEFm7h0A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@11ty/eleventy-utils": "^2.0.7", + "acorn": "^8.15.0", + "dependency-graph": "^1.0.0", + "normalize-path": "^3.0.0" + } + }, + "node_modules/@11ty/eleventy": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/@11ty/eleventy/-/eleventy-3.1.5.tgz", + "integrity": "sha512-hZ0g6MwZyRxCqXsPm82gIM304LraKbUz3ZmezOSjsqxttZG6cHTib3Qq8QkESJoKwnr+yX1eyfOkPC5/mEgZnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@11ty/dependency-tree": "^4.0.2", + "@11ty/dependency-tree-esm": "^2.0.4", + "@11ty/eleventy-dev-server": "^2.0.8", + "@11ty/eleventy-plugin-bundle": "^3.0.7", + "@11ty/eleventy-utils": "^2.0.7", + "@11ty/lodash-custom": "^4.17.21", + "@11ty/posthtml-urls": "^1.0.2", + "@11ty/recursive-copy": "^4.0.4", + "@sindresorhus/slugify": "^2.2.1", + "bcp-47-normalize": "^2.3.0", + "chokidar": "^3.6.0", + "debug": "^4.4.3", + "dependency-graph": "^1.0.0", + "entities": "^6.0.1", + "filesize": "^10.1.6", + "gray-matter": "^4.0.3", + "iso-639-1": "^3.1.5", + "js-yaml": "^4.1.1", + "kleur": "^4.1.5", + "liquidjs": "^10.25.0", + "luxon": "^3.7.2", + "markdown-it": "^14.1.1", + "minimist": "^1.2.8", + "moo": "0.5.2", + "node-retrieve-globals": "^6.0.1", + "nunjucks": "^3.2.4", + "picomatch": "^4.0.3", + "please-upgrade-node": "^3.2.0", + "posthtml": "^0.16.7", + "posthtml-match-helper": "^2.0.3", + "semver": "^7.7.4", + "slugify": "^1.6.8", + "tinyglobby": "^0.2.15" + }, + "bin": { + "eleventy": "cmd.cjs" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + } + }, + "node_modules/@11ty/eleventy-dev-server": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/@11ty/eleventy-dev-server/-/eleventy-dev-server-2.0.8.tgz", + "integrity": "sha512-15oC5M1DQlCaOMUq4limKRYmWiGecDaGwryr7fTE/oM9Ix8siqMvWi+I8VjsfrGr+iViDvWcH/TVI6D12d93mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@11ty/eleventy-utils": "^2.0.1", + "chokidar": "^3.6.0", + "debug": "^4.4.0", + "finalhandler": "^1.3.1", + "mime": "^3.0.0", + "minimist": "^1.2.8", + "morphdom": "^2.7.4", + "please-upgrade-node": "^3.2.0", + "send": "^1.1.0", + "ssri": "^11.0.0", + "urlpattern-polyfill": "^10.0.0", + "ws": "^8.18.1" + }, + "bin": { + "eleventy-dev-server": "cmd.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + } + }, + "node_modules/@11ty/eleventy-fetch": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/@11ty/eleventy-fetch/-/eleventy-fetch-5.1.2.tgz", + "integrity": "sha512-YxDARdR3S9UT4gOGRWgGNyokYT9jkCAjJge3OVKFdNMv1cyvWg1NHCvj9NVvK9XHenCLFy3cwvM/YYpZZTZopw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@11ty/eleventy-utils": "^2.0.7", + "@rgrove/parse-xml": "^4.2.0", + "debug": "^4.4.3", + "flatted": "^3.4.2", + "p-queue": "6.6.2" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + } + }, + "node_modules/@11ty/eleventy-img": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/@11ty/eleventy-img/-/eleventy-img-6.0.4.tgz", + "integrity": "sha512-jSy9BmubVs0mN76dcXWfSYDgRU+1+/rq/SxUR3MgIvTUAJRDop5pFW+Z1f56CDcOlEHaiPqHgnfOlqRmJvXl7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@11ty/eleventy-fetch": "^5.1.0", + "@11ty/eleventy-utils": "^2.0.7", + "brotli-size": "^4.0.0", + "debug": "^4.4.0", + "entities": "^6.0.0", + "image-size": "^1.2.1", + "p-queue": "^6.6.2", + "sharp": "^0.33.5" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + } + }, + "node_modules/@11ty/eleventy-navigation": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@11ty/eleventy-navigation/-/eleventy-navigation-1.0.5.tgz", + "integrity": "sha512-zb6xe29cM9viSdYtZywKIkJw2HIROyBINdBcFWC9uD0c/jYOTAex5nwy3HNEuh5t6/Ld/S9V4gEizfmeYuYpCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "dependency-graph": "^1.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + } + }, + "node_modules/@11ty/eleventy-plugin-bundle": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/@11ty/eleventy-plugin-bundle/-/eleventy-plugin-bundle-3.0.7.tgz", + "integrity": "sha512-QK1tRFBhQdZASnYU8GMzpTdsMMFLVAkuU0gVVILqNyp09xJJZb81kAS3AFrNrwBCsgLxTdWHJ8N64+OTTsoKkA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@11ty/eleventy-utils": "^2.0.2", + "debug": "^4.4.0", + "posthtml-match-helper": "^2.0.3" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + } + }, + "node_modules/@11ty/eleventy-utils": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@11ty/eleventy-utils/-/eleventy-utils-2.0.7.tgz", + "integrity": "sha512-6QE+duqSQ0GY9rENXYb4iPR4AYGdrFpqnmi59tFp9VrleOl0QSh8VlBr2yd6dlhkdtj7904poZW5PvGr9cMiJQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + } + }, + "node_modules/@11ty/posthtml-urls": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@11ty/posthtml-urls/-/posthtml-urls-1.0.3.tgz", + "integrity": "sha512-1YvhnkaNlFnnJic1rBMWmTC2adbuy+JQiBfl1Hecr1Wjjik1pQZmGyk/eC9zKX/FQv52s2Nht1Gi/UwhYqrBeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "evaluate-value": "^2.0.0", + "http-equiv-refresh": "^2.0.1", + "list-to-array": "^1.1.0", + "parse-srcset": "^1.0.2" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/@11ty/recursive-copy": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@11ty/recursive-copy/-/recursive-copy-4.0.4.tgz", + "integrity": "sha512-oI7m8pa7/IAU/3lqRU9vjBbs20iKFo7x+1K9kT3aVira6scc1X9MjBdgLCHzLJeJ7iB6wydioA+kr9/qPnvmlQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "errno": "^1.0.0", + "junk": "^3.1.0", + "minimatch": "^3.1.5", + "slash": "^3.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz", + "integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.5.tgz", + "integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.0.4" + } + }, + "node_modules/@mdit/helper": { + "version": "0.23.1", + "resolved": "https://registry.npmjs.org/@mdit/helper/-/helper-0.23.1.tgz", + "integrity": "sha512-ifWDG3VbUAx1ia7eBWEHm5vpv5QFUPY3kFLPPZzYBr15A7/d5w7D+8ZBg8xxqkvyC73Ys+zF14EQCq7eQAXYxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/markdown-it": "^14.1.2" + }, + "engines": { + "node": ">= 20" + }, + "peerDependencies": { + "markdown-it": "^14.1.0" + }, + "peerDependenciesMeta": { + "markdown-it": { + "optional": true + } + } + }, + "node_modules/@mdit/plugin-attrs": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/@mdit/plugin-attrs/-/plugin-attrs-0.25.1.tgz", + "integrity": "sha512-nJ8vZvREJOUcbih3D+BaCnbsYbA3MskOzWX6JAjRmnfQFFDmigK0WTx9Z5xLlo87D120AIYWGo3DGxZhwLCE0Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@mdit/helper": "0.23.1", + "@types/markdown-it": "^14.1.2" + }, + "engines": { + "node": ">= 20" + }, + "peerDependencies": { + "markdown-it": "^14.1.0" + }, + "peerDependenciesMeta": { + "markdown-it": { + "optional": true + } + } + }, + "node_modules/@rgrove/parse-xml": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@rgrove/parse-xml/-/parse-xml-4.2.0.tgz", + "integrity": "sha512-UuBOt7BOsKVOkFXRe4Ypd/lADuNIfqJXv8GvHqtXaTYXPPKkj2nS2zPllVsrtRjcomDhIJVBnZwfmlI222WH8g==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@sindresorhus/slugify": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@sindresorhus/slugify/-/slugify-2.2.1.tgz", + "integrity": "sha512-MkngSCRZ8JdSOCHRaYd+D01XhvU3Hjy6MGl06zhOk614hp9EOAp5gIkBeQg7wtmxpitU6eAL4kdiRMcJa2dlrw==", + "dev": true, + "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==", + "dev": true, + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^5.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@types/linkify-it": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz", + "integrity": "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/markdown-it": { + "version": "14.1.2", + "resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-14.1.2.tgz", + "integrity": "sha512-promo4eFwuiW+TfGxhi+0x3czqTYJkG8qB17ZUJiVF10Xm7NLVRSLUsfRTU/6h1e24VvRnXCx+hG7li58lkzog==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/linkify-it": "^5", + "@types/mdurl": "^2" + } + }, + "node_modules/@types/mdurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-2.0.0.tgz", + "integrity": "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==", + "dev": true, + "license": "MIT" + }, + "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==", + "dev": true, + "license": "MIT" + }, + "node_modules/acorn": { + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", + "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.5", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz", + "integrity": "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.11.0" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "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==", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/anymatch/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "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==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/asap": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", + "integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==", + "dev": true, + "license": "MIT" + }, + "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==", + "dev": true, + "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==", + "dev": true, + "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==", + "dev": true, + "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==", + "dev": true, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz", + "integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==", + "dev": true, + "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==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/brotli-size": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/brotli-size/-/brotli-size-4.0.0.tgz", + "integrity": "sha512-uA9fOtlTRC0iqKfzff1W34DXUA3GyVqbUaeo3Rw3d4gd1eavKVCETXrn3NzO74W+UVkG3UHu8WxUi+XvKI/huA==", + "dev": true, + "license": "MIT", + "dependencies": { + "duplexer": "0.1.1" + }, + "engines": { + "node": ">= 10.16.0" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "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": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", + "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1", + "color-string": "^1.9.0" + }, + "engines": { + "node": ">=12.5.0" + } + }, + "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==", + "dev": true, + "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==", + "dev": true, + "license": "MIT" + }, + "node_modules/color-string": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz", + "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "^1.0.0", + "simple-swizzle": "^0.2.2" + } + }, + "node_modules/commander": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-10.0.1.tgz", + "integrity": "sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==", + "dev": true, + "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==", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "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==", + "dev": true, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "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==", + "dev": true, + "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==", + "dev": true, + "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==", + "dev": true, + "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==", + "dev": true, + "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==", + "dev": true, + "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/duplexer": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.1.tgz", + "integrity": "sha512-sxNZ+ljy+RA1maXoUReeqBBpBC6RLKmg5ewzV+x+mSETmWNoKdZN6vcQjpFROemza23hGFskJtFNoUWUaQ+R4Q==", + "dev": true + }, + "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==", + "dev": true, + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/errno": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/errno/-/errno-1.0.0.tgz", + "integrity": "sha512-3zV5mFS1E8/1bPxt/B0xxzI1snsg3uSCIh6Zo1qKg6iMw93hzPANk9oBFzSFBFrwuVoQuE3rLoouAUfwOAj1wQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prr": "~1.0.1" + }, + "bin": { + "errno": "cli.js" + } + }, + "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==", + "dev": true, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/esm-import-transformer": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/esm-import-transformer/-/esm-import-transformer-3.0.5.tgz", + "integrity": "sha512-1GKLvfuMnnpI75l8c6sHoz0L3Z872xL5akGuBudgqTDPv4Vy6f2Ec7jEMKTxlqWl/3kSvNbHELeimJtnqgYniw==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.15.0" + } + }, + "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==", + "dev": true, + "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==", + "dev": true, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", + "dev": true, + "license": "MIT" + }, + "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==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extendable": "^0.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/filesize": { + "version": "10.1.6", + "resolved": "https://registry.npmjs.org/filesize/-/filesize-10.1.6.tgz", + "integrity": "sha512-sJslQKU2uM33qH5nqewAwVB2QgR6w1aMNsYUp3aN5rMRyXEwJGmZvaWzeJFNTOXWlHQyBFCWrdj3fV/fsTOX8w==", + "dev": true, + "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==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", + "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", + "dev": true, + "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.2", + "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==", + "dev": true, + "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==", + "dev": true, + "license": "MIT" + }, + "node_modules/flatted": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz", + "integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==", + "dev": true, + "license": "ISC" + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "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==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/gray-matter": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/gray-matter/-/gray-matter-4.0.3.tgz", + "integrity": "sha512-5v6yZd4JK3eMI3FqqCouswVqwugaA9r4dNZB1wwcmrD02QkV5H0y7XBQW8QwQqEaZY1pM9aqORSORhJRdNK44Q==", + "dev": true, + "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==", + "dev": true, + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/gray-matter/node_modules/js-yaml": { + "version": "3.14.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz", + "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/htmlparser2": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-7.2.0.tgz", + "integrity": "sha512-H7MImA4MS6cw7nbyURtLPO1Tms7C5H602LRETv95z1MxO/7CP7rDVROehUYeYBUYEON94NXXDEPmZuq+hX4sog==", + "dev": true, + "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==", + "dev": true, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/image-size": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/image-size/-/image-size-1.2.1.tgz", + "integrity": "sha512-rH+46sQJ2dlwfjfhCyNx5thzrv+dtmBIhPHk0zgRUukHzZ/kRueTJXoYYsclBaKcSMBWuGbOFXtioLpzTb5euw==", + "dev": true, + "license": "MIT", + "dependencies": { + "queue": "6.0.2" + }, + "bin": { + "image-size": "bin/image-size.js" + }, + "engines": { + "node": ">=16.x" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true, + "license": "ISC" + }, + "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==", + "dev": true, + "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==", + "dev": true, + "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-arrayish": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.4.tgz", + "integrity": "sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==", + "dev": true, + "license": "MIT" + }, + "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==", + "dev": true, + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "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==", + "dev": true, + "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==", + "dev": true, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "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==", + "dev": true, + "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==", + "dev": true, + "license": "ISC" + }, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/iso-639-1": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/iso-639-1/-/iso-639-1-3.1.5.tgz", + "integrity": "sha512-gXkz5+KN7HrG0Q5UGqSMO2qB9AsbEeyLP54kF1YrMsIxmu+g4BdB7rflReZTSTZGpfj8wywu6pfPBCylPIzGQA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0" + } + }, + "node_modules/js-yaml": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/junk": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/junk/-/junk-3.1.0.tgz", + "integrity": "sha512-pBxcB3LFc8QVgdggvZWyeys+hnrNWg4OcZIU/1X59k5jQdLBlCsYGRQaz234SqoRLTCgMH00fY0xRJH+F9METQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "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==", + "dev": true, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "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==", + "dev": true, + "license": "MIT", + "dependencies": { + "uc.micro": "^2.0.0" + } + }, + "node_modules/liquidjs": { + "version": "10.25.2", + "resolved": "https://registry.npmjs.org/liquidjs/-/liquidjs-10.25.2.tgz", + "integrity": "sha512-ZbgcjEjGNlAIjqhuMzymO3lCpHgmVMftKfrq4/YLLxmKaFFeQMXRGrJTqKX7OXX1hKVPUDpTIrvL7lxt3X/hmw==", + "dev": true, + "license": "MIT", + "dependencies": { + "commander": "^10.0.0" + }, + "bin": { + "liquid": "bin/liquid.js", + "liquidjs": "bin/liquid.js" + }, + "engines": { + "node": ">=16" + }, + "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==", + "dev": true, + "license": "MIT" + }, + "node_modules/luxon": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/luxon/-/luxon-3.7.2.tgz", + "integrity": "sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/markdown-it": { + "version": "14.1.1", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.1.tgz", + "integrity": "sha512-BuU2qnTti9YKgK5N+IeMubp14ZUKUUw7yeJbkjtosvHiP0AZ5c8IAgEMk79D0eC8F23r4Ac/q8cAIFdm2FtyoA==", + "dev": true, + "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==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "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==", + "dev": true, + "license": "MIT" + }, + "node_modules/mime": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz", + "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==", + "dev": true, + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "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==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/moo": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/moo/-/moo-0.5.2.tgz", + "integrity": "sha512-iSAJLHYKnX41mKcJKjqvnAN9sf0LMDTXDEvFv+ffuRR9a1MIuXLjMNL6EsnDHSkKLTWNqQQ5uo61P4EbU4NU+Q==", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/morphdom": { + "version": "2.7.8", + "resolved": "https://registry.npmjs.org/morphdom/-/morphdom-2.7.8.tgz", + "integrity": "sha512-D/fR4xgGUyVRbdMGU6Nejea1RFzYxYtyurG4Fbv2Fi/daKlWKuXGLOdXtl+3eIwL110cI2hz1ZojGICjjFLgTg==", + "dev": true, + "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==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-retrieve-globals": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/node-retrieve-globals/-/node-retrieve-globals-6.0.1.tgz", + "integrity": "sha512-j0DeFuZ/Wg3VlklfbxUgZF/mdHMTEiEipBb3q0SpMMbHaV3AVfoUQF8UGxh1s/yjqO0TgRZd4Pi/x2yRqoQ4Eg==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.14.1", + "acorn-walk": "^8.3.4", + "esm-import-transformer": "^3.0.3" + } + }, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/nunjucks": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/nunjucks/-/nunjucks-3.2.4.tgz", + "integrity": "sha512-26XRV6BhkgK0VOxfbU5cQI+ICFUtMLixv1noZn1tGU38kQH5A5nmmbk/O45xdyBhD1esk47nKrY0mvQpZIhRjQ==", + "dev": true, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "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==", + "dev": true, + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/p-finally": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/p-queue": { + "version": "6.6.2", + "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-6.6.2.tgz", + "integrity": "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "eventemitter3": "^4.0.4", + "p-timeout": "^3.2.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-timeout": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-3.2.0.tgz", + "integrity": "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-finally": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "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==", + "dev": true, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "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==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver-compare": "^1.0.0" + } + }, + "node_modules/posthtml": { + "version": "0.16.7", + "resolved": "https://registry.npmjs.org/posthtml/-/posthtml-0.16.7.tgz", + "integrity": "sha512-7Hc+IvlQ7hlaIfQFZnxlRl0jnpWq2qwibORBhQYIb0QbNtuicc5ZxvKkVT71HJ4Py1wSZ/3VR1r8LfkCtoCzhw==", + "dev": true, + "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.3", + "resolved": "https://registry.npmjs.org/posthtml-match-helper/-/posthtml-match-helper-2.0.3.tgz", + "integrity": "sha512-p9oJgTdMF2dyd7WE54QI1LvpBIkNkbSiiECKezNnDVYhGhD1AaOnAkw0Uh0y5TW+OHO8iBdSqnd8Wkpb6iUqmw==", + "dev": true, + "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==", + "dev": true, + "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==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-json": "^2.0.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/prr": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz", + "integrity": "sha512-yPw4Sng1gWghHQWj0B3ZggWUm4qVbPwPFcRG8KyxiU7J2OHFSoEHKS+EZ3fv5l1t9CyCiop6l/ZYeWbrgoQejw==", + "dev": true, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/queue": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/queue/-/queue-6.0.2.tgz", + "integrity": "sha512-iHZWu+q3IdFZFX36ro/lKBkSvfkztY5Y7HMiPlOUjhupPcG2JMfst2KKEpu5XndviX/3UhFbRngUPNKtgvtZiA==", + "dev": true, + "license": "MIT", + "dependencies": { + "inherits": "~2.0.3" + } + }, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/readdirp/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/section-matter": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/section-matter/-/section-matter-1.0.0.tgz", + "integrity": "sha512-vfD3pmTzGpufjScBh50YHKzEu2lxBWhVEHsNGoEXmCmn2hKGfeNLYMzCJpe8cD7gqX7TJluOVpBkAequ6dgMmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "extend-shallow": "^2.0.1", + "kind-of": "^6.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "dev": true, + "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==", + "dev": true, + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "dev": true, + "license": "ISC" + }, + "node_modules/sharp": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.5.tgz", + "integrity": "sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "color": "^4.2.3", + "detect-libc": "^2.0.3", + "semver": "^7.6.3" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.33.5", + "@img/sharp-darwin-x64": "0.33.5", + "@img/sharp-libvips-darwin-arm64": "1.0.4", + "@img/sharp-libvips-darwin-x64": "1.0.4", + "@img/sharp-libvips-linux-arm": "1.0.5", + "@img/sharp-libvips-linux-arm64": "1.0.4", + "@img/sharp-libvips-linux-s390x": "1.0.4", + "@img/sharp-libvips-linux-x64": "1.0.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.0.4", + "@img/sharp-libvips-linuxmusl-x64": "1.0.4", + "@img/sharp-linux-arm": "0.33.5", + "@img/sharp-linux-arm64": "0.33.5", + "@img/sharp-linux-s390x": "0.33.5", + "@img/sharp-linux-x64": "0.33.5", + "@img/sharp-linuxmusl-arm64": "0.33.5", + "@img/sharp-linuxmusl-x64": "0.33.5", + "@img/sharp-wasm32": "0.33.5", + "@img/sharp-win32-ia32": "0.33.5", + "@img/sharp-win32-x64": "0.33.5" + } + }, + "node_modules/simple-swizzle": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.4.tgz", + "integrity": "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.3.1" + } + }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/slugify": { + "version": "1.6.8", + "resolved": "https://registry.npmjs.org/slugify/-/slugify-1.6.8.tgz", + "integrity": "sha512-HVk9X1E0gz3mSpoi60h/saazLKXKaZThMLU3u/aNwoYn8/xQyX2MGxL0ui2eaokkD7tF+Zo+cKTHUbe1mmmGzA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.0.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==", + "dev": true, + "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==", + "dev": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "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==", + "dev": true, + "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==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "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==", + "dev": true, + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/urlpattern-polyfill": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/urlpattern-polyfill/-/urlpattern-polyfill-10.1.0.tgz", + "integrity": "sha512-IGjKp/o0NL3Bso1PymYURCJxMPNAf/ILOpendP9f5B6e1rTJgdgiOvgfoT8VxCAdY+Wisb9uhGaJJf3yZ2V9nw==", + "dev": true, + "license": "MIT" + }, + "node_modules/ws": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz", + "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==", + "dev": true, + "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 + } + } + } + } +} 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..5684472 --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/README.md @@ -0,0 +1,53 @@ +# `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 +import { find } from "@11ty/dependency-tree-esm"; +// CommonJS is fine too +// const { find } = require("@11ty/dependency-tree-esm"); + +await find("./my-file.js"); +// returns ["./my-local-dependency.js"] +``` + +Return a [dependency-graph](https://github.com/jriecken/dependency-graph) instance: + +```js +import { findGraph } from "@11ty/dependency-tree-esm"; +// CommonJS is fine too +// const { find } = require("@11ty/dependency-tree-esm"); + +(await findGraph("./my-file.js")).overallOrder(); +// returns ["./my-local-dependency.js", "./my-file.js"] +``` \ No newline at end of file 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..4e9a9b4 --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/main.js @@ -0,0 +1,173 @@ +const path = require("node:path"); +const { readFileSync, existsSync } = require("node:fs"); + +const acorn = require("acorn"); +const normalizePath = require("normalize-path"); +const { TemplatePath } = require("@11ty/eleventy-utils"); +const { DepGraph } = require("dependency-graph"); + +// 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); +} + +function getImportAttributeType(attributes = []) { + for(let node of attributes) { + if(node.type === "ImportAttribute" && node.key.type === "Identifier" && node.key.name === "type") { + return node.value.value; + } + } +} + +async function getSources(filePath, contents, options = {}) { + let { parserOverride } = Object.assign({}, options); + let sources = new Set(); + let sourcesToRecurse = new Set(); + + let ast = (parserOverride || acorn).parse(contents, { + sourceType: "module", + ecmaVersion: "latest", + }); + + for(let node of ast.body) { + if(node.type === "ImportDeclaration" && isNonBareSpecifier(node.source.value)) { + let importAttributeType = getImportAttributeType(node?.attributes); + let normalized = normalizeImportSourceToFilePath(filePath, node.source.value); + if(normalized !== filePath) { + sources.add(normalized); + + // Recurse typeless (JavaScript) import types only + // Right now only `css` and `json` are valid but others might come later + if(!importAttributeType) { + sourcesToRecurse.add(normalized); + } + } + } + } + + + return { + sources, + sourcesToRecurse, + } +} + +// second argument used to be `alreadyParsedSet = new Set()`, keep that backwards compat +async function find(filePath, options = {}) { + if(options instanceof Set) { + options = { + alreadyParsedSet: options + }; + } + + if(!options.alreadyParsedSet) { + options.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(options.alreadyParsedSet.has(normalized) || !existsSync(filePath)) { + return []; + } + options.alreadyParsedSet.add(normalized); + + let contents = readFileSync(normalized, { encoding: 'utf8' }); + let { sources, sourcesToRecurse } = await getSources(filePath, contents, options); + + // Recurse for nested deps + for(let source of sourcesToRecurse) { + let s = await find(source, options); + for(let p of s) { + if(sources.has(p) || p === filePath) { + continue; + } + + sources.add(p); + } + } + + return Array.from(sources); +} + +function mergeGraphs(rootGraph, ...graphs) { + if(!(rootGraph instanceof DepGraph)) { + throw new Error("Incorrect type passed to mergeGraphs, expected DepGraph"); + } + for(let g of graphs) { + for(let node of g.overallOrder()) { + if(!rootGraph.hasNode(node)) { + rootGraph.addNode(node); + } + for(let dep of g.directDependenciesOf(node)) { + rootGraph.addDependency(node, dep); + } + } + } +} + +// second argument used to be `alreadyParsedSet = new Set()`, keep that backwards compat +async function findGraph(filePath, options = {}) { + if(options instanceof Set) { + options = { + alreadyParsedSet: options + }; + } + if(!options.alreadyParsedSet) { + options.alreadyParsedSet = new Set(); + } + + let graph = new DepGraph(); + let normalized = normalizeFilePath(filePath); + graph.addNode(filePath); + + if(options.alreadyParsedSet.has(normalized) || !existsSync(filePath)) { + return graph; + } + options.alreadyParsedSet.add(normalized); + + let contents = readFileSync(normalized, "utf8"); + let { sources, sourcesToRecurse } = await getSources(filePath, contents, options); + for(let source of sources) { + if(!graph.hasNode(source)) { + graph.addNode(source); + } + graph.addDependency(normalized, source); + } + + // Recurse for nested deps + for(let source of sourcesToRecurse) { + let recursedGraph = await findGraph(source, options); + mergeGraphs(graph, recursedGraph); + } + + return graph; +} + +module.exports = { + find, + findGraph, + mergeGraphs, +}; \ No newline at end of file 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..40b8cd7 --- /dev/null +++ b/node_modules/@11ty/dependency-tree-esm/package.json @@ -0,0 +1,26 @@ +{ + "name": "@11ty/dependency-tree-esm", + "version": "2.0.4", + "description": "Finds all JavaScript ES Module dependencies from a filename.", + "main": "main.js", + "type": "commonjs", + "scripts": { + "test": "echo \"Error: run tests from root directory\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/11ty/eleventy-utils.git" + }, + "author": { + "name": "Zach Leatherman", + "email": "zach@zachleat.com", + "url": "https://zachleat.com/" + }, + "license": "MIT", + "dependencies": { + "@11ty/eleventy-utils": "^2.0.7", + "acorn": "^8.15.0", + "dependency-graph": "^1.0.0", + "normalize-path": "^3.0.0" + } +} 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..0910ca4 --- /dev/null +++ b/node_modules/@11ty/dependency-tree/README.md @@ -0,0 +1,109 @@ +# `@11ty/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: [`@11ty/dependency-tree-esm`](https://github.com/11ty/eleventy-utils/tree/main/parse-deps-esm) for the ESM version. +* See also: [`@11ty/dependency-tree-typescript`](https://github.com/11ty/eleventy-utils/tree/main/parse-deps-typescript) for the TypeScript version. + +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. + +### `getPackagesByType` method + +_Added in v4.0.2._ + +```js +const DependencyTree = require("@11ty/dependency-tree"); +const {getPackagesByType} = DependencyTree; + +// With `require(esm)` support, some targets may be modules! +// Return separate lists for commonjs and esm lists +getPackagesByType("./my-file.js"); +// returns { commonjs: ["./my-file.js"], esm: [] } +``` diff --git a/node_modules/@11ty/dependency-tree/main.js b/node_modules/@11ty/dependency-tree/main.js new file mode 100644 index 0000000..b7dd2d2 --- /dev/null +++ b/node_modules/@11ty/dependency-tree/main.js @@ -0,0 +1,157 @@ +const path = require("node: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); + let modules = new Set(); + + try { + let res = require(absoluteFilename); + if(res[Symbol.toStringTag] === "Module" || res.__esModule) { + modules.add(filename); + } + } 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(Array.isArray(mod.children) && mod.children.length > 0) { + 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] ) { + let { commonjs, esm } = getDependenciesFor(relativeChildFilename, avoidCircular, options); + for(let dependency of commonjs) { + dependencies.add(dependency); + } + for(let dependency of esm) { + modules.add(dependency); + } + } + } + } + } + } + + return { + esm: modules, + commonjs: dependencies, + } +} + +function normalizeList(packageSet) { + return Array.from( packageSet ).map(filePath => { + if(filePath.startsWith("./")) { + return TemplatePath.standardizeFilePath(filePath); + } + return filePath; // node_module name + }) +} + +function getCleanDependencyListFor(filename, options = {}) { + let { commonjs } = getDependenciesFor(filename, null, options); + + return normalizeList(commonjs); +} + +function getCleanDependencyListByTypeFor(filename, options = {}) { + let { commonjs, esm } = getDependenciesFor(filename, null, options); + + return { + commonjs: normalizeList(commonjs), + esm: normalizeList(esm), + }; +} + +module.exports = getCleanDependencyListFor; +module.exports.getPackagesByType = getCleanDependencyListByTypeFor; +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..f140f82 --- /dev/null +++ b/node_modules/@11ty/dependency-tree/package.json @@ -0,0 +1,42 @@ +{ + "name": "@11ty/dependency-tree", + "version": "4.0.2", + "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" + ], + "watchMode": { + "ignoreChanged": [ + "./test/stubs/**" + ] + } + }, + "devDependencies": { + "@sindresorhus/is": "^4.6.0", + "ava": "^6.4.1", + "semver": "^7.7.3" + }, + "dependencies": { + "@11ty/eleventy-utils": "^2.0.1" + } +} 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..fc0ddd1 --- /dev/null +++ b/node_modules/@11ty/eleventy-dev-server/client/reload-client.js @@ -0,0 +1,336 @@ +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 paramName = EleventyReload.QUERY_PARAM; + let isErasing = oldUrl.searchParams.has(paramName) && !newUrl.searchParams.has(paramName); + if(!isErasing) { + // not a match if _11ty has a new value (not being erased) + return false; + } + + oldUrl.searchParams.set(paramName, ""); + newUrl.searchParams.set(paramName, ""); + + // 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); + } + + static fullPageReload() { + Util.log(`Page reload initiated.`); + window.location.reload(); + } +} + +class EleventyReload { + static QUERY_PARAM = "_11ty"; + + static reloadTypes = { + css: (files, build = {}) => { + // Initiate a full page refresh if a CSS change is made but does match any stylesheet url + // `build.stylesheets` available in Eleventy v3.0.1-alpha.5+ + if(Array.isArray(build.stylesheets)) { + let match = false; + for (let link of document.querySelectorAll(`link[rel="stylesheet"]`)) { + if (link.href) { + let url = new URL(link.href); + if(build.stylesheets.includes(url.pathname)) { + match = true; + } + } + } + + if(!match) { + Util.fullPageReload(); + return; + } + } + + for (let link of document.querySelectorAll(`link[rel="stylesheet"]`)) { + if (link.href) { + let url = new URL(link.href); + url.searchParams.set(this.QUERY_PARAM, Date.now()); + link.href = url.toString(); + } + } + + Util.log(`CSS updated without page reload.`); + }, + default: async (files, build = {}) => { + let morphed = false; + let domdiffTemplates = (build?.templates || []).filter(({url, inputPath}) => { + return url === document.location.pathname && (files || []).includes(inputPath); + }); + + if(domdiffTemplates.length === 0) { + Util.fullPageReload(); + return; + } + + try { + // Important: using `./` allows the `.11ty` folder name to be changed + const { default: morphdom } = await import(`./morphdom.js`); + + for (let {url, inputPath, content} of domdiffTemplates) { + // Notable limitation: this won’t re-run script elements or JavaScript page lifecycle events (load/DOMContentLoaded) + morphed = true; + + morphdom(document.documentElement, 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(content); + Util.log(`HTML delta applied without page reload.`); + } + } catch(e) { + Util.error( "Morphdom error", e ); + } + + if (!morphed) { + Util.fullPageReload(); + } + } + } + + constructor() { + this.connectionMessageShown = false; + this.reconnectEventCallback = this.reconnect.bind(this); + } + + init(options = {}) { + if (!("WebSocket" in window)) { + return; + } + + let documentUrl = new URL(document.location.href); + + let reloadPort = new URL(import.meta.url).searchParams.get("reloadPort"); + if(reloadPort) { + documentUrl.port = reloadPort; + } + + let { protocol, host } = documentUrl; + + // 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(!EleventyReload.reloadTypes[subtype]) { + subtype = "default"; + } + + await EleventyReload.reloadTypes[subtype](files, build); + } + + 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..e413c7c --- /dev/null +++ b/node_modules/@11ty/eleventy-dev-server/package.json @@ -0,0 +1,57 @@ +{ + "name": "@11ty/eleventy-dev-server", + "version": "2.0.8", + "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": "^2.0.1", + "chokidar": "^3.6.0", + "debug": "^4.4.0", + "finalhandler": "^1.3.1", + "mime": "^3.0.0", + "minimist": "^1.2.8", + "morphdom": "^2.7.4", + "please-upgrade-node": "^3.2.0", + "send": "^1.1.0", + "ssri": "^11.0.0", + "urlpattern-polyfill": "^10.0.0", + "ws": "^8.18.1" + }, + "devDependencies": { + "ava": "^6.2.0" + } +} 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..9fbe898 --- /dev/null +++ b/node_modules/@11ty/eleventy-dev-server/server.js @@ -0,0 +1,1024 @@ +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 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"); +const ipAddress = require("./server/ipAddress.js"); + +if (!globalThis.URLPattern) { + require("urlpattern-polyfill"); +} + +const DEFAULT_OPTIONS = { + port: 8080, + reloadPort: false, // Falsy uses same as `port` + 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 { + #watcher; + #serverClosing; + #serverState; + #readyPromise; + #readyResolve; + + 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; + this.getWatcher(); + + this.#readyPromise = new Promise((resolve) => { + this.#readyResolve = resolve; + }) + } + + 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) { + return 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() { + // only initialize watcher if watcher via getWatcher if has targets + // this.watcher in watchFiles() is a manual workaround + if(this.options.watch.length > 0) { + return this.watcher; + } + } + + watchFiles(files) { + if(Array.isArray(files) && files.length > 0) { + 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, + }; + } + + #readFile(filepath) { + if(this.options.useCache && this.fileCache[filepath]) { + return this.fileCache[filepath]; + } + + let contents = fs.readFileSync(filepath, { + encoding: this.options.encoding, + }); + + if(this.options.useCache) { + this.fileCache[filepath] = contents; + } + + return contents; + } + + #getFileContents(localpath, rootDir) { + 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; + } + } + + return this.#readFile(filepath); + } + + augmentContentWithNotifier(content, inlineContents = false, options = {}) { + let { integrityHash, scriptContents } = options; + if(!scriptContents) { + scriptContents = this.#getFileContents("./client/reload-client.js"); + } + if(!integrityHash) { + integrityHash = ssri.fromData(scriptContents); + } + + let searchParams = new URLSearchParams(); + if(this.options.reloadPort) { + searchParams.set("reloadPort", this.options.reloadPort); + } + + let searchParamsStr = searchParams.size > 0 ? `?${searchParams.toString()}` : ""; + + // 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 = / \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-img/eslint.config.mjs b/node_modules/@11ty/eleventy-img/eslint.config.mjs new file mode 100644 index 0000000..ed7517e --- /dev/null +++ b/node_modules/@11ty/eleventy-img/eslint.config.mjs @@ -0,0 +1,29 @@ +import { defineConfig } from "eslint/config"; +import pluginJs from "@eslint/js"; +import pluginStylistic from "@stylistic/eslint-plugin-js"; +import globals from "globals"; + +const GLOB_JS = '**/*.?([cm])js'; + +export default defineConfig([ + { + files: [GLOB_JS], + plugins: { + js: pluginJs, + "@stylistic/js": pluginStylistic + }, + extends: [ + "js/recommended", + ], + languageOptions: { + ecmaVersion: 2022, + sourceType: "module", + globals: { ...globals.node }, + }, + rules: { + "@stylistic/js/indent": ["error", 2], + "@stylistic/js/linebreak-style": ["error", "unix"], + "@stylistic/js/semi": ["error", "always"], + }, + }, +]); diff --git a/node_modules/@11ty/eleventy-img/img.js b/node_modules/@11ty/eleventy-img/img.js new file mode 100644 index 0000000..ee4ed6d --- /dev/null +++ b/node_modules/@11ty/eleventy-img/img.js @@ -0,0 +1,151 @@ +const {default: PQueue} = require("p-queue"); + +const DeferCounter = require("./src/defer-counter.js"); +const BuildLogger = require("./src/build-logger.js"); +const Util = require("./src/util.js"); +const Image = require("./src/image.js"); +const DirectoryManager = require("./src/directory-manager.js"); + +// For exports +const getImageSize = require("image-size"); +const ImagePath = require("./src/image-path.js"); + +const debug = require("debug")("Eleventy:Image"); + +const GLOBAL_OPTIONS = require("./src/global-options.js").defaults; + +const { memCache, diskCache } = require("./src/caches.js"); + +let deferCounter = new DeferCounter(); +let buildLogger = new BuildLogger(); +let directoryManager = new DirectoryManager(); + +/* Queue */ +let processingQueue = new PQueue({ + concurrency: GLOBAL_OPTIONS.concurrency +}); +processingQueue.on("active", () => { + debug( `Concurrency: ${processingQueue.concurrency}, Size: ${processingQueue.size}, Pending: ${processingQueue.pending}` ); +}); + +// TODO move this into build-logger.js +function setupLogger(eleventyConfig, opts) { + if(typeof eleventyConfig?.logger?.logWithOptions !== "function" || Util.isRequested(opts?.generatedVia)) { + return; + } + + buildLogger.setupOnce(eleventyConfig, () => { + // before build + deferCounter.resetCount(); + memCache.resetCount(); + diskCache.resetCount(); + }, () => { + // after build + let [memoryCacheHit] = memCache.getCount(); + let [diskCacheHit, diskCacheMiss] = diskCache.getCount(); + // these are unique images, multiple requests to optimize the same image are de-duplicated + let deferCount = deferCounter.getCount(); + + let cachedCount = memoryCacheHit + diskCacheHit; + let optimizedCount = diskCacheMiss + diskCacheHit + memoryCacheHit + deferCount; + + let msg = []; + msg.push(`${optimizedCount} ${optimizedCount !== 1 ? "images" : "image"} optimized`); + + if(cachedCount > 0 || deferCount > 0) { + let innerMsg = []; + if(cachedCount > 0) { + innerMsg.push(`${cachedCount} cached`); + } + if(deferCount > 0) { + innerMsg.push(`${deferCount} deferred`); + } + msg.push(` (${innerMsg.join(", ")})`); + } + + if(optimizedCount > 0 || cachedCount > 0 || deferCount > 0) { + eleventyConfig?.logger?.logWithOptions({ + message: msg.join(""), + prefix: "[11ty/eleventy-img]", + color: "green", + }); + } + }); +} + +function createImage(src, opts = {}) { + let eleventyConfig = opts.eleventyConfig; + + if(opts?.eleventyConfig && {}.propertyIsEnumerable.call(opts, "eleventyConfig")) { + delete opts.eleventyConfig; + Util.addConfig(eleventyConfig, opts); + } + + let img = Image.create(src, opts); + + img.setQueue(processingQueue); + img.setBuildLogger(buildLogger); + img.setDirectoryManager(directoryManager); + + setupLogger(eleventyConfig, opts); + + if(opts.transformOnRequest) { + deferCounter.increment(src); + } + + return img; +}; + +function queueImage(src, opts = {}) { + if(src.constructor?.name === "UserConfig") { + throw new Error(`Eleventy Image’s default export is not an Eleventy Plugin and cannot be used with \`eleventyConfig.addPlugin()\`. Use the \`eleventyImageTransformPlugin\` named export instead, like this: \`import { eleventyImageTransformPlugin } from '@11ty/eleventy-img';\` or this: \`const { eleventyImageTransformPlugin } = require('@11ty/eleventy-img');\``); + } + + let img = createImage(src, opts); + return img.queue(); +} + +// Exports + +module.exports = queueImage; + +Object.defineProperty(module.exports, "concurrency", { + get: function() { + return processingQueue.concurrency; + }, + set: function(concurrency) { + processingQueue.concurrency = concurrency; + }, +}); + +module.exports.Util = Util; +module.exports.Image = Image; +module.exports.ImagePath = ImagePath; +module.exports.ImageSize = getImageSize; + +// Backwards compat +module.exports.statsSync = Image.statsSync; +module.exports.statsByDimensionsSync = Image.statsByDimensionsSync; +module.exports.getFormats = Image.getFormatsArray; +module.exports.getWidths = Image.getValidWidths; + +module.exports.getHash = function getHash(src, options) { + let img = new Image(src, options); + return img.getHash(); +}; + +module.exports.setupLogger = setupLogger; + +const generateHTML = require("./src/generate-html.js"); +module.exports.generateHTML = generateHTML; +module.exports.generateObject = generateHTML.generateObject; + +const { eleventyWebcOptionsPlugin } = require("./src/webc-options-plugin.js"); +module.exports.eleventyImagePlugin = eleventyWebcOptionsPlugin; +module.exports.eleventyImageWebcOptionsPlugin = eleventyWebcOptionsPlugin; + +const { eleventyImageTransformPlugin } = require("./src/transform-plugin.js"); +module.exports.eleventyImageTransformPlugin = eleventyImageTransformPlugin; + +const { eleventyImageOnRequestDuringServePlugin } = require("./src/on-request-during-serve-plugin.js"); +module.exports.eleventyImageOnRequestDuringServePlugin = eleventyImageOnRequestDuringServePlugin; diff --git a/node_modules/@11ty/eleventy-img/package.json b/node_modules/@11ty/eleventy-img/package.json new file mode 100644 index 0000000..9a2b34a --- /dev/null +++ b/node_modules/@11ty/eleventy-img/package.json @@ -0,0 +1,75 @@ +{ + "name": "@11ty/eleventy-img", + "version": "6.0.4", + "description": "Low level utility to perform build-time image transformations.", + "publishConfig": { + "access": "public" + }, + "main": "img.js", + "engines": { + "node": ">=18" + }, + "scripts": { + "pretest": "eslint img.js src/**.js test/**.js", + "test": "ava --no-worker-threads", + "watch": "ava --no-worker-threads --watch", + "sample": "cd sample && node sample.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/11ty/eleventy-img.git" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + }, + "keywords": [ + "eleventy", + "eleventy-utility" + ], + "author": { + "name": "Zach Leatherman", + "email": "zachleatherman@gmail.com", + "url": "https://zachleat.com/" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/11ty/eleventy-img/issues" + }, + "homepage": "https://github.com/11ty/eleventy-img#readme", + "dependencies": { + "@11ty/eleventy-fetch": "^5.1.0", + "@11ty/eleventy-utils": "^2.0.7", + "brotli-size": "^4.0.0", + "debug": "^4.4.0", + "entities": "^6.0.0", + "image-size": "^1.2.1", + "p-queue": "^6.6.2", + "sharp": "^0.33.5" + }, + "devDependencies": { + "@11ty/eleventy": "^3.0.0", + "@11ty/eleventy-plugin-webc": "^0.11.2", + "@eslint/js": "^9.26.0", + "@stylistic/eslint-plugin-js": "^4.2.0", + "ava": "^6.3.0", + "eslint": "^9.26.0", + "exifr": "^7.1.3", + "globals": "^16.1.0", + "pixelmatch": "^5.3.0" + }, + "ava": { + "failFast": false, + "files": [ + "./test/*.{js,cjs,mjs}" + ], + "watchMode": { + "ignoreChanges": [ + "./.cache/*", + "./img/*", + "./test/img/*", + "./test/**/generated*" + ] + } + } +} diff --git a/node_modules/@11ty/eleventy-img/src/adapters/brotli-size.browser.js b/node_modules/@11ty/eleventy-img/src/adapters/brotli-size.browser.js new file mode 100644 index 0000000..cf0ce10 --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/adapters/brotli-size.browser.js @@ -0,0 +1,3 @@ +module.exports = function() { + throw new Error("`svgCompressionSize: 'br'` feature is not supported in browser."); +}; diff --git a/node_modules/@11ty/eleventy-img/src/adapters/brotli-size.js b/node_modules/@11ty/eleventy-img/src/adapters/brotli-size.js new file mode 100644 index 0000000..57efc1a --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/adapters/brotli-size.js @@ -0,0 +1,5 @@ +const brotliSize = require("brotli-size"); + +module.exports = function(contents) { + return brotliSize.sync(contents); +}; diff --git a/node_modules/@11ty/eleventy-img/src/adapters/sharp.browser.js b/node_modules/@11ty/eleventy-img/src/adapters/sharp.browser.js new file mode 100644 index 0000000..c1f6eb2 --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/adapters/sharp.browser.js @@ -0,0 +1,3 @@ +module.exports = function() { + throw new Error("Sharp is not supported in browser."); +}; diff --git a/node_modules/@11ty/eleventy-img/src/adapters/sharp.js b/node_modules/@11ty/eleventy-img/src/adapters/sharp.js new file mode 100644 index 0000000..63e9253 --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/adapters/sharp.js @@ -0,0 +1,3 @@ +const sharp = require("sharp"); + +module.exports = sharp; diff --git a/node_modules/@11ty/eleventy-img/src/build-logger.js b/node_modules/@11ty/eleventy-img/src/build-logger.js new file mode 100644 index 0000000..434fc8e --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/build-logger.js @@ -0,0 +1,66 @@ +const path = require("node:path"); +const { TemplatePath } = require("@11ty/eleventy-utils"); + +const Util = require("./util.js"); + +class BuildLogger { + #eleventyConfig; + + constructor() { + this.hasAssigned = false; + } + + setupOnce(eleventyConfig, beforeCallback, afterCallback) { + if(this.hasAssigned) { + return; + } + + this.hasAssigned = true; + this.#eleventyConfig = eleventyConfig; + + eleventyConfig.on("eleventy.before", beforeCallback); + eleventyConfig.on("eleventy.after", afterCallback); + + eleventyConfig.on("eleventy.reset", () => { + this.hasAssigned = false; + beforeCallback(); // we run this on reset because the before callback will have disappeared (as the config reset) + }); + } + + getFriendlyImageSource(imageSource) { + if(Buffer.isBuffer(imageSource)) { + return ``; + } + + if(Util.isRemoteUrl(imageSource)) { + return imageSource; + } + if(path.isAbsolute(imageSource)) { + // convert back to relative url + return TemplatePath.addLeadingDotSlash(path.relative(path.resolve("."), imageSource)); + } + + return TemplatePath.addLeadingDotSlash(imageSource); + } + + log(message, options = {}, logOptions = {}) { + if(typeof this.#eleventyConfig?.logger?.logWithOptions !== "function" || options.transformOnRequest) { + return; + } + + this.#eleventyConfig.logger.logWithOptions(Object.assign({ + message: `${message}${options.generatedVia ? ` (${options.generatedVia})` : ""}`, + type: "log", + prefix: "[11ty/eleventy-img]" + }, logOptions)); + } + + error(message, options = {}, logOptions = {}) { + logOptions.type = "error"; + logOptions.force = true; + + this.log(message, options, logOptions); + } +} + +module.exports = BuildLogger; diff --git a/node_modules/@11ty/eleventy-img/src/caches.js b/node_modules/@11ty/eleventy-img/src/caches.js new file mode 100644 index 0000000..62818ac --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/caches.js @@ -0,0 +1,16 @@ +const MemoryCache = require("./memory-cache.js"); +const DiskCache = require("./disk-cache.js"); +const ExistsCache = require("./exists-cache.js"); + +let memCache = new MemoryCache(); + +let existsCache = new ExistsCache(); + +let diskCache = new DiskCache(); +diskCache.setExistsCache(existsCache); + +module.exports = { + memCache, + diskCache, + existsCache +}; diff --git a/node_modules/@11ty/eleventy-img/src/defer-counter.js b/node_modules/@11ty/eleventy-img/src/defer-counter.js new file mode 100644 index 0000000..9fcb0ff --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/defer-counter.js @@ -0,0 +1,27 @@ +class DeferCounter { + constructor() { + this.resetCount(); + } + + resetCount() { + this.deferCount = 0; + this.inputs = new Map(); + } + + getCount() { + return this.deferCount; + } + + increment(input) { + if(input) { + if(this.inputs.has(input)) { + return; + } + this.inputs.set(input, true); + } + + this.deferCount++; + } +} + +module.exports = DeferCounter; diff --git a/node_modules/@11ty/eleventy-img/src/directory-manager.js b/node_modules/@11ty/eleventy-img/src/directory-manager.js new file mode 100644 index 0000000..a2ebbe0 --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/directory-manager.js @@ -0,0 +1,29 @@ +const fs = require("node:fs"); +const path = require("node:path"); +const debugUtil = require("debug"); +const debugAssets = debugUtil("Eleventy:Assets"); + +class DirectoryManager { + #dirs = new Set(); + + isCreated(dir) { + return this.#dirs.has(dir); + } + + create(dir) { + if(this.isCreated(dir)) { + return; + } + + this.#dirs.add(dir); + debugAssets("[11ty/eleventy-img] Creating directory %o", dir); + fs.mkdirSync(dir, { recursive: true }); + } + + createFromFile(filepath) { + let dir = path.dirname(filepath); + this.create(dir); + } +} + +module.exports = DirectoryManager; diff --git a/node_modules/@11ty/eleventy-img/src/disk-cache.js b/node_modules/@11ty/eleventy-img/src/disk-cache.js new file mode 100644 index 0000000..4d14319 --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/disk-cache.js @@ -0,0 +1,54 @@ +// const debug = require("debug")("Eleventy:Image"); + +class DiskCache { + #existsCache; + + constructor() { + this.hitCounter = 0; + this.missCounter = 0; + this.inputs = new Map(); + } + + setExistsCache(existsCache) { + this.#existsCache = existsCache; + } + + resetCount() { + this.hitCounter = 0; + this.missCounter = 0; + } + + getCount() { + return [this.hitCounter, this.missCounter]; + } + + isCached(targetFile, sourceInput, incrementCounts = true) { + if(!this.#existsCache) { + throw new Error("Missing `#existsCache`"); + } + + // Disk cache runs once per output file, so we only increment counts once per input + if(this.inputs.has(sourceInput)) { + incrementCounts = false; + } + + this.inputs.set(sourceInput, true); + + if(this.#existsCache?.exists(targetFile)) { + if(incrementCounts) { + this.hitCounter++; + } + + // debug("Images re-used (via disk cache): %o", this.hitCounter); + return true; + } + + if(incrementCounts) { + this.missCounter++; + } + + return false; + } +} + +module.exports = DiskCache; diff --git a/node_modules/@11ty/eleventy-img/src/exists-cache.js b/node_modules/@11ty/eleventy-img/src/exists-cache.js new file mode 100644 index 0000000..56b1702 --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/exists-cache.js @@ -0,0 +1,40 @@ +const fs = require("node:fs"); +const Util = require("./util.js"); + +// Checks both files and directories +class ExistsCache { + #exists = new Map(); + + constructor() { + this.lookupCount = 0; + } + + get size() { + return this.#exists.size; + } + + has(path) { + return this.#exists.has(path); + } + + // Relative paths (to root directory) expected (but not enforced due to perf costs) + exists(path) { + if(Util.isFullUrl(path)) { + return false; + } + + if (!this.#exists.has(path)) { + let exists = fs.existsSync(path); + this.lookupCount++; + + // mark for next time + this.#exists.set(path, Boolean(exists)); + + return exists; + } + + return this.#exists.get(path); + } +} + +module.exports = ExistsCache; diff --git a/node_modules/@11ty/eleventy-img/src/format-hooks/svg.js b/node_modules/@11ty/eleventy-img/src/format-hooks/svg.js new file mode 100644 index 0000000..ff42e69 --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/format-hooks/svg.js @@ -0,0 +1,14 @@ +const fs = require("node:fs"); +const debugUtil = require("debug"); +const debugAssets = debugUtil("Eleventy:Assets"); + +module.exports = async function createSvg(sharpInstance) { + let input = sharpInstance.options.input; + let svgBuffer = input.buffer; + if(svgBuffer) { // remote URL already has buffer + return svgBuffer; + } else { // local file system + debugAssets("[11ty/eleventy-img] Reading %o", input.file); + return fs.readFileSync(input.file); + } +}; diff --git a/node_modules/@11ty/eleventy-img/src/generate-html.js b/node_modules/@11ty/eleventy-img/src/generate-html.js new file mode 100644 index 0000000..87ade77 --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/generate-html.js @@ -0,0 +1,220 @@ +const { escapeAttribute } = require("entities"); + +const LOWSRC_FORMAT_PREFERENCE = ["jpeg", "png", "gif", "svg", "webp", "avif"]; + +const CHILDREN_OBJECT_KEY = "@children"; + +function generateSrcset(metadataFormatEntry) { + if(!Array.isArray(metadataFormatEntry)) { + return ""; + } + + return metadataFormatEntry.map(entry => entry.srcset).join(", "); +} + +/* + Returns: + e.g. { img: { alt: "", src: "" } + e.g. { img: { alt: "", src: "", srcset: "", sizes: "" } } + e.g. { picture: { + class: "", + @children: [ + { source: { srcset: "", sizes: "" } }, + { source: { srcset: "", sizes: "" } }, + { img: { alt: "", src: "", srcset: "", sizes: "" } }, + ] + } + */ +function generateObject(metadata, userDefinedImgAttributes = {}, userDefinedPictureAttributes = {}, options = {}) { + let htmlOptions = options?.htmlOptions || {}; + let imgAttributes = Object.assign({}, options?.defaultAttributes, htmlOptions?.imgAttributes, userDefinedImgAttributes); + let pictureAttributes = Object.assign({}, htmlOptions?.pictureAttributes, userDefinedPictureAttributes); + + // The attributes.src gets overwritten later on. Save it here to make the error outputs less cryptic. + let originalSrc = imgAttributes.src; + + if(imgAttributes.alt === undefined) { + // You bet we throw an error on missing alt (alt="" works okay) + throw new Error(`Missing \`alt\` attribute on eleventy-img shortcode from: ${originalSrc}`); + } + + let formats = Object.keys(metadata); + let values = Object.values(metadata); + let entryCount = 0; + for(let imageFormat of values) { + entryCount += imageFormat.length; + } + + if(entryCount === 0) { + throw new Error("No image results found from `eleventy-img` in generateHTML. Expects a results object similar to: https://www.11ty.dev/docs/plugins/image/#usage."); + } + + let lowsrc; + let lowsrcFormat; + for(let format of LOWSRC_FORMAT_PREFERENCE) { + if((format in metadata) && metadata[format].length) { + lowsrcFormat = format; + lowsrc = metadata[lowsrcFormat]; + break; + } + } + + // Handle if empty intersection between format and LOWSRC_FORMAT_PREFERENCE (e.g. gif) + // If there’s only one format in the results, use that + if(!lowsrc && formats.length === 1) { + lowsrcFormat = formats[0]; + lowsrc = metadata[lowsrcFormat]; + } + + if(!lowsrc || !lowsrc.length) { + throw new Error(`Could not find the lowest source for responsive markup for ${originalSrc}`); + } + + imgAttributes.src = lowsrc[0].url; + + if(htmlOptions.fallback === "largest" || htmlOptions.fallback === undefined) { + imgAttributes.width = lowsrc[lowsrc.length - 1].width; + imgAttributes.height = lowsrc[lowsrc.length - 1].height; + } else if(htmlOptions.fallback === "smallest") { + imgAttributes.width = lowsrc[0].width; + imgAttributes.height = lowsrc[0].height; + } else { + throw new Error("Invalid `fallback` option specified. 'largest' and 'smallest' are supported. Received: " + htmlOptions.fallback); + } + + let imgAttributesWithoutSizes = Object.assign({}, imgAttributes); + delete imgAttributesWithoutSizes.sizes; + + // : one format and one size + if(entryCount === 1) { + return { + img: imgAttributesWithoutSizes + }; + } + + // Per the HTML specification sizes is required srcset is using the `w` unit + // https://html.spec.whatwg.org/dev/semantics.html#the-link-element:attr-link-imagesrcset-4 + // Using the default "100vw" is okay + let missingSizesErrorMessage = `Missing \`sizes\` attribute on eleventy-img shortcode from: ${originalSrc}. Workarounds: 1. Use a single output width for this image 2. Use \`loading="lazy"\` (which uses sizes="auto" though browser support currently varies)`; + + // : one format and multiple sizes + if(formats.length === 1) { // implied entryCount > 1 + if(entryCount > 1 && !imgAttributes.sizes) { + // Use `sizes="auto"` when using `loading="lazy"` instead of throwing an error. + if(imgAttributes.loading === "lazy") { + imgAttributes.sizes = "auto"; + } else { + throw new Error(missingSizesErrorMessage); + } + } + + let imgAttributesCopy = Object.assign({}, imgAttributesWithoutSizes); + imgAttributesCopy.srcset = generateSrcset(lowsrc); + imgAttributesCopy.sizes = imgAttributes.sizes; + + return { + img: imgAttributesCopy + }; + } + + let children = []; + values.filter(imageFormat => { + return imageFormat.length > 0 && (lowsrcFormat !== imageFormat[0].format); + }).forEach(imageFormat => { + if(imageFormat.length > 1 && !imgAttributes.sizes) { + if(imgAttributes.loading === "lazy") { + imgAttributes.sizes = "auto"; + } else { + throw new Error(missingSizesErrorMessage); + } + } + + let sourceAttrs = { + type: imageFormat[0].sourceType, + srcset: generateSrcset(imageFormat), + }; + + if(imgAttributes.sizes) { + sourceAttrs.sizes = imgAttributes.sizes; + } + + children.push({ + "source": sourceAttrs + }); + }); + + /* + Add lowsrc as an img, for browsers that don’t support picture or the formats provided in source + + If we have more than one size, we can use srcset and sizes. + If the browser doesn't support those attributes, it should ignore them. + */ + let imgAttributesForPicture = Object.assign({}, imgAttributesWithoutSizes); + if (lowsrc.length > 1) { + if (!imgAttributes.sizes) { + // Per the HTML specification sizes is required srcset is using the `w` unit + // https://html.spec.whatwg.org/dev/semantics.html#the-link-element:attr-link-imagesrcset-4 + // Using the default "100vw" is okay + throw new Error(missingSizesErrorMessage); + } + + imgAttributesForPicture.srcset = generateSrcset(lowsrc); + imgAttributesForPicture.sizes = imgAttributes.sizes; + } + + children.push({ + "img": imgAttributesForPicture + }); + + return { + "picture": { + ...pictureAttributes, + [CHILDREN_OBJECT_KEY]: children, + } + }; +} + +function mapObjectToHTML(tagName, attrs = {}) { + let attrHtml = Object.entries(attrs).map(entry => { + let [key, value] = entry; + if(key === CHILDREN_OBJECT_KEY) { + return false; + } + + // Issue #82 + if(key === "alt") { + return `${key}="${value ? escapeAttribute(value) : ""}"`; + } + + return `${key}="${value}"`; + }).filter(keyPair => Boolean(keyPair)).join(" "); + + return `<${tagName}${attrHtml ? ` ${attrHtml}` : ""}>`; +} + +function generateHTML(metadata, attributes = {}, htmlOptionsOverride = {}) { + let htmlOptions = Object.assign({}, metadata?.eleventyImage?.htmlOptions, htmlOptionsOverride); + + let isInline = htmlOptions.whitespaceMode !== "block"; + let markup = []; + + // htmlOptions.imgAttributes and htmlOptions.pictureAttributes are merged in generateObject + let obj = generateObject(metadata, attributes, {}, { htmlOptions }); + for(let tag in obj) { + markup.push(mapObjectToHTML(tag, obj[tag])); + + // + if(Array.isArray(obj[tag]?.[CHILDREN_OBJECT_KEY])) { + for(let child of obj[tag][CHILDREN_OBJECT_KEY]) { + let childTagName = Object.keys(child)[0]; + markup.push((!isInline ? " " : "") + mapObjectToHTML(childTagName, child[childTagName])); + } + + markup.push(``); + } + } + return markup.join(!isInline ? "\n" : ""); +} + +module.exports = generateHTML; +module.exports.generateObject = generateObject; diff --git a/node_modules/@11ty/eleventy-img/src/global-options.js b/node_modules/@11ty/eleventy-img/src/global-options.js new file mode 100644 index 0000000..70f8bee --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/global-options.js @@ -0,0 +1,121 @@ +const path = require("node:path"); +const os = require("node:os"); + +const Util = require("./util.js"); +const svgHook = require("./format-hooks/svg.js"); + +const DEFAULTS = { + widths: ["auto"], + formats: ["webp", "jpeg"], // "png", "svg", "avif" + + formatFiltering: ["transparent", "animated"], + + // Via https://github.com/11ty/eleventy-img/issues/258 + concurrency: Math.min(Math.max(8, os.availableParallelism()), 16), + + urlPath: "/img/", + outputDir: "img/", + + // true to skip raster formats if SVG input is found + // "size" to skip raster formats if larger than SVG input + svgShortCircuit: false, + svgAllowUpscale: true, + svgCompressionSize: "", // "br" to report SVG `size` property in metadata as Brotli compressed + // overrideInputFormat: false, // internal, used to force svg output in statsSync et al + sharpOptions: {}, // options passed to the Sharp constructor + sharpWebpOptions: {}, // options passed to the Sharp webp output method + sharpPngOptions: {}, // options passed to the Sharp png output method + sharpJpegOptions: {}, // options passed to the Sharp jpeg output method + sharpAvifOptions: {}, // options passed to the Sharp avif output method + + formatHooks: { + svg: svgHook, + }, + + cacheDuration: "1d", // deprecated, use cacheOptions.duration + + // disk cache for remote assets + cacheOptions: { + // duration: "1d", + // directory: ".cache", + // removeUrlQueryParams: false, + // fetchOptions: {}, + }, + + filenameFormat: null, + + // urlFormat allows you to return a full URL to an image including the domain. + // Useful when you’re using your own hosted image service (probably via .statsSync or .statsByDimensionsSync) + // Note: when you use this, metadata will not include .filename or .outputPath + urlFormat: null, + + // If true, skips all image processing, just return stats. Doesn’t read files, doesn’t write files. + // Important to note that `dryRun: true` performs image processing and includes a buffer—this does not. + // Useful when used with `urlFormat` above. + // Better than .statsSync* functions, because this will use the in-memory cache and de-dupe requests. Those will not. + statsOnly: false, + remoteImageMetadata: {}, // For `statsOnly` remote images, this needs to be populated with { width, height, format? } + + useCache: true, // in-memory and disk cache + dryRun: false, // Also returns a buffer instance in the return object. Doesn’t write anything to the file system + + hashLength: 10, // Truncates the hash to this length + + fixOrientation: false, // always rotate images to ensure correct orientation + + // When the original width is smaller than the desired output width, this is the minimum size difference + // between the next smallest image width that will generate one extra width in the output. + // e.g. when using `widths: [400, 800]`, the source image would need to be at least (400 * 1.25 =) 500px wide + // to generate two outputs (400px, 500px). If the source image is less than 500px, only one output will + // be generated (400px). + // Read more at https://github.com/11ty/eleventy-img/issues/184 and https://github.com/11ty/eleventy-img/pull/190 + minimumThreshold: 1.25, + + // During --serve mode in Eleventy, this will generate images on request instead of part of the build skipping + // writes to the file system and speeding up builds! + transformOnRequest: false, + + // operate on Sharp instance manually. + transform: undefined, + + // return HTML from generateHTML directly + returnType: "object", // or "html" + + // Defaults used when generateHTML is called from a result set + htmlOptions: { + imgAttributes: {}, + pictureAttributes: {}, + + whitespaceMode: "inline", // "block" + + // the will use the largest dimensions for width/height (when multiple output widths are specified) + // see https://github.com/11ty/eleventy-img/issues/63 + fallback: "largest", // or "smallest" + }, + + // v5.0.0 Removed `extensions`, option to override output format with new file extension. It wasn’t being used anywhere or documented. + // v6.0.0, removed `useCacheValidityInHash: true` see https://github.com/11ty/eleventy-img/issues/146#issuecomment-2555741376 +}; + +function getGlobalOptions(eleventyConfig, options, via) { + let directories = eleventyConfig.directories; + let globalOptions = Object.assign({ + packages: { + image: require("../"), + }, + outputDir: path.join(directories.output, options.urlPath || ""), + failOnError: true, + }, options); + + globalOptions.directories = directories; + globalOptions.generatedVia = via; + + Util.addConfig(eleventyConfig, globalOptions); + + return globalOptions; +} + +module.exports = { + getGlobalOptions, + defaults: DEFAULTS, +}; diff --git a/node_modules/@11ty/eleventy-img/src/image-attrs-to-posthtml-node.js b/node_modules/@11ty/eleventy-img/src/image-attrs-to-posthtml-node.js new file mode 100644 index 0000000..55b41b1 --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/image-attrs-to-posthtml-node.js @@ -0,0 +1,140 @@ +const eleventyImage = require("../img.js"); +const Util = require("./util.js"); + +const ATTR_PREFIX = "eleventy:"; + +const CHILDREN_OBJECT_KEY = "@children"; + +const ATTR = { + IGNORE: `${ATTR_PREFIX}ignore`, + WIDTHS: `${ATTR_PREFIX}widths`, + FORMATS: `${ATTR_PREFIX}formats`, + OUTPUT: `${ATTR_PREFIX}output`, + OPTIONAL: `${ATTR_PREFIX}optional`, + PICTURE: `${ATTR_PREFIX}pictureattr:`, +}; + +function getPictureAttributesFromImgNode(attrs = {}) { + let pictureAttrs = {}; + for(let key in attrs) { + // hoists to ` + // e.g. hoists to + if(key.startsWith(ATTR.PICTURE)) { + pictureAttrs[key.slice(ATTR.PICTURE.length)] = attrs[key]; + } + } + return pictureAttrs; +} + +function convertToPosthtmlNode(obj) { + // node.tag + // node.attrs + // node.content + + let node = {}; + let [key] = Object.keys(obj); + node.tag = key; + + let children = obj[key]?.[CHILDREN_OBJECT_KEY]; + let attributes = {}; + for(let attrKey in obj[key]) { + if(attrKey !== CHILDREN_OBJECT_KEY) { + attributes[attrKey] = obj[key][attrKey]; + } + } + node.attrs = attributes; + + if(Array.isArray(children)) { + node.content = obj[key]?.[CHILDREN_OBJECT_KEY] + .filter(child => Boolean(child)) + .map(child => { + return convertToPosthtmlNode(child); + }); + } + + return node; +} + +function isValidSimpleWidthAttribute(width) { + // `width` must be a single integer (not comma separated). Don’t use invalid HTML in width attribute. Use eleventy:widths if you want more complex support + return (""+width) == (""+parseInt(width, 10)); +} + +async function imageAttributesToPosthtmlNode(attributes, instanceOptions, globalPluginOptions) { + if(!attributes.src) { + throw new Error("Missing `src` attribute for `@11ty/eleventy-img`"); + } + + if(!globalPluginOptions) { + throw new Error("Missing global defaults for `@11ty/eleventy-img`: did you call addPlugin?"); + } + + if(!instanceOptions) { + instanceOptions = {}; + } + + // overrides global widths + if(attributes.width && isValidSimpleWidthAttribute(attributes.width)) { + // Support `width` but only single value + instanceOptions.widths = [ parseInt(attributes.width, 10) ]; + } else if(attributes[ATTR.WIDTHS] && typeof attributes[ATTR.WIDTHS] === "string") { + instanceOptions.widths = attributes[ATTR.WIDTHS].split(",").map(entry => parseInt(entry, 10)); + } + + if(attributes[ATTR.FORMATS] && typeof attributes[ATTR.FORMATS] === "string") { + instanceOptions.formats = attributes[ATTR.FORMATS].split(","); + } + + let options = Object.assign({}, globalPluginOptions, instanceOptions); + Util.addConfig(globalPluginOptions.eleventyConfig, options); + + let metadata = await eleventyImage(attributes.src, options); + let pictureAttributes = getPictureAttributesFromImgNode(attributes); + + cleanAttrs(attributes); + + // You bet we throw an error on missing alt in `imageAttributes` (alt="" works okay) + let obj = await eleventyImage.generateObject(metadata, attributes, pictureAttributes, options); + return convertToPosthtmlNode(obj); +} + +function cleanAttrs(attrs = {}) { + for(let key in attrs) { + if(key.startsWith(ATTR_PREFIX)) { + delete attrs?.[key]; + } + } +} + +function cleanTag(node) { + // Delete all prefixed attributes + cleanAttrs(node?.attrs); +} + +function isIgnored(node) { + return node?.attrs && node?.attrs?.[ATTR.IGNORE] !== undefined; +} + +function isOptional(node, comparisonValue) { + let attrValue = node?.attrs && node?.attrs?.[ATTR.OPTIONAL]; + if(attrValue !== undefined) { + // if comparisonValue is not specified, return true + if(comparisonValue === undefined) { + return true; + } + return attrValue === comparisonValue; + } + return false; +} + +function getOutputDirectory(node) { + return node?.attrs?.[ATTR.OUTPUT]; +} + +module.exports = { + imageAttributesToPosthtmlNode, + cleanTag, + isIgnored, + isOptional, + getOutputDirectory, +}; diff --git a/node_modules/@11ty/eleventy-img/src/image-path.js b/node_modules/@11ty/eleventy-img/src/image-path.js new file mode 100644 index 0000000..1a875c7 --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/image-path.js @@ -0,0 +1,30 @@ +const path = require("node:path"); + +class ImagePath { + static filenameFormat(id, src, width, format) { // and options + if (width) { + return `${id}-${width}.${format}`; + } + + return `${id}.${format}`; + } + + static getFilename(id, src, width, format, options = {}) { + if (typeof options.filenameFormat === "function") { + let filename = options.filenameFormat(id, src, width, format, options); + // if options.filenameFormat returns falsy, use fallback filename + if(filename) { + return filename; + } + } + + return ImagePath.filenameFormat(id, src, width, format, options); + } + + static convertFilePathToUrl(dir, filename) { + let src = path.join(dir, filename); + return src.split(path.sep).join("/"); + } +} + +module.exports = ImagePath; diff --git a/node_modules/@11ty/eleventy-img/src/image.js b/node_modules/@11ty/eleventy-img/src/image.js new file mode 100644 index 0000000..0f01861 --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/image.js @@ -0,0 +1,930 @@ +const fs = require("node:fs"); +const fsp = fs.promises; +const path = require("node:path"); +const getImageSize = require("image-size"); +const debugUtil = require("debug"); + +const { createHashSync } = require("@11ty/eleventy-utils"); +const { Fetch } = require("@11ty/eleventy-fetch"); + +const sharp = require("./adapters/sharp.js"); +const brotliSize = require("./adapters/brotli-size.js"); +const Util = require("./util.js"); +const ImagePath = require("./image-path.js"); +const generateHTML = require("./generate-html.js"); + +const GLOBAL_OPTIONS = require("./global-options.js").defaults; +const { existsCache, memCache, diskCache } = require("./caches.js"); + +const debug = debugUtil("Eleventy:Image"); +const debugAssets = debugUtil("Eleventy:Assets"); + +const MIME_TYPES = { + "jpeg": "image/jpeg", + "webp": "image/webp", + "png": "image/png", + "svg": "image/svg+xml", + "avif": "image/avif", + "gif": "image/gif", +}; + +const FORMAT_ALIASES = { + "jpg": "jpeg", + // if you’re working from a mime type input, let’s alias it back to svg + "svg+xml": "svg", +}; + +const ANIMATED_TYPES = [ + "webp", + "gif", +]; + +const TRANSPARENCY_TYPES = [ + "avif", + "png", + "webp", + "gif", + "svg", +]; + +const MINIMUM_TRANSPARENCY_TYPES = [ + "png", + "gif", + "svg", +]; + +class Image { + #input; + #contents = {}; + #queue; + #queuePromise; + #buildLogger; + #computedHash; + #directoryManager; + + constructor(src, options = {}) { + if(!src) { + throw new Error("`src` is a required argument to the eleventy-img utility (can be a String file path, String URL, or Buffer)."); + } + + this.src = src; + this.isRemoteUrl = typeof src === "string" && Util.isRemoteUrl(src); + + this.rawOptions = options; + this.options = Object.assign({}, GLOBAL_OPTIONS, options); + + // Compatible with eleventy-dev-server and Eleventy 3.0.0-alpha.7+ in serve mode. + if(this.options.transformOnRequest && !this.options.urlFormat) { + this.options.urlFormat = function({ src, width, format }/*, imageOptions*/, options) { + return `/.11ty/image/?src=${encodeURIComponent(src)}&width=${width}&format=${format}${options.generatedVia ? `&via=${options.generatedVia}` : ""}`; + }; + + this.options.statsOnly = true; + } + + if(this.isRemoteUrl) { + this.cacheOptions = Object.assign({ + type: "buffer", + // deprecated in Eleventy Image, but we already prefer this.cacheOptions.duration automatically + duration: this.options.cacheDuration, + // Issue #117: re-use eleventy-img dryRun option value for eleventy-fetch dryRun + dryRun: this.options.dryRun, + }, this.options.cacheOptions); + + // v6.0.0 this now inherits eleventy-fetch option defaults + this.assetCache = Fetch(src, this.cacheOptions); + } + } + + setQueue(queue) { + this.#queue = queue; + } + + setBuildLogger(buildLogger) { + this.#buildLogger = buildLogger; + } + + setDirectoryManager(manager) { + this.#directoryManager = manager; + } + + get directoryManager() { + if(!this.#directoryManager) { + throw new Error("Missing #directoryManager"); + } + + return this.#directoryManager; + } + + get buildLogger() { + if(!this.#buildLogger) { + throw new Error("Missing #buildLogger. Call `setBuildLogger`"); + } + return this.#buildLogger; + } + + // In memory cache is up front, handles promise de-duping from input (this does not use getHash) + // Note: output cache is also in play below (uses getHash) + getInMemoryCacheKey() { + let opts = Util.getSortedObject(this.options); + + opts.__originalSrc = this.src; + + if(this.isRemoteUrl) { + opts.sourceUrl = this.src; // the source url + } else if(Buffer.isBuffer(this.src)) { + opts.sourceUrl = this.src.toString(); + opts.__originalSize = this.src.length; + } else { + // Important: do not cache this + opts.__originalSize = fs.statSync(this.src).size; + } + + return JSON.stringify(opts, function(key, value) { + // allows `transform` functions to be truthy for in-memory key + if (typeof value === "function") { + return "" + (value.name || ""); + } + return value; + }); + } + + getFileContents(overrideLocalFilePath) { + if(!overrideLocalFilePath && this.isRemoteUrl) { + return false; + } + + let src = overrideLocalFilePath || this.src; + + if(!this.#contents[src]) { + // perf: check to make sure it’s not a string first + if(typeof src !== "string" && Buffer.isBuffer(src)) { + this.#contents[src] = src; + } else { + debugAssets("[11ty/eleventy-img] Reading %o", src); + this.#contents[src] = fs.readFileSync(src); + } + } + + // Always + return this.#contents[src]; + } + + static getValidWidths(originalWidth, widths = [], allowUpscale = false, minimumThreshold = 1) { + // replace any falsy values with the original width + let valid = widths.map(width => !width || width === 'auto' ? originalWidth : width); + + // Convert strings to numbers, "400" (floats are not allowed in sharp) + valid = valid.map(width => parseInt(width, 10)); + + // Replace any larger-than-original widths with the original width if upscaling is not allowed. + // This ensures that if a larger width has been requested, we're at least providing the closest + // non-upscaled image that we can. + if (!allowUpscale) { + let lastWidthWasBigEnough = true; // first one is always valid + valid = valid.sort((a, b) => a - b).map(width => { + if(width > originalWidth) { + if(lastWidthWasBigEnough) { + return originalWidth; + } + return -1; + } + + lastWidthWasBigEnough = originalWidth > Math.floor(width * minimumThreshold); + + return width; + }).filter(width => width > 0); + } + + // Remove duplicates (e.g., if null happens to coincide with an explicit width + // or a user passes in multiple duplicate values, or multiple larger-than-original + // widths have resulted in the original width being included multiple times) + valid = [...new Set(valid)]; + + // sort ascending + return valid.sort((a, b) => a - b); + } + + static getFormatsArray(formats, autoFormat, svgShortCircuit, isAnimated, hasTransparency) { + if(formats && formats.length) { + if(typeof formats === "string") { + formats = formats.split(","); + } + + formats = formats.map(format => { + if(autoFormat) { + if((!format || format === "auto")) { + format = autoFormat; + } + } + + if(FORMAT_ALIASES[format]) { + return FORMAT_ALIASES[format]; + } + return format; + }); + + if(svgShortCircuit !== "size") { + // svg must come first for possible short circuiting + formats.sort((a, b) => { + if(a === "svg") { + return -1; + } else if(b === "svg") { + return 1; + } + return 0; + }); + } + + if(isAnimated) { + let validAnimatedFormats = formats.filter(f => ANIMATED_TYPES.includes(f)); + // override formats if a valid animated format is found, otherwise leave as-is + if(validAnimatedFormats.length > 0) { + debug("Filtering non-animated formats from output: from %o to %o", formats, validAnimatedFormats); + formats = validAnimatedFormats; + } else { + debug("No animated output formats found for animated image, using original formats (may be a static image): %o", formats); + } + } + + if(hasTransparency) { + let minimumValidTransparencyFormats = formats.filter(f => MINIMUM_TRANSPARENCY_TYPES.includes(f)); + // override formats if a valid animated format is found, otherwise leave as-is + if(minimumValidTransparencyFormats.length > 0) { + let validTransparencyFormats = formats.filter(f => TRANSPARENCY_TYPES.includes(f)); + debug("Filtering non-transparency-friendly formats from output: from %o to %o", formats, validTransparencyFormats); + formats = validTransparencyFormats; + } else { + debug("At least one transparency-friendly output format of %o must be included if the source image has an alpha channel, skipping formatFiltering and using original formats: %o", MINIMUM_TRANSPARENCY_TYPES, formats); + } + } + + // Remove duplicates (e.g., if null happens to coincide with an explicit format + // or a user passes in multiple duplicate values) + formats = [...new Set(formats)]; + + return formats; + } + + return []; + } + + #transformRawFiles(files = []) { + let byType = {}; + for(let file of files) { + if(!byType[file.format]) { + byType[file.format] = []; + } + byType[file.format].push(file); + } + for(let type in byType) { + // sort by width, ascending (for `srcset`) + byType[type].sort((a, b) => { + return a.width - b.width; + }); + } + + let filterLargeRasterImages = this.options.svgShortCircuit === "size"; + let svgEntry = byType.svg; + let svgSize = svgEntry && svgEntry.length && svgEntry[0].size; + + if(filterLargeRasterImages && svgSize) { + for(let type of Object.keys(byType)) { + if(type === "svg") { + continue; + } + + let svgAdded = false; + let originalFormatKept = false; + byType[type] = byType[type].map(entry => { + if(entry.size > svgSize) { + if(!svgAdded) { + svgAdded = true; + // need at least one raster smaller than SVG to do this trick + if(originalFormatKept) { + return svgEntry[0]; + } + // all rasters are bigger + return false; + } + + return false; + } + + originalFormatKept = true; + return entry; + }).filter(entry => entry); + } + } + + return byType; + } + + #finalizeResults(results = {}) { + // used when results are passed to generate HTML, we maintain some internal metadata about the options used. + let imgAttributes = this.options.htmlOptions?.imgAttributes || {}; + imgAttributes.src = this.src; + + Object.defineProperty(results, "eleventyImage", { + enumerable: false, + writable: false, + value: { + htmlOptions: { + whitespaceMode: this.options.htmlOptions?.whitespaceMode, + imgAttributes, + pictureAttributes: this.options.htmlOptions?.pictureAttributes, + fallback: this.options.htmlOptions?.fallback, + }, + } + }); + + // renamed `return` to `returnType` to match Fetch API in v6.0.0-beta.3 + if(this.options.returnType === "html" || this.options.return === "html") { + return generateHTML(results); + } + + return results; + } + + getSharpOptionsForFormat(format) { + if(format === "webp") { + return this.options.sharpWebpOptions; + } else if(format === "jpeg") { + return this.options.sharpJpegOptions; + } else if(format === "png") { + return this.options.sharpPngOptions; + } else if(format === "avif") { + return this.options.sharpAvifOptions; + } + return {}; + } + + async getInput() { + // internal cache + if(!this.#input) { + if(this.isRemoteUrl) { + // fetch remote image Buffer + this.#input = this.assetCache.queue(); + } else { + // not actually a promise, this is sync + this.#input = this.getFileContents(); + } + } + + return this.#input; + } + + getHash() { + if (this.#computedHash) { + return this.#computedHash; + } + + // debug("Creating hash for %o", this.src); + let hashContents = []; + + if(existsCache.exists(this.src)) { + let fileContents = this.getFileContents(); + + // If the file starts with whitespace or the '<' character, it might be SVG. + // Otherwise, skip the expensive buffer.toString() call + // (no point in unicode encoding a binary file) + let fileContentsPrefix = fileContents?.slice(0, 1)?.toString()?.trim(); + if (!fileContentsPrefix || fileContentsPrefix[0] == "<") { + // remove all newlines for hashing for better cross-OS hash compatibility (Issue #122) + let fileContentsStr = fileContents.toString(); + let firstFour = fileContentsStr.trim().slice(0, 5); + if(firstFour === "8 as 1 (normal) but check anyways + return orientation >= 5 && orientation <= 8; + } + + isAnimated(metadata) { + // sharp options have animated image support enabled + if(!this.options?.sharpOptions?.animated) { + return false; + } + + let isAnimationFriendlyFormat = ANIMATED_TYPES.includes(metadata.format); + if(!isAnimationFriendlyFormat) { + return false; + } + + if(metadata?.pages) { + // input has multiple pages: https://sharp.pixelplumbing.com/api-input#metadata + // this is *unknown* when not called from `resize` (limited metadata available) + return metadata?.pages > 1; + } + + // Best guess + return isAnimationFriendlyFormat; + } + + getEntryFormat(metadata) { + return metadata.format || this.options.overrideInputFormat; + } + + // metadata so far: width, height, format + // src is used to calculate the output file names + getFullStats(metadata) { + let results = []; + let isImageAnimated = this.isAnimated(metadata) && Array.isArray(this.options.formatFiltering) && this.options.formatFiltering.includes("animated"); + let hasAlpha = metadata.hasAlpha && Array.isArray(this.options.formatFiltering) && this.options.formatFiltering.includes("transparent"); + let entryFormat = this.getEntryFormat(metadata); + let outputFormats = Image.getFormatsArray(this.options.formats, entryFormat, this.options.svgShortCircuit, isImageAnimated, hasAlpha); + + if (this.needsRotation(metadata.orientation)) { + [metadata.height, metadata.width] = [metadata.width, metadata.height]; + } + + if(metadata.pageHeight) { + // When the { animated: true } option is provided to sharp, animated + // image formats like gifs or webp will have an inaccurate `height` value + // in their metadata which is actually the height of every single frame added together. + // In these cases, the metadata will contain an additional `pageHeight` property which + // is the height that the image should be displayed at. + metadata.height = metadata.pageHeight; + } + + for(let outputFormat of outputFormats) { + if(!outputFormat || outputFormat === "auto") { + throw new Error("When using statsSync or statsByDimensionsSync, `formats: [null | 'auto']` to use the native image format is not supported."); + } + + if(outputFormat === "svg") { + if(entryFormat === "svg") { + let svgStats = this.getStat("svg", metadata.width, metadata.height); + + // SVG metadata.size is only available with Buffer input (remote urls) + if(metadata.size) { + // Note this is unfair for comparison with raster formats because its uncompressed (no GZIP, etc) + svgStats.size = metadata.size; + } + results.push(svgStats); + + if(this.options.svgShortCircuit === true) { + break; + } else { + continue; + } + } else { + debug("Skipping SVG output for %o: received raster input.", this.src); + continue; + } + } else { // not outputting SVG (might still be SVG input though!) + let widths = Image.getValidWidths(metadata.width, this.options.widths, metadata.format === "svg" && this.options.svgAllowUpscale, this.options.minimumThreshold); + for(let width of widths) { + let height = Image.getAspectRatioHeight(metadata, width); + + results.push(this.getStat(outputFormat, width, height)); + } + } + } + + return this.#transformRawFiles(results); + } + + static getDimensionsFromSharp(sharpInstance, stat) { + let dims = {}; + if(sharpInstance.options.width > -1) { + dims.width = sharpInstance.options.width; + dims.resized = true; + } + if(sharpInstance.options.height > -1) { + dims.height = sharpInstance.options.height; + dims.resized = true; + } + + if(dims.width || dims.height) { + if(!dims.width) { + dims.width = Image.getAspectRatioWidth(stat, dims.height); + } + if(!dims.height) { + dims.height = Image.getAspectRatioHeight(stat, dims.width); + } + } + + return dims; + } + + static getAspectRatioWidth(originalDimensions, newHeight) { + return Math.floor(newHeight * originalDimensions.width / originalDimensions.height); + } + + static getAspectRatioHeight(originalDimensions, newWidth) { + // Warning: if this is a guess via statsByDimensionsSync and that guess is wrong + // The aspect ratio will be wrong and any height/widths returned will be wrong! + return Math.floor(newWidth * originalDimensions.height / originalDimensions.width); + } + + getOutputSize(contents, filePath) { + if(contents) { + if(this.options.svgCompressionSize === "br") { + return brotliSize(contents); + } + + if("length" in contents) { + return contents.length; + } + } + + // fallback to looking on local file system + if(!filePath) { + throw new Error("`filePath` expected."); + } + + return fs.statSync(filePath).size; + } + + isOutputCached(targetFile, sourceInput) { + if(!this.options.useCache) { + return false; + } + + // last cache was a miss, so we must write to disk + if(this.assetCache && !this.assetCache.wasLastFetchCacheHit()) { + return false; + } + + if(!diskCache.isCached(targetFile, sourceInput, !Util.isRequested(this.options.generatedVia))) { + return false; + } + + return true; + } + + // src should be a file path to an image or a buffer + async resize(input) { + let sharpInputImage = sharp(input, Object.assign({ + // Deprecated by sharp, use `failOn` option instead + // https://github.com/lovell/sharp/blob/1533bf995acda779313fc178d2b9d46791349961/lib/index.d.ts#L915 + failOnError: false, + }, this.options.sharpOptions)); + + // Must find the image format from the metadata + // File extensions lie or may not be present in the src url! + let sharpMetadata = await sharpInputImage.metadata(); + + let outputFilePromises = []; + + let fullStats = this.getFullStats(sharpMetadata); + + for(let outputFormat in fullStats) { + for(let stat of fullStats[outputFormat]) { + if(this.isOutputCached(stat.outputPath, input)) { + // Cached images already exist in output + let outputFileContents; + + if(this.options.dryRun || outputFormat === "svg" && this.options.svgCompressionSize === "br") { + outputFileContents = this.getFileContents(stat.outputPath); + } + + if(this.options.dryRun) { + stat.buffer = outputFileContents; + } + + stat.size = this.getOutputSize(outputFileContents, stat.outputPath); + + outputFilePromises.push(Promise.resolve(stat)); + continue; + } + + let sharpInstance = sharpInputImage.clone(); + let transform = this.options.transform; + let isTransformResize = false; + + if(transform) { + if(typeof transform !== "function") { + throw new Error("Expected `function` type in `transform` option. Received: " + transform); + } + + await transform(sharpInstance); + + // Resized in a transform (maybe for a crop) + let dims = Image.getDimensionsFromSharp(sharpInstance, stat); + if(dims.resized) { + isTransformResize = true; + + // Overwrite current `stat` object with new sizes and file names + stat = this.getStat(stat.format, dims.width, dims.height); + } + } + + // https://github.com/11ty/eleventy-img/issues/244 + sharpInstance.keepIccProfile(); + + // Output images do not include orientation metadata (https://github.com/11ty/eleventy-img/issues/52) + // Use sharp.rotate to bake orientation into the image (https://github.com/lovell/sharp/blob/v0.32.6/docs/api-operation.md#rotate): + // > If no angle is provided, it is determined from the EXIF data. Mirroring is supported and may infer the use of a flip operation. + // > The use of rotate without an angle will remove the EXIF Orientation tag, if any. + if(this.options.fixOrientation || this.needsRotation(sharpMetadata.orientation)) { + sharpInstance.rotate(); + } + + if(!isTransformResize) { + if(stat.width < sharpMetadata.width || (this.options.svgAllowUpscale && sharpMetadata.format === "svg")) { + let resizeOptions = { + width: stat.width + }; + + if(sharpMetadata.format !== "svg" || !this.options.svgAllowUpscale) { + resizeOptions.withoutEnlargement = true; + } + + sharpInstance.resize(resizeOptions); + } + } + + // Format hooks take priority over Sharp processing. + // format hooks are only used for SVG out of the box + if(this.options.formatHooks && this.options.formatHooks[outputFormat]) { + let hookResult = await this.options.formatHooks[outputFormat].call(stat, sharpInstance); + if(hookResult) { + stat.size = this.getOutputSize(hookResult); + + if(this.options.dryRun) { + stat.buffer = Buffer.from(hookResult); + + outputFilePromises.push(Promise.resolve(stat)); + } else { + this.directoryManager.createFromFile(stat.outputPath); + + debugAssets("[11ty/eleventy-img] Writing %o", stat.outputPath); + + outputFilePromises.push(fsp.writeFile(stat.outputPath, hookResult).then(() => stat)); + } + } + } else { // not a format hook + let sharpFormatOptions = this.getSharpOptionsForFormat(outputFormat); + let hasFormatOptions = Object.keys(sharpFormatOptions).length > 0; + if(hasFormatOptions || outputFormat && sharpMetadata.format !== outputFormat) { + // https://github.com/lovell/sharp/issues/3680 + // Fix heic regression in sharp 0.33 + if(outputFormat === "heic" && !sharpFormatOptions.compression) { + sharpFormatOptions.compression = "av1"; + } + sharpInstance.toFormat(outputFormat, sharpFormatOptions); + } + + if(!this.options.dryRun && stat.outputPath) { + // Should never write when dryRun is true + this.directoryManager.createFromFile(stat.outputPath); + + debugAssets("[11ty/eleventy-img] Writing %o", stat.outputPath); + + outputFilePromises.push( + sharpInstance.toFile(stat.outputPath) + .then(info => { + stat.size = info.size; + return stat; + }) + ); + } else { + outputFilePromises.push(sharpInstance.toBuffer({ resolveWithObject: true }).then(({ data, info }) => { + stat.buffer = data; + stat.size = info.size; + return stat; + })); + } + } + + if(stat.outputPath) { + if(this.options.dryRun) { + debug( "Generated %o", stat.url ); + } else { + debug( "Wrote %o", stat.outputPath ); + } + } + } + } + + return Promise.all(outputFilePromises).then(files => this.#finalizeResults(this.#transformRawFiles(files))); + } + + async getStatsOnly() { + if(typeof this.src !== "string" || !this.options.statsOnly) { + return; + } + + let input; + if(Util.isRemoteUrl(this.src)) { + if(this.rawOptions.remoteImageMetadata?.width && this.rawOptions.remoteImageMetadata?.height) { + return this.getFullStats({ + width: this.rawOptions.remoteImageMetadata.width, + height: this.rawOptions.remoteImageMetadata.height, + format: this.rawOptions.remoteImageMetadata.format, // only required if you want to use the "auto" format + guess: true, + }); + } + + // Fetch remote image to operate on it + // `remoteImageMetadata` is no longer required for statsOnly on remote images + input = await this.getInput(); + } + + // Local images + try { + // Related to https://github.com/11ty/eleventy-img/issues/295 + let { width, height, type } = getImageSize(input || this.src); + + return this.getFullStats({ + width, + height, + format: type // only required if you want to use the "auto" format + }); + } catch(e) { + throw new Error(`Eleventy Image error (statsOnly): \`image-size\` on "${this.src}" failed. Original error: ${e.message}`); + } + } + + // returns raw Promise + queue() { + if(!this.#queue) { + return Promise.reject(new Error("Missing #queue.")); + } + + if(this.#queuePromise) { + return this.#queuePromise; + } + + debug("Processing %o (in-memory cache miss), options: %o", this.src, this.options); + + this.#queuePromise = this.#queue.add(async () => { + try { + if(typeof this.src === "string" && this.options.statsOnly) { + return this.getStatsOnly(); + } + + this.buildLogger.log(`Processing ${this.buildLogger.getFriendlyImageSource(this.src)}`, this.options); + + let input = await this.getInput(); + + return this.resize(input); + } catch(e) { + this.buildLogger.error(`Error: ${e.message} (via ${this.buildLogger.getFriendlyImageSource(this.src)})`, this.options); + + if(this.options.failOnError) { + throw e; + } + } + }); + + return this.#queuePromise; + } + + // Factory to return from cache if available + static create(src, options = {}) { + let img = new Image(src, options); + + // use resolved options for this + if(!img.options.useCache) { + return img; + } + + let key = img.getInMemoryCacheKey(); + let cached = memCache.get(key, !options.transformOnRequest && !Util.isRequested(options.generatedVia)); + if(cached) { + return cached; + } + + memCache.add(key, img); + + return img; + } + + /* `statsSync` doesn’t generate any files, but will tell you where + * the asynchronously generated files will end up! This is useful + * in synchronous-only template environments where you need the + * image URLs synchronously but can’t rely on the files being in + * the correct location yet. + * + * `options.dryRun` is still asynchronous but also doesn’t generate + * any files. + */ + statsSync() { + if(this.isRemoteUrl) { + throw new Error("`statsSync` is not supported with remote sources. Use `statsByDimensionsSync(src, width, height, options)` instead."); + } + + let dimensions = getImageSize(this.src); + + return this.getFullStats({ + width: dimensions.width, + height: dimensions.height, + format: dimensions.type, + }); + } + + static statsSync(src, opts) { + if(typeof src === "string" && Util.isRemoteUrl(src)) { + throw new Error("`statsSync` is not supported with remote sources. Use `statsByDimensionsSync(src, width, height, options)` instead."); + } + + let img = Image.create(src, opts); + return img.statsSync(); + } + + statsByDimensionsSync(width, height) { + let dimensions = { + width, + height, + guess: true + }; + return this.getFullStats(dimensions); + } + + static statsByDimensionsSync(src, width, height, opts) { + let img = Image.create(src, opts); + return img.statsByDimensionsSync(width, height); + } +} + +module.exports = Image; diff --git a/node_modules/@11ty/eleventy-img/src/memory-cache.js b/node_modules/@11ty/eleventy-img/src/memory-cache.js new file mode 100644 index 0000000..3ff63c0 --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/memory-cache.js @@ -0,0 +1,54 @@ +const debug = require("debug")("Eleventy:Image"); + +class MemoryCache { + constructor() { + this.cache = {}; + this.hitCounter = 0; + this.missCounter = 0; + } + + resetCount() { + this.hitCounter = 0; + this.missCounter = 0; + } + + getCount() { + return [this.hitCounter, this.missCounter]; + } + + add(key, results) { + this.cache[key] = { + results + }; + + debug("Unique images processed: %o", this.size()); + } + + get(key, incrementCounts = false) { + if(this.cache[key]) { + if(incrementCounts) { + this.hitCounter++; + } + // debug("Images re-used (via in-memory cache): %o", this.hitCounter); + + // may return promise + return this.cache[key].results; + } + + if(incrementCounts) { + this.missCounter++; + } + + return false; + } + + has(key) { + return key in this.cache; + } + + size() { + return Object.keys(this.cache).length; + } +} + +module.exports = MemoryCache; diff --git a/node_modules/@11ty/eleventy-img/src/on-request-during-serve-plugin.js b/node_modules/@11ty/eleventy-img/src/on-request-during-serve-plugin.js new file mode 100644 index 0000000..30e707d --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/on-request-during-serve-plugin.js @@ -0,0 +1,105 @@ +const fs = require("node:fs"); +const { TemplatePath } = require("@11ty/eleventy-utils"); + +const eleventyImage = require("../img.js"); +const setupLogger = eleventyImage.setupLogger; +const Util = require("./util.js"); + +const debug = require("debug")("Eleventy:Image"); + +function eleventyImageOnRequestDuringServePlugin(eleventyConfig, options = {}) { + try { + // Throw an error if the application is not using Eleventy 3.0.0-alpha.7 or newer (including prereleases). + eleventyConfig.versionCheck(">=3.0.0-alpha.7"); + } catch(e) { + console.log( `[11ty/eleventy-img] Warning: your version of Eleventy is incompatible with the dynamic image rendering plugin (see \`eleventyImageOnRequestDuringServePlugin\`). Any dynamically rendered images will 404 (be missing) during --serve mode but will not affect the standard build output: ${e.message}` ); + } + + setupLogger(eleventyConfig, {}); + + // Eleventy 3.0 or newer only. + eleventyConfig.setServerOptions({ + onRequest: { + // TODO work with dev-server’s option for `injectedScriptsFolder` + "/.11ty/image/": async function({ url }) { + // src could be file path or full url + let src = url.searchParams.get("src"); + let imageFormat = url.searchParams.get("format"); + let width = parseInt(url.searchParams.get("width"), 10); + let via = url.searchParams.get("via"); + + let defaultOptions; + if(via === "webc") { + defaultOptions = eleventyConfig.getFilter("__private_eleventyImageConfigurationOptions")(); + } else if(via === "transform") { + defaultOptions = eleventyConfig.getFilter("__private_eleventyImageTransformConfigurationOptions")(); + } + // if using this plugin directly (not via webc or transform), global default options will need to be passed in to the `addPlugin` call directly + + // Prefer options passed to this plugin, fallback to Transform plugin or WebC options if the image source was generated via those options. + let opts = Object.assign({}, defaultOptions, options, { + widths: [width || "auto"], + formats: [imageFormat || "auto"], + + dryRun: true, + cacheOptions: { + // We *do* want to write files to .cache for re-use here. + dryRun: false + }, + + transformOnRequest: false, // use the built images so we don’t go in a loop + generatedVia: Util.KEYS.requested, + }); + + Util.addConfig(eleventyConfig, opts); + + debug( `%o transformed on request to %o at %o width.`, src, imageFormat, width ); + + try { + if(!Util.isFullUrl(src)) { + // Image path on file system must be in working directory + src = TemplatePath.absolutePath(".", src); + + if(!fs.existsSync(src) || !src.startsWith(TemplatePath.absolutePath("."))) { + throw new Error(`Invalid path: ${src}`); + } + } + + let stats = await eleventyImage(src, opts); + + let format = Object.keys(stats).pop(); + let stat = stats[format][0]; + if(!stat) { + throw new Error("Invalid image format."); + } + if(!stat.buffer) { + throw new Error("Could not find `buffer` property for image."); + } + + return { + headers: { + // TODO Set cache headers to match eleventy-fetch cache options (though remote fetchs are still written to .cache) + "Content-Type": stat.sourceType, + }, + body: stat.buffer, + }; + } catch (error) { + debug("Error attempting to transform %o: %O", src, error); + + return { + status: 500, + headers: { + "Content-Type": "image/svg+xml", + "x-error-message": error.message + }, + body: ``, + }; + } + } + } + }); +} + +module.exports = { + eleventyImageOnRequestDuringServePlugin, +}; diff --git a/node_modules/@11ty/eleventy-img/src/transform-plugin.js b/node_modules/@11ty/eleventy-img/src/transform-plugin.js new file mode 100644 index 0000000..959dca0 --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/transform-plugin.js @@ -0,0 +1,210 @@ +const path = require("node:path"); +const Util = require("./util.js"); +const { imageAttributesToPosthtmlNode, getOutputDirectory, cleanTag, isIgnored, isOptional } = require("./image-attrs-to-posthtml-node.js"); +const { getGlobalOptions } = require("./global-options.js"); +const { eleventyImageOnRequestDuringServePlugin } = require("./on-request-during-serve-plugin.js"); + +const PLACEHOLDER_DATA_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgYAAAAAMAASsJTYQAAAAASUVORK5CYII="; + +const ATTRS = { + ORIGINAL_SOURCE: "eleventy:internal_original_src", +}; + +function getSrcAttributeValue(sourceNode/*, rootTargetNode*/) { + // Debatable TODO: use rootTargetNode (if `picture`) to retrieve a potentially higher quality source from + return sourceNode.attrs?.src; +} + +function assignAttributes(rootTargetNode, newNode) { + // only copy attributes if old and new tag name are the same (picture => picture, img => img) + if(rootTargetNode.tag !== newNode.tag) { + delete rootTargetNode.attrs; + } + + if(!rootTargetNode.attrs) { + rootTargetNode.attrs = {}; + } + + // Copy all new attributes to target + if(newNode.attrs) { + Object.assign(rootTargetNode.attrs, newNode.attrs); + } +} + +function getOutputLocations(originalSource, outputDirectoryFromAttribute, pageContext, options) { + let projectOutputDirectory = options.directories.output; + + if(outputDirectoryFromAttribute) { + if(path.isAbsolute(outputDirectoryFromAttribute)) { + return { + outputDir: path.join(projectOutputDirectory, outputDirectoryFromAttribute), + urlPath: outputDirectoryFromAttribute, + }; + } + return { + outputDir: path.join(projectOutputDirectory, pageContext.url, outputDirectoryFromAttribute), + urlPath: path.join(pageContext.url, outputDirectoryFromAttribute), + }; + } + + if(options.urlPath) { + // do nothing, user has specified directories in the plugin options. + return {}; + } + + if(path.isAbsolute(originalSource)) { + // if the path is an absolute one (relative to the content directory) write to a global output directory to avoid duplicate writes for identical source images. + return { + outputDir: path.join(projectOutputDirectory, "/img/"), + urlPath: "/img/", + }; + } + + // If original source is a relative one, this colocates images to the template output. + let dir = path.dirname(pageContext.outputPath); + + // filename is included in url: ./dir/post.html => /dir/post.html + if(pageContext.outputPath.endsWith(pageContext.url)) { + // remove file name + let split = pageContext.url.split("/"); + split[split.length - 1] = ""; + + return { + outputDir: dir, + urlPath: split.join("/"), + }; + } + + // filename is not included in url: ./dir/post/index.html => /dir/post/ + return { + outputDir: dir, + urlPath: pageContext.url, + }; +} + +function transformTag(context, sourceNode, rootTargetNode, opts) { + let originalSource = getSrcAttributeValue(sourceNode, rootTargetNode); + + if(!originalSource) { + return sourceNode; + } + + let { inputPath } = context.page; + + sourceNode.attrs.src = Util.normalizeImageSource({ + input: opts.directories.input, + inputPath, + }, originalSource, { + isViaHtml: true, // this reference came from HTML, so we can decode the file name + }); + + if(sourceNode.attrs.src !== originalSource) { + sourceNode.attrs[ATTRS.ORIGINAL_SOURCE] = originalSource; + } + + let outputDirectoryFromAttribute = getOutputDirectory(sourceNode); + let instanceOptions = getOutputLocations(originalSource, outputDirectoryFromAttribute, context.page, opts); + + // returns promise + return imageAttributesToPosthtmlNode(sourceNode.attrs, instanceOptions, opts).then(newNode => { + // node.tag + // node.attrs + // node.content + + assignAttributes(rootTargetNode, newNode); + + rootTargetNode.tag = newNode.tag; + rootTargetNode.content = newNode.content; + }, (error) => { + if(isOptional(sourceNode) || !opts.failOnError) { + if(isOptional(sourceNode, "keep")) { + // replace with the original source value, no image transformation is taking place + if(sourceNode.attrs[ATTRS.ORIGINAL_SOURCE]) { + sourceNode.attrs.src = sourceNode.attrs[ATTRS.ORIGINAL_SOURCE]; + } + // leave as-is, likely 404 when a user visits the page + } else if(isOptional(sourceNode, "placeholder")) { + // transparent png + sourceNode.attrs.src = PLACEHOLDER_DATA_URI; + } else if(isOptional(sourceNode)) { + delete sourceNode.attrs.src; + } + + // optional or don’t fail on error + cleanTag(sourceNode); + + return Promise.resolve(); + } + + return Promise.reject(error); + }); +} + +function eleventyImageTransformPlugin(eleventyConfig, options = {}) { + options = Object.assign({ + extensions: "html", + transformOnRequest: process.env.ELEVENTY_RUN_MODE === "serve", + }, options); + + if(options.transformOnRequest !== false) { + // Add the on-request plugin automatically (unless opt-out in this plugins options only) + eleventyConfig.addPlugin(eleventyImageOnRequestDuringServePlugin); + } + + // Notably, global options are not shared automatically with the WebC `eleventyImagePlugin` above. + // Devs can pass in the same object to both if they want! + let opts = getGlobalOptions(eleventyConfig, options, "transform"); + + eleventyConfig.addJavaScriptFunction("__private_eleventyImageTransformConfigurationOptions", () => { + return opts; + }); + + function posthtmlPlugin(context) { + return async (tree) => { + let promises = []; + let match = tree.match; + + tree.match({ tag: 'picture' }, pictureNode => { + match.call(pictureNode, { tag: 'img' }, imgNode => { + imgNode._insideOfPicture = true; + + if(!isIgnored(imgNode) && !imgNode?.attrs?.src?.startsWith("data:")) { + promises.push(transformTag(context, imgNode, pictureNode, opts)); + } + + return imgNode; + }); + + return pictureNode; + }); + + tree.match({ tag: 'img' }, (imgNode) => { + if(imgNode._insideOfPicture) { + delete imgNode._insideOfPicture; + } else if(isIgnored(imgNode) || imgNode?.attrs?.src?.startsWith("data:")) { + cleanTag(imgNode); + } else { + promises.push(transformTag(context, imgNode, imgNode, opts)); + } + + return imgNode; + }); + + await Promise.all(promises); + + return tree; + }; + } + + if(!eleventyConfig.htmlTransformer || !("addPosthtmlPlugin" in eleventyConfig.htmlTransformer)) { + throw new Error("[@11ty/eleventy-img] `eleventyImageTransformPlugin` is not compatible with this version of Eleventy. You will need to use v3.0.0 or newer."); + } + + eleventyConfig.htmlTransformer.addPosthtmlPlugin(options.extensions, posthtmlPlugin, { + priority: -1, // we want this to go before or inputpath to url + }); +} + +module.exports = { + eleventyImageTransformPlugin, +}; diff --git a/node_modules/@11ty/eleventy-img/src/util.js b/node_modules/@11ty/eleventy-img/src/util.js new file mode 100644 index 0000000..cf59faf --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/util.js @@ -0,0 +1,78 @@ +const path = require("node:path"); + +class Util { + static KEYS = { + requested: "requested" + }; + + /* + * Does not mutate, returns new Object. + */ + static getSortedObject(unordered) { + let keys = Object.keys(unordered).sort(); + let obj = {}; + for(let key of keys) { + obj[key] = unordered[key]; + } + return obj; + } + + static isRemoteUrl(url) { + try { + const validUrl = new URL(url); + + if (validUrl.protocol.startsWith("https:") || validUrl.protocol.startsWith("http:")) { + return true; + } + + return false; + // eslint-disable-next-line no-unused-vars + } catch(e) { + // invalid url OR local path + return false; + } + } + + static normalizeImageSource({ input, inputPath }, src, options = {}) { + let { isViaHtml } = Object.assign({ + isViaHtml: false + }, options); + + if(Util.isFullUrl(src)) { + return src; + } + + if(isViaHtml) { + src = decodeURIComponent(src); + } + + if(!path.isAbsolute(src)) { + // if the image src is relative, make it relative to the template file (inputPath); + let dir = path.dirname(inputPath); + return path.join(dir, src); + } + + // if the image src is absolute, make it relative to the input/content directory. + return path.join(input, src); + } + + static isRequested(generatedVia) { + return generatedVia === this.KEYS.requested; + } + + static addConfig(eleventyConfig, options) { + if(!eleventyConfig) { + return; + } + + Object.defineProperty(options, "eleventyConfig", { + value: eleventyConfig, + enumerable: false, + }); + } +} + +// Temporary alias for changes made in https://github.com/11ty/eleventy-img/pull/138 +Util.isFullUrl = Util.isRemoteUrl; + +module.exports = Util; diff --git a/node_modules/@11ty/eleventy-img/src/webc-options-plugin.js b/node_modules/@11ty/eleventy-img/src/webc-options-plugin.js new file mode 100644 index 0000000..1fbfde3 --- /dev/null +++ b/node_modules/@11ty/eleventy-img/src/webc-options-plugin.js @@ -0,0 +1,23 @@ +const { getGlobalOptions } = require("./global-options.js"); +const { eleventyImageOnRequestDuringServePlugin } = require("./on-request-during-serve-plugin.js"); + +function eleventyWebcOptionsPlugin(eleventyConfig, options = {}) { + options = Object.assign({ + transformOnRequest: process.env.ELEVENTY_RUN_MODE === "serve", + }, options); + + // Notably, global options are not shared automatically with the `eleventyImageTransformPlugin` below. + // Devs can pass in the same object to both if they want! + eleventyConfig.addJavaScriptFunction("__private_eleventyImageConfigurationOptions", () => { + return getGlobalOptions(eleventyConfig, options, "webc"); + }); + + if(options.transformOnRequest !== false) { + // Add the on-request plugin automatically (unless opt-out in this plugins options only) + eleventyConfig.addPlugin(eleventyImageOnRequestDuringServePlugin); + } +} + +module.exports = { + eleventyWebcOptionsPlugin, +}; diff --git a/node_modules/@11ty/eleventy-navigation/.eleventy.js b/node_modules/@11ty/eleventy-navigation/.eleventy.js new file mode 100644 index 0000000..20b9141 --- /dev/null +++ b/node_modules/@11ty/eleventy-navigation/.eleventy.js @@ -0,0 +1,26 @@ +const pkg = require("./package.json"); +const EleventyNavigation = require("./eleventy-navigation"); + +// export the configuration function for plugin +module.exports = function(eleventyConfig) { + try { + eleventyConfig.versionCheck(pkg["11ty"].compatibility); + } catch(e) { + console.log( `WARN: Eleventy Plugin (${pkg.name}) Compatibility: ${e.message}` ); + } + + eleventyConfig.addFilter("eleventyNavigation", EleventyNavigation.findNavigationEntries); + eleventyConfig.addFilter("eleventyNavigationBreadcrumb", EleventyNavigation.findBreadcrumbEntries); + eleventyConfig.addFilter("eleventyNavigationToHtml", function(pages, options) { + return EleventyNavigation.toHtml.call(eleventyConfig, pages, options); + }); + eleventyConfig.addFilter("eleventyNavigationToMarkdown", function(pages, options) { + return EleventyNavigation.toMarkdown.call(eleventyConfig, pages, options); + }); +}; + +module.exports.navigation = { + find: EleventyNavigation.findNavigationEntries, + findBreadcrumbs: EleventyNavigation.findBreadcrumbEntries, + getDependencyGraph: EleventyNavigation.getDependencyGraph, +}; \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-navigation/.github/workflows/ci.yml b/node_modules/@11ty/eleventy-navigation/.github/workflows/ci.yml new file mode 100644 index 0000000..03f969e --- /dev/null +++ b/node_modules/@11ty/eleventy-navigation/.github/workflows/ci.yml @@ -0,0 +1,22 @@ +name: Node Unit Tests +on: [push, pull_request] +permissions: read-all +jobs: + build: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: ["ubuntu-latest", "macos-latest", "windows-latest"] + node: ["18", "20", "22", "24"] + name: Node.js ${{ matrix.node }} on ${{ matrix.os }} + steps: + - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # 4.1.7 + - name: Setup node + uses: actions/setup-node@1e60f620b9541d16bece96c5465dc8ee9832be0b # 4.0.3 + with: + node-version: ${{ matrix.node }} + # cache: npm + - run: npm install + - run: npm test +env: + YARN_GPG: no diff --git a/node_modules/@11ty/eleventy-navigation/.github/workflows/release.yml b/node_modules/@11ty/eleventy-navigation/.github/workflows/release.yml new file mode 100644 index 0000000..594770a --- /dev/null +++ b/node_modules/@11ty/eleventy-navigation/.github/workflows/release.yml @@ -0,0 +1,25 @@ +name: Publish Release to npm +on: + release: + types: [published] +permissions: read-all +jobs: + build: + runs-on: ubuntu-latest + environment: GitHub Publish + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # 4.1.7 + - uses: actions/setup-node@1e60f620b9541d16bece96c5465dc8ee9832be0b # 4.0.3 + with: + node-version: "22" + registry-url: 'https://registry.npmjs.org' + - run: npm install -g npm@latest + - run: npm ci + - run: npm test + - if: ${{ github.event.release.tag_name != '' && env.NPM_PUBLISH_TAG != '' }} + run: npm publish --provenance --access=public --tag=${{ env.NPM_PUBLISH_TAG }} + env: + NPM_PUBLISH_TAG: ${{ contains(github.event.release.tag_name, '-beta.') && 'beta' || 'latest' }} diff --git a/node_modules/@11ty/eleventy-navigation/LICENSE b/node_modules/@11ty/eleventy-navigation/LICENSE new file mode 100644 index 0000000..37922a8 --- /dev/null +++ b/node_modules/@11ty/eleventy-navigation/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019–2025 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-navigation/README.md b/node_modules/@11ty/eleventy-navigation/README.md new file mode 100644 index 0000000..7475fc8 --- /dev/null +++ b/node_modules/@11ty/eleventy-navigation/README.md @@ -0,0 +1,9 @@ +

11ty Logo

+ +# eleventy-navigation 🕚⚡️🎈🐀 + +A plugin for creating hierarchical navigation in Eleventy projects. Supports breadcrumbs too! + +Used [in production on 11ty.dev](https://www.11ty.dev/docs/)! + +## Read the [Full Documentation on 11ty.dev](https://www.11ty.dev/docs/plugins/navigation/) diff --git a/node_modules/@11ty/eleventy-navigation/eleventy-navigation.js b/node_modules/@11ty/eleventy-navigation/eleventy-navigation.js new file mode 100644 index 0000000..d361d93 --- /dev/null +++ b/node_modules/@11ty/eleventy-navigation/eleventy-navigation.js @@ -0,0 +1,277 @@ +const DepGraph = require("dependency-graph").DepGraph; + +function findNavigationEntries(nodes = [], key = "") { + let keys = key.split(",").filter(k => Boolean(k)); + let pages = {}; + for(let entry of nodes) { + let data = entry?.data || {}; + if(data?.eleventyNavigation) { + let {eleventyNavigation} = data || {}; + + let pageKey; + if(!key && !eleventyNavigation.parent) { // top level (no parents) + pageKey = "__default"; + } else if(keys.includes(eleventyNavigation.parent)) { + pageKey = eleventyNavigation.parent; + } + + if(pageKey) { + if(!pages[pageKey]) { + pages[pageKey] = []; + } + let url = eleventyNavigation.url ?? data?.page?.url; + + pages[pageKey].push(Object.assign({ data }, eleventyNavigation, { + ...(url ? { url } : {}), + pluginType: "eleventy-navigation", + ...(keys.length > 0 ? { parentKey: eleventyNavigation.parent } : {}), + })); + } + } + } + + return Object.values(pages).flat().sort(function(a, b) { + if(a.pinned && b.pinned) { + return (a.order || 0) - (b.order || 0); + } + + let order = [a.order, b.order]; + if(a.pinned) { + order[0] = -Infinity; + } + if(b.pinned) { + order[1] = -Infinity; + } + + if(order[0] === undefined && order[1] === undefined) { + return 0; + } + if(order[1] === undefined) { + return -1; + } + if(order[0] === undefined) { + return 1; + } + return order[0] - order[1]; + }).map(function(entry) { + if(!entry.title) { + entry.title = entry.key; + } + if(entry.key) { + entry.children = findNavigationEntries(nodes, entry.key); + } + return entry; + }); +} + +function findDependencies(pages, depGraph, parentKey) { + for( let page of pages ) { + depGraph.addNode(page.key, page); + if(parentKey) { + depGraph.addDependency(page.key, parentKey); + } + if(page.children) { + findDependencies(page.children, depGraph, page.key); + } + } +} + +function getDependencyGraph(nodes) { + let pages = findNavigationEntries(nodes); + let graph = new DepGraph(); + findDependencies(pages, graph); + return graph; +} + +function isOptionMatch(options, name) { + // Liquid.js issue #35 + if(Array.isArray(options)) { + return options[options.indexOf(name)] + } + return options[name]; +} + +function findBreadcrumbEntries(nodes, activeKey, options = {}) { + let graph = getDependencyGraph(nodes); + if (isOptionMatch(options, "allowMissing") && !graph.hasNode(activeKey)) { + // Fail gracefully if the key isn't in the graph + return []; + } + let deps = graph.dependenciesOf(activeKey); + if(isOptionMatch(options, "includeSelf")) { + deps.push(activeKey); + } + + return activeKey ? deps.map(key => { + let data = Object.assign({}, graph.getNodeData(key)); + delete data.children; + data._isBreadcrumb = true; + return data; + }) : []; +} + +function getUrlFilter(eleventyConfig) { + // eleventyConfig.pathPrefix was first available in Eleventy 2.0.0-canary.15 + // And in Eleventy 2.0.0-canary.15 we recommend the a built-in transform for pathPrefix + if(eleventyConfig.pathPrefix !== undefined) { + return function(url) { + return url; + }; + } + + if("getFilter" in eleventyConfig) { + // v0.10.0 and above + return eleventyConfig.getFilter("url"); + } else if("nunjucksFilters" in eleventyConfig) { + // backwards compat, hardcoded key + return eleventyConfig.nunjucksFilters.url; + } else { + // Theoretically we could just move on here with a `url => url` but then `pathPrefix` + // would not work and it wouldn’t be obvious why—so let’s fail loudly to avoid that. + throw new Error("Could not find a `url` filter for the eleventy-navigation plugin in eleventyNavigationToHtml filter."); + } +} + +function buildHtmlAttr(name, values) { + // values could be array or string + if (!values || !values.length) { + return ''; + } + const valueStr = Array.isArray(values) ? values.join(" ") : values; + return ` ${name}="${valueStr}"`; +} + +function buildAllHtmlAttrs(attrs) { + return attrs.reduce((acc, { name, values }) => acc + buildHtmlAttr(name, values), ''); +} + +function navigationToHtml(pages, options = {}) { + options = Object.assign({ + listElement: "ul", + listItemElement: "li", + listClass: "", + listItemClass: "", + listItemHasChildrenClass: "", + activeKey: "", + activeListItemClass: "", + anchorClass: "", + activeAnchorClass: "", + useAriaCurrentAttr: false, + showExcerpt: false, + isChildList: false, + useTopLevelDetails: false, + anchorElementWithoutHref: "a", // default, better to use span + }, options); + + let isChildList = !!options.isChildList; + options.isChildList = true; + + let urlFilter; + + if(pages.length && pages[0].pluginType !== "eleventy-navigation") { + throw new Error("Incorrect argument passed to eleventyNavigationToHtml filter. You must call `eleventyNavigation` or `eleventyNavigationBreadcrumb` first, like: `collection.all | eleventyNavigation | eleventyNavigationToHtml | safe`"); + } + + return pages.length ? `<${options.listElement}${!isChildList && options.listClass ? ` class="${options.listClass}"` : ''}>${pages.map(entry => { + let liClass = []; + let aClass = []; + let aAttrs = []; + if(options.listItemClass) { + liClass.push(options.listItemClass); + } + if(options.anchorClass) { + aClass.push(options.anchorClass); + } + if(entry.url) { + if(!urlFilter) { + // don’t get if not used + urlFilter = getUrlFilter(this); + } + aAttrs.push({name: "href", values: urlFilter(entry.url)}) + } + if(options.activeKey === entry.key) { + if(options.activeListItemClass) { + liClass.push(options.activeListItemClass); + } + if(options.activeAnchorClass) { + aClass.push(options.activeAnchorClass); + } + if(options.useAriaCurrentAttr) { + aAttrs.push({ name: "aria-current", values: "page" }); + } + } + if(options.listItemHasChildrenClass && entry.children && entry.children.length) { + liClass.push(options.listItemHasChildrenClass); + } + if(aClass.length) { + aAttrs.push({ name: "class", values: aClass }); + } + + let postfix = ""; + + // Helper to show pin/order in text: + // let hasOrder = entry.order || entry.order === 0; + // if(process.env.ELEVENTY_RUN_MODE === "serve" && (hasOrder || entry.pinned)) { + // postfix = ` (${entry.pinned ? "📌" : ""}${entry.order ?? ""})`; + // } + + let aAttrsStr = buildAllHtmlAttrs(aAttrs); + let hasLink = aAttrs.find(entry => entry.name === "href"); + let itemTitle = entry.title + postfix; + + let titleHtmlStart = `${itemTitle}`; + + // purely defensive use of `useTopLevelDetails` here + if(options.anchorElementWithoutHref && !hasLink) { + titleHtmlStart = `<${options.anchorElementWithoutHref}>${itemTitle}`; + } + + let titleHtmlEnd = ""; + if(options.useTopLevelDetails && !isChildList && entry.children) { + if(hasLink) { + // `` must be sibling: no other interactive elements in + titleHtmlStart = `${titleHtmlStart}
${itemTitle}`; + } else { + titleHtmlStart = `
${itemTitle}`; + } + titleHtmlEnd = "
"; + } + + let childContentStr = entry.children ? navigationToHtml.call(this, entry.children, options) : ""; + + return `<${options.listItemElement}${buildHtmlAttr("class", liClass)}>${titleHtmlStart}${options.showExcerpt && entry.excerpt ? `: ${entry.excerpt}` : ""}${childContentStr}${titleHtmlEnd}`; + }).join("\n")}` : ""; +} + +function navigationToMarkdown(pages, options = {}) { + options = Object.assign({ + showExcerpt: false, + childDepth: 0 + }, options); + + let childDepth = 1 + options.childDepth; + options.childDepth++; + + let urlFilter; + + if(pages.length && pages[0].pluginType !== "eleventy-navigation") { + throw new Error("Incorrect argument passed to eleventyNavigationToMarkdown filter. You must call `eleventyNavigation` or `eleventyNavigationBreadcrumb` first, like: `collection.all | eleventyNavigation | eleventyNavigationToMarkdown | safe`"); + } + + let indent = (new Array(childDepth)).join(" ") || ""; + return pages.length ? `${pages.map(entry => { + if(entry.url && !urlFilter) { + // don’t get if not used + urlFilter = getUrlFilter(this); + } + return `${indent}* ${entry.url ? `[` : ""}${entry.title}${entry.url ? `](${urlFilter(entry.url)})` : ""}${options.showExcerpt && entry.excerpt ? `: ${entry.excerpt}` : ""}\n${entry.children ? navigationToMarkdown.call(this, entry.children, options) : ""}`; + }).join("")}` : ""; +} + +module.exports = { + getDependencyGraph, + findNavigationEntries, + findBreadcrumbEntries, + toHtml: navigationToHtml, + toMarkdown: navigationToMarkdown +}; \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-navigation/package.json b/node_modules/@11ty/eleventy-navigation/package.json new file mode 100644 index 0000000..5d020c9 --- /dev/null +++ b/node_modules/@11ty/eleventy-navigation/package.json @@ -0,0 +1,49 @@ +{ + "name": "@11ty/eleventy-navigation", + "version": "1.0.5", + "publishConfig": { + "access": "public" + }, + "description": "A plugin for creating hierarchical navigation in Eleventy projects. Supports breadcrumbs too!", + "main": ".eleventy.js", + "scripts": { + "test": "npx ava", + "sample": "npx @11ty/eleventy --input=sample --output=sample/_site --config=sample/.eleventy.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/11ty/eleventy-navigation.git" + }, + "bugs": { + "url": "https://github.com/11ty/eleventy-navigation/issues" + }, + "homepage": "https://www.11ty.dev/docs/plugins/navigation/", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/11ty" + }, + "keywords": [ + "eleventy", + "eleventy-plugin" + ], + "author": { + "name": "Zach Leatherman", + "email": "zachleatherman@gmail.com", + "url": "https://zachleat.com/" + }, + "license": "MIT", + "11ty": { + "compatibility": ">=0.7 || >=1.0.0-canary" + }, + "devDependencies": { + "ava": "^6.4.1" + }, + "dependencies": { + "dependency-graph": "^1.0.0" + }, + "ava": { + "files": [ + "./test/*.js" + ] + } +} diff --git a/node_modules/@11ty/eleventy-navigation/sample/.eleventy.js b/node_modules/@11ty/eleventy-navigation/sample/.eleventy.js new file mode 100644 index 0000000..8ffc704 --- /dev/null +++ b/node_modules/@11ty/eleventy-navigation/sample/.eleventy.js @@ -0,0 +1,9 @@ +const EleventyNavigationPlugin = require("../"); + +module.exports = function(eleventyConfig) { + eleventyConfig.addPlugin(EleventyNavigationPlugin); + + return { + pathPrefix: "/sdljfkaldsjlfka/" + } +}; \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-navigation/sample/bats.md b/node_modules/@11ty/eleventy-navigation/sample/bats.md new file mode 100644 index 0000000..b024399 --- /dev/null +++ b/node_modules/@11ty/eleventy-navigation/sample/bats.md @@ -0,0 +1,5 @@ +--- +eleventyNavigation: + key: Bats + parent: Mammals +--- \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-navigation/sample/humans.md b/node_modules/@11ty/eleventy-navigation/sample/humans.md new file mode 100644 index 0000000..2f323ba --- /dev/null +++ b/node_modules/@11ty/eleventy-navigation/sample/humans.md @@ -0,0 +1,5 @@ +--- +eleventyNavigation: + key: Humans + parent: Mammals +--- \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-navigation/sample/liquid/index.liquid b/node_modules/@11ty/eleventy-navigation/sample/liquid/index.liquid new file mode 100644 index 0000000..3fd6c74 --- /dev/null +++ b/node_modules/@11ty/eleventy-navigation/sample/liquid/index.liquid @@ -0,0 +1,19 @@ +

Full List

+ +{{ collections.all | eleventyNavigation | dump(2) }} + +{{ collections.all | eleventyNavigation | eleventyNavigationToHtml }} + +

Breadcrumb for Bats

+ +{{ + collections.all + | eleventyNavigationBreadcrumb: "Bats" + | dump(2) +}} + +{{ + collections.all + | eleventyNavigationBreadcrumb: "Bats" + | eleventyNavigationToHtml +}} diff --git a/node_modules/@11ty/eleventy-navigation/sample/mammals.md b/node_modules/@11ty/eleventy-navigation/sample/mammals.md new file mode 100644 index 0000000..f3d7ca8 --- /dev/null +++ b/node_modules/@11ty/eleventy-navigation/sample/mammals.md @@ -0,0 +1,4 @@ +--- +eleventyNavigation: + key: Mammals +--- \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-navigation/sample/no-key.md b/node_modules/@11ty/eleventy-navigation/sample/no-key.md new file mode 100644 index 0000000..69fb2c2 --- /dev/null +++ b/node_modules/@11ty/eleventy-navigation/sample/no-key.md @@ -0,0 +1,4 @@ +--- +eleventyNavigation: +--- +This page has no key. \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-navigation/sample/no-nav.md b/node_modules/@11ty/eleventy-navigation/sample/no-nav.md new file mode 100644 index 0000000..586ff35 --- /dev/null +++ b/node_modules/@11ty/eleventy-navigation/sample/no-nav.md @@ -0,0 +1,3 @@ +--- +--- +This page has no navigation. \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-navigation/sample/nunjucks/index.njk b/node_modules/@11ty/eleventy-navigation/sample/nunjucks/index.njk new file mode 100644 index 0000000..327dc3c --- /dev/null +++ b/node_modules/@11ty/eleventy-navigation/sample/nunjucks/index.njk @@ -0,0 +1,11 @@ +

Full List

+ +{{ collections.all | eleventyNavigation | dump(2) | safe }} + +{{ collections.all | eleventyNavigation | eleventyNavigationToHtml | safe }} + +

Breadcrumb for Bats

+ +{{ collections.all | eleventyNavigationBreadcrumb("Bats") | dump(2) | safe }} + +{{ collections.all | eleventyNavigationBreadcrumb("Bats") | eleventyNavigationToHtml | safe }} \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-navigation/test/navigationTest.js b/node_modules/@11ty/eleventy-navigation/test/navigationTest.js new file mode 100644 index 0000000..6c5d080 --- /dev/null +++ b/node_modules/@11ty/eleventy-navigation/test/navigationTest.js @@ -0,0 +1,747 @@ +const test = require("ava"); +const EleventyNavigation = require("../eleventy-navigation"); + +test("Empty navigation", t => { + t.deepEqual(EleventyNavigation.findNavigationEntries(), []); +}); + +test("One root page navigation", t => { + let obj = EleventyNavigation.findNavigationEntries([ + { + data: { + eleventyNavigation: { + key: "root1" + }, + page: { + url: "root1.html" + } + } + } + ]); + t.is(obj[0].key, "root1"); + t.is(obj[0].pluginType, "eleventy-navigation"); + + // Warning, title must be preserved per the public API + t.is(obj[0].title, "root1"); + // Warning, url must be preserved per the public API + t.is(obj[0].url, "root1.html"); + + t.is(obj[0].children.length, 0); +}); + +test("One root page navigation with separate title", t => { + let obj = EleventyNavigation.findNavigationEntries([ + { + data: { + eleventyNavigation: { + key: "root1", + title: "Another title" + }, + page: { + url: "root1.html" + } + } + } + ]); + t.is(obj[0].key, "root1"); + t.is(obj[0].pluginType, "eleventy-navigation"); + t.is(obj[0].title, "Another title"); + t.is(obj[0].children.length, 0); +}); + +test("One root, one child page navigation", t => { + let obj = EleventyNavigation.findNavigationEntries([ + { + data: { + eleventyNavigation: { + key: "root1" + }, + page: { + url: "root1.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child1" + }, + page: { + url: "child1.html" + } + } + } + ]); + t.is(obj[0].key, "root1"); + t.is(obj[0].children.length, 1); + t.is(obj[0].children[0].parent, "root1"); + t.is(obj[0].children[0].key, "child1"); +}); + +test("Three layers deep navigation", t => { + let obj = EleventyNavigation.findNavigationEntries([ + { + data: { + eleventyNavigation: { + key: "root1" + }, + page: { + url: "root1.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child1" + }, + page: { + url: "child1.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "child1", + key: "grandchild1" + }, + page: { + url: "grandchild1.html" + } + } + } + ]); + t.is(obj[0].key, "root1"); + t.is(obj[0].children.length, 1); + t.is(obj[0].children[0].parent, "root1"); + t.is(obj[0].children[0].key, "child1"); + t.is(obj[0].children[0].children[0].parent, "child1"); + t.is(obj[0].children[0].children[0].key, "grandchild1"); +}); + +test("One root, three child navigation (order)", t => { + let obj = EleventyNavigation.findNavigationEntries([ + { + data: { + eleventyNavigation: { + key: "root1" + }, + page: { + url: "root1.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child1", + order: 3 + }, + page: { + url: "child1.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child2", + order: 1 + }, + page: { + url: "child2.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child3", + order: 2 + }, + page: { + url: "child3.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child4" + }, + page: { + url: "child4.html" + } + } + } + ]); + t.is(obj[0].key, "root1"); + t.is(obj[0].children.length, 4); + t.is(obj[0].children.map(e => e.key).join(","), "child2,child3,child1,child4"); +}); + +test("One root, three child navigation, one with 0 (order)", t => { + let obj = EleventyNavigation.findNavigationEntries([ + { + data: { + eleventyNavigation: { + key: "root1" + }, + page: { + url: "root1.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child1", + order: 3 + }, + page: { + url: "child1.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child2", + order: 0 + }, + page: { + url: "child2.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child3", + order: 2 + }, + page: { + url: "child3.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child4" + }, + page: { + url: "child4.html" + } + } + } + ]); + t.is(obj[0].key, "root1"); + t.is(obj[0].children.length, 4); + t.is(obj[0].children.map(e => e.key).join(","), "child2,child3,child1,child4"); +}); + +test("One root, three child navigation (implied order)", t => { + let obj = EleventyNavigation.findNavigationEntries([ + { + data: { + eleventyNavigation: { + key: "root1" + }, + page: { + url: "root1.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child1", + order: 3 + }, + page: { + url: "child1.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child2" + }, + page: { + url: "child2.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child3", + order: -1 + }, + page: { + url: "child3.html" + } + } + } + ]); + t.is(obj[0].key, "root1"); + t.is(obj[0].children.length, 3); + t.is(obj[0].children.map(e => e.key).join(","), "child3,child1,child2"); +}); + +test("Show throw an error without a config", t => { + let obj = EleventyNavigation.findNavigationEntries([ + { + data: { + eleventyNavigation: { + key: "root1" + }, + page: { + url: "root1.html" + } + } + } + ]); + + t.throws(() => { + EleventyNavigation.toHtml(obj); + }); +}); + +let fakeConfig = { + nunjucksFilters: { + url: url => url + } +}; + +let fakeNavigationEntries = [ + { + data: { + eleventyNavigation: { + key: "root1" + }, + page: { + url: "root1.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child1" + }, + page: { + url: "child1.html" + } + } + } +]; + +let fakeNavigationEntriesEmptyUrl = [ + { + data: { + eleventyNavigation: { + key: "root1" + }, + page: { + url: "root1.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child1" + }, + page: { + url: false + } + } + } +]; + +test("Checking active class on output HTML", t => { + let obj = EleventyNavigation.findNavigationEntries(fakeNavigationEntries); + + let html = EleventyNavigation.toHtml.call(fakeConfig, obj); + t.is(html, `
`); + + let activeHtmlItem = EleventyNavigation.toHtml.call(fakeConfig, obj, { + activeKey: "child1", + activeListItemClass: "this-is-the-active-item" + }); + t.is(activeHtmlItem, ``); + + let activeHtmlAnchor = EleventyNavigation.toHtml.call(fakeConfig, obj, { + activeKey: "child1", + activeAnchorClass: "this-is-the-active-anchor" + }); + t.is(activeHtmlAnchor, ``); + + let activeHtmlItemAndAnchor = EleventyNavigation.toHtml.call(fakeConfig, obj, { + activeKey: "child1", + activeListItemClass: "this-is-the-active-item", + activeAnchorClass: "this-is-the-active-anchor" + }); + t.is(activeHtmlItemAndAnchor, ``); +}); + +test("Checking aria-current option on output HTML", t => { + let obj = EleventyNavigation.findNavigationEntries(fakeNavigationEntries); + + let html = EleventyNavigation.toHtml.call(fakeConfig, obj); + t.true(html.indexOf(`
  • child1
  • `) > -1); + + let activeHtmlAnchor = EleventyNavigation.toHtml.call(fakeConfig, obj, { + activeKey: "child1", + useAriaCurrentAttr: true + }); + t.true(activeHtmlAnchor.indexOf(`
  • child1
  • `) > -1); +}); + +test("Checking has children class on output HTML", t => { + let obj = EleventyNavigation.findNavigationEntries(fakeNavigationEntries); + + let activeHtml = EleventyNavigation.toHtml.call(fakeConfig, obj, { + listItemHasChildrenClass: "item-has-children" + }); + t.true(activeHtml.indexOf(`
  • root1`) > -1); + t.true(activeHtml.indexOf(`
  • child1
  • `) > -1); +}); + +test("URL override", t => { + let obj = EleventyNavigation.findNavigationEntries([ + { + data: { + eleventyNavigation: { + key: "root1", + url: "https://www.zachleat.com/" + }, + page: { + url: "root1.html" + } + } + } + ]); + + t.is(obj[0].url, "https://www.zachleat.com/"); +}); + +test("Breadcrumbs", t => { + let obj = EleventyNavigation.findBreadcrumbEntries([ + { + data: { + eleventyNavigation: { + key: "root1" + }, + page: { + url: "root1.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child1" + }, + page: { + url: "child1.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "child1", + key: "grandchild1" + }, + page: { + url: "grandchild1.html" + } + } + } + ], "grandchild1"); + + t.is(obj.length, 2); + t.is(obj[0].key, "root1"); + t.is(obj[1].key, "child1"); +}); + +test("Breadcrumbs (include self)", t => { + let obj = EleventyNavigation.findBreadcrumbEntries([ + { + data: { + eleventyNavigation: { + key: "root1" + }, + page: { + url: "root1.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child1" + }, + page: { + url: "child1.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "child1", + key: "grandchild1" + }, + page: { + url: "grandchild1.html" + } + } + } + ], "grandchild1", { + includeSelf: true + }); + + t.is(obj.length, 3); + t.is(obj[0].key, "root1"); + t.is(obj[1].key, "child1"); + t.is(obj[2].key, "grandchild1"); +}); + +test("Breadcrumbs (options.allowMissing)", t => { + const entries = EleventyNavigation.findBreadcrumbEntries( + [], + "orphan", + {allowMissing: true} + ); + t.is(entries.length, 0); +}); + +test("Output markdown", t => { + let obj = EleventyNavigation.findNavigationEntries([ + { + data: { + eleventyNavigation: { + key: "root1" + }, + page: { + url: "root1.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child1" + }, + page: { + url: "child1.html" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "child1", + key: "grandchild1" + }, + page: { + url: "grandchild1.html" + } + } + } + ]); + + let html = EleventyNavigation.toMarkdown.call(fakeConfig, obj); + t.is(html, `* [root1](root1.html) + * [child1](child1.html) + * [grandchild1](grandchild1.html) +`); +}); + +test("Navigation entry contains page data", t => { + let obj = EleventyNavigation.findNavigationEntries([ + { + data: { + eleventyNavigation: { + key: "root1" + }, + page: { + url: "root1.html" + }, + tags: [ + "robot", + "lesbian" + ], + collections: {} + } + } + ]); + + // Page data like tags should be included in the obj + t.deepEqual(obj[0].data.tags, ["robot", "lesbian"]); +}); + +test("Missing url", t => { + let obj = EleventyNavigation.findNavigationEntries([ + { + data: { + eleventyNavigation: { + key: "root1", + } + } + } + ]); + + t.is(EleventyNavigation.toHtml.call(fakeConfig, obj), ``); +}); + +test("Multiple roots", t => { + let obj = EleventyNavigation.findNavigationEntries([ + { + data: { + eleventyNavigation: { + key: "root1" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child1", + } + } + }, + { + data: { + eleventyNavigation: { + key: "root2" + }, + } + }, + { + data: { + eleventyNavigation: { + parent: "root2", + key: "child3", + } + } + } + ]); + + t.deepEqual(obj.map(e => e.key), ["root1", "root2"]); + t.deepEqual(obj[0].children.map(e => e.key), ["child1"]); + t.deepEqual(obj[1].children.map(e => e.key), ["child3"]); +}); + +test("Multiple roots, multiple keys", t => { + let obj = EleventyNavigation.findNavigationEntries([ + { + data: { + eleventyNavigation: { + key: "root1" + } + } + }, + { + data: { + eleventyNavigation: { + parent: "root1", + key: "child1", + } + } + }, + { + data: { + eleventyNavigation: { + key: "root2" + }, + } + }, + { + data: { + eleventyNavigation: { + parent: "root2", + key: "child3", + } + } + } + ], "root1,root2"); + + t.deepEqual(obj.map(e => e.key), ["child1", "child3"]); + t.deepEqual(obj[0].children.map(e => e.key), []); + t.deepEqual(obj[1].children.map(e => e.key), []); +}); + +test("Breadcrumb include self", t => { + let nodes = [ + { + data: { + eleventyNavigation: { + key: "root1", + } + } + } + ]; + let obj = EleventyNavigation.findBreadcrumbEntries(nodes, "root1", { includeSelf: true }); + + t.is(EleventyNavigation.toHtml(obj), ``); +}); + +test("Breadcrumb include self (Liquid.js #35)", t => { + let nodes = [ + { + data: { + eleventyNavigation: { + key: "root1", + } + } + } + ]; + let obj = EleventyNavigation.findBreadcrumbEntries(nodes, "root1", [ "includeSelf", true ]); + + t.is(EleventyNavigation.toHtml(obj), ``); +}); + +test("Use top level details", t => { + let obj = EleventyNavigation.findNavigationEntries(fakeNavigationEntries); + + let html = EleventyNavigation.toHtml.call(fakeConfig, obj, { + useTopLevelDetails: true + }); + t.is(html, ``); +}); + +test("Use top level details with empty url", t => { + let obj = EleventyNavigation.findNavigationEntries(fakeNavigationEntriesEmptyUrl); + + let html = EleventyNavigation.toHtml.call(fakeConfig, obj, { + useTopLevelDetails: true, + anchorElementWithoutHref: "span", + }); + t.is(html, ``); +}); \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-plugin-bundle/README.md b/node_modules/@11ty/eleventy-plugin-bundle/README.md new file mode 100644 index 0000000..a585831 --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/README.md @@ -0,0 +1,337 @@ +# eleventy-plugin-bundle + +Little bundles of code, little bundles of joy. + +Create minimal per-page or app-level bundles of CSS, JavaScript, or HTML to be included in your Eleventy project. + +Makes it easy to implement Critical CSS, in-use-only CSS/JS bundles, SVG icon libraries, or secondary HTML content to load via XHR. + +## Why? + +This project is a minimum-viable-bundler and asset pipeline in Eleventy. It does not perform any transpilation or code manipulation (by default). The code you put in is the code you get out (with configurable `transforms` if you’d like to modify the code). + +For more larger, more complex use cases you may want to use a more full featured bundler like Vite, Parcel, Webpack, rollup, esbuild, or others. + +But do note that a full-featured bundler has a significant build performance cost, so take care to weigh the cost of using that style of bundler against whether or not this plugin has sufficient functionality for your use case—especially as the platform matures and we see diminishing returns on code transpilation (ES modules everywhere). + +## Installation + +No installation necessary. Starting with Eleventy `v3.0.0-alpha.10` and newer, this plugin is now bundled with Eleventy. + +## Usage + +By default, Bundle Plugin v2.0 does not include any default bundles. You must add these yourself via `eleventyConfig.addBundle`. One notable exception happens when using the WebC Eleventy Plugin, which adds `css`, `js`, and `html` bundles for you. + +To create a bundle type, use `eleventyConfig.addBundle` in your Eleventy configuration file (default `.eleventy.js`): + +```js +// .eleventy.js +export default function(eleventyConfig) { + eleventyConfig.addBundle("css"); +}; +``` + +This does two things: + +1. Creates a new `css` shortcode for adding arbitrary code to this bundle +2. Adds `"css"` as an eligible type argument to the `getBundle` and `getBundleFileUrl` shortcodes. + +### Full options list + +```js +export default function(eleventyConfig) { + eleventyConfig.addBundle("css", { + // (Optional) Folder (relative to output directory) files will write to + toFileDirectory: "bundle", + + // (Optional) File extension used for bundle file output, defaults to bundle name + outputFileExtension: "css", + + // (Optional) Name of shortcode for use in templates, defaults to bundle name + shortcodeName: "css", + // shortcodeName: false, // disable this feature. + + // (Optional) Modify bundle content + transforms: [], + + // (Optional) If two identical code blocks exist in non-default buckets, they’ll be hoisted to the first bucket in common. + hoist: true, + + // (Optional) In 11ty.js templates, having a named export of `bundle` will populate your bundles. + bundleExportKey: "bundle", + // bundleExportKey: false, // disable this feature. + }); +}; +``` + +Read more about [`hoist` and duplicate bundle hoisting](https://github.com/11ty/eleventy-plugin-bundle/issues/5). + +### Universal Shortcodes + +The following Universal Shortcodes (available in `njk`, `liquid`, `hbs`, `11ty.js`, and `webc`) are provided by this plugin: + +* `getBundle` to retrieve bundled code as a string. +* `getBundleFileUrl` to create a bundle file on disk and retrieve the URL to that file. + +Here’s a [real-world commit showing this in use on the `eleventy-base-blog` project](https://github.com/11ty/eleventy-base-blog/commit/c9595d8f42752fa72c66991c71f281ea960840c9?diff=split). + +### Example: Add bundle code in a Markdown file in Eleventy + +```md +# My Blog Post + +This is some content, I am writing markup. + +{% css %} +em { font-style: italic; } +{% endcss %} + +## More Markdown + +{% css %} +strong { font-weight: bold; } +{% endcss %} +``` + +Renders to: + +```html +

    My Blog Post

    + +

    This is some content, I am writing markup.

    + +

    More Markdown

    +``` + +Note that the bundled code is excluded! + +_There are a few [more examples below](#examples)!_ + +### Render bundle code + +```html + + + + +{% css %}* { color: orange; }{% endcss %} +``` + +### Write a bundle to a file + +Writes the bundle content to a content-hashed file location in your output directory and returns the URL to the file for use like this: + +```html + +``` + +Note that writing bundles to files will likely be slower for empty-cache first time visitors but better cached in the browser for repeat-views (and across multiple pages, too). + +### Asset bucketing + +```html + +{% css "defer" %}em { font-style: italic; }{% endcss %} +``` + +```html + + + +``` + +A `default` bucket is implied: + +```html + +{% css %}em { font-style: italic; }{% endcss %} +{% css "default" %}em { font-style: italic; }{% endcss %} + + + + +``` + +### Examples + +#### Critical CSS + +```js +// .eleventy.js +export default function(eleventyConfig) { + eleventyConfig.addBundle("css"); +}; +``` + +Use asset bucketing to divide CSS between the `default` bucket and a `defer` bucket, loaded asynchronously. + +_(Note that some HTML boilerplate has been omitted from the sample below)_ + +```html + + + + + + + + + + + + {% css %}/* Inline in the head, great with @font-face! */{% endcss %} + + {% css "defer" %}/* Load me later */{% endcss %} + + +``` + +**Related**: + +* Check out the [demo of Critical CSS using Eleventy Edge](https://demo-eleventy-edge.netlify.app/critical-css/) for a repeat view optimization without JavaScript. +* You may want to improve the above code with [`fetchpriority`](https://www.smashingmagazine.com/2022/04/boost-resource-loading-new-priority-hint-fetchpriority/) when [browser support improves](https://caniuse.com/mdn-html_elements_link_fetchpriority). + +#### SVG Icon Library + +Here an `svg` is bundle is created. + +```js +// .eleventy.js +export default function(eleventyConfig) { + eleventyConfig.addBundle("svg"); +}; +``` + +```html + + + +{% svg %} + +{% endsvg %} + +And now you can use `icon-close` in as many SVG instances as you’d like (without repeating the heftier SVG content). + + + + + +``` + +#### React Helmet-style `` additions + +```js +// .eleventy.js +export default function(eleventyConfig) { + eleventyConfig.addBundle("html"); +}; +``` + +This might exist in an Eleventy layout file: + +```html + + {% getBundle "html", "head" %} + +``` + +And then in your content you might want to page-specific `preconnect`: + +```html +{% html "head" %} + +{% endhtml %} +``` + +#### Bundle Sass with the Render Plugin + +You can render template syntax inside of the `{% css %}` shortcode too, if you’d like to do more advanced things using Eleventy template types. + +This example assumes you have added the [Render plugin](https://www.11ty.dev/docs/plugins/render/) and the [`scss` custom template type](https://www.11ty.dev/docs/languages/custom/) to your Eleventy configuration file. + +```html +{% css %} + {% renderTemplate "scss" %} + h1 { .test { color: red; } } + {% endrenderTemplate %} +{% endcss %} +``` + +Now the compiled Sass is available in your default bundle and will show up in `getBundle` and `getBundleFileUrl`. + +#### Use with [WebC](https://www.11ty.dev/docs/languages/webc/) + +Starting with `@11ty/eleventy-plugin-webc@0.9.0` (track at [issue #48](https://github.com/11ty/eleventy-plugin-webc/issues/48)) this plugin is used by default in the Eleventy WebC plugin. Specifically, [WebC Bundler Mode](https://www.11ty.dev/docs/languages/webc/#css-and-js-(bundler-mode)) now uses the bundle plugin under the hood. + +To add CSS to a bundle in WebC, you would use a ` + +``` + +To add JS to a page bundle in WebC, you would use a ` + +``` + +* 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..35f571c --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/eleventy.bundle.js @@ -0,0 +1,72 @@ +import bundleManagersPlugin from "./src/eleventy.bundleManagers.js"; +import pruneEmptyBundlesPlugin from "./src/eleventy.pruneEmptyBundles.js"; +import globalShortcodesAndTransforms from "./src/eleventy.shortcodes.js"; +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:Bundle"); + +function normalizeOptions(options = {}) { + options = Object.assign({ + // Plugin defaults + + // Extra bundles + // css, js, and html are guaranteed unless `bundles: false` + bundles: [], + toFileDirectory: "bundle", + // post-process + transforms: [], + hoistDuplicateBundlesFor: [], + bundleExportKey: "bundle", // use a `bundle` export in a 11ty.js template to populate bundles + + force: false, // force overwrite of existing getBundleManagers and addBundle configuration API methods + }, options); + + if(options.bundles !== false) { + options.bundles = Array.from(new Set(["css", "js", "html", ...(options.bundles || [])])); + } + + return options; +} + +function eleventyBundlePlugin(eleventyConfig, pluginOptions = {}) { + eleventyConfig.versionCheck(">=3.0.0"); + pluginOptions = normalizeOptions(pluginOptions); + + let alreadyAdded = "getBundleManagers" in eleventyConfig || "addBundle" in eleventyConfig; + if(!alreadyAdded || pluginOptions.force) { + if(alreadyAdded && pluginOptions.force) { + debug("Bundle plugin already added via `addPlugin`, add was forced via `force: true`"); + } + + bundleManagersPlugin(eleventyConfig, pluginOptions); + } + + // These can’t be unique (don’t skip re-add above), when the configuration file resets they need to be added again + pruneEmptyBundlesPlugin(eleventyConfig, pluginOptions); + globalShortcodesAndTransforms(eleventyConfig, pluginOptions); + + // Support subsequent calls like addPlugin(BundlePlugin, { bundles: [] }); + 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: "@11ty/eleventy-plugin-bundle" +}); + +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..21c8405 --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/package.json @@ -0,0 +1,62 @@ +{ + "name": "@11ty/eleventy-plugin-bundle", + "version": "3.0.7", + "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" + }, + "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" + ], + "watchMode": { + "ignoreChanges": [ + "**/_site/**", + ".cache" + ] + } + }, + "devDependencies": { + "@11ty/eleventy": "^3.0.0", + "ava": "^6.2.0", + "postcss": "^8.5.3", + "postcss-nested": "^7.0.2", + "sass": "^1.86.3" + }, + "dependencies": { + "@11ty/eleventy-utils": "^2.0.2", + "debug": "^4.4.0", + "posthtml-match-helper": "^2.0.3" + } +} 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..332c5b7 --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/BundleFileOutput.js @@ -0,0 +1,75 @@ +import fs from "node:fs"; +import path from "node:path"; +import debugUtil from "debug"; + +import { createHash } from "@11ty/eleventy-utils"; + +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; + } + + async getFilenameHash(content) { + if(hashCache[content]) { + return hashCache[content]; + } + + let base64hash = await createHash(content); + 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("/"); + } + + async 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 = await 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..809c242 --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/CodeManager.js @@ -0,0 +1,231 @@ +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"; + this.runsAfterHtmlTransformer = false; + this.pluckedSelector = undefined; + } + + setDelayed(isDelayed) { + this.runsAfterHtmlTransformer = Boolean(isDelayed); + } + + isDelayed() { + return this.runsAfterHtmlTransformer; + } + + // posthtml-match-selector friendly + setPluckedSelector(selector) { + this.pluckedSelector = selector; + } + + getPluckedSelector() { + return this.pluckedSelector; + } + + 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); + + for(let content of codeContent) { + if(content) { + if(!this.pages[pageUrl][b].has(content)) { + debug("Adding code to bundle %o for %o (bucket: %o, size: %o): %o", this.name, pageUrl, b, content.length, content.length > DEBUG_LOG_TRUNCATION_SIZE ? content.slice(0, DEBUG_LOG_TRUNCATION_SIZE) + "…" : 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); + + let set = new Set(); + let size = 0; + 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]) { + size += entry.length; + set.add(entry); + } + } + + debug("Retrieving %o for %o (buckets: %o, entries: %o, size: %o)", this.name, url, buckets, set.size, size); + 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..6cafa49 --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/OutOfOrderRender.js @@ -0,0 +1,158 @@ +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, stage = 0) { + 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); + + // Quit early if in stage 0, run delayed replacements if in stage 1+ + if(typeof manager.isDelayed === "function" && manager.isDelayed() && stage === 0) { + return OutOfOrderRender.getAssetKey(type, name, bucket); + } + + 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/bundlePlucker.js b/node_modules/@11ty/eleventy-plugin-bundle/src/bundlePlucker.js new file mode 100644 index 0000000..5dcad46 --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/bundlePlucker.js @@ -0,0 +1,69 @@ +import debugUtil from "debug"; +import matchHelper from "posthtml-match-helper"; + +const debug = debugUtil("Eleventy:Bundle"); + +const ATTRS = { + ignore: "eleventy:ignore", + bucket: "eleventy:bucket", +}; + +const POSTHTML_PLUGIN_NAME = "11ty/eleventy/html-bundle-plucker"; + +function hasAttribute(node, name) { + return node?.attrs?.[name] !== undefined; +} + +function addHtmlPlucker(eleventyConfig, bundleManager) { + let matchSelector = bundleManager.getPluckedSelector(); + + if(!matchSelector) { + throw new Error("Internal error: missing plucked selector on bundle manager."); + } + + eleventyConfig.htmlTransformer.addPosthtmlPlugin( + "html", + function (context = {}) { + let pageUrl = context?.url; + if(!pageUrl) { + throw new Error("Internal error: missing `url` property from context."); + } + + return function (tree, ...args) { + tree.match(matchHelper(matchSelector), function (node) { + try { + // ignore + if(hasAttribute(node, ATTRS.ignore)) { + delete node.attrs[ATTRS.ignore]; + return node; + } + + if(Array.isArray(node?.content) && node.content.length > 0) { + // TODO make this better decoupled + if(node?.content.find(entry => entry.includes(`/*__EleventyBundle:`))) { + // preserve {% getBundle %} calls as-is + return node; + } + + let bucketName = node?.attrs?.[ATTRS.bucket]; + bundleManager.addToPage(pageUrl, [ ...node.content ], bucketName); + + return { attrs: [], content: [], tag: false }; + } + } catch(e) { + debug(`Bundle plucker: error adding content to bundle in HTML Assets: %o`, e); + return node; + } + + return node; + }); + }; + }, + { + // pluginOptions + name: POSTHTML_PLUGIN_NAME, + }, + ); +} + +export { addHtmlPlucker }; 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..8510abc --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.bundleManagers.js @@ -0,0 +1,85 @@ +import debugUtil from "debug"; +import { CodeManager } from "./CodeManager.js"; +import { addHtmlPlucker } from "./bundlePlucker.js" + +const debug = debugUtil("Eleventy:Bundle"); + +function eleventyBundleManagers(eleventyConfig, pluginOptions = {}) { + if(pluginOptions.force) { + // no errors + } else if(("getBundleManagers" in eleventyConfig || "addBundle" in eleventyConfig)) { + throw new Error("Duplicate addPlugin calls for @11ty/eleventy-plugin-bundle"); + } + + let managers = {}; + + function addBundle(name, bundleOptions = {}) { + if(name in managers) { + // note: shortcode must still be added + debug("Bundle exists %o, skipping.", name); + } else { + debug("Creating new bundle %o", name); + managers[name] = new CodeManager(name); + + if(bundleOptions.delayed !== undefined) { + managers[name].setDelayed(bundleOptions.delayed); + } + + if(bundleOptions.hoist !== undefined) { + managers[name].setHoisting(bundleOptions.hoist); + } + + if(bundleOptions.bundleHtmlContentFromSelector !== undefined) { + managers[name].setPluckedSelector(bundleOptions.bundleHtmlContentFromSelector); + managers[name].setDelayed(true); // must override `delayed` above + + addHtmlPlucker(eleventyConfig, managers[name]); + } + + 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..3bcaa72 --- /dev/null +++ b/node_modules/@11ty/eleventy-plugin-bundle/src/eleventy.pruneEmptyBundles.js @@ -0,0 +1,105 @@ +import matchHelper from "posthtml-match-helper"; +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:Bundle"); + +const ATTRS = { + keep: "eleventy:keep" +}; + +const POSTHTML_PLUGIN_NAME = "11ty/eleventy-bundle/prune-empty"; + +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"]`; + + // Subsequent call can remove a previously added `addPosthtmlPlugin` entry + // htmlTransformer.remove is v3.0.1-alpha.4+ + if(typeof eleventyConfig.htmlTransformer.remove === "function") { + eleventyConfig.htmlTransformer.remove("html", entry => { + if(entry.name === POSTHTML_PLUGIN_NAME) { + return true; + } + + // Temporary workaround for missing `name` property. + let fnStr = entry.fn.toString(); + return !entry.name && fnStr.startsWith("function (pluginOptions = {}) {") && fnStr.includes(`tree.match(matchHelper(options.pruneEmptySelector), function (node)`); + }); + } + + // `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 bundlePruneEmptyPosthtmlPlugin(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; + }); + }; + }, + { + name: POSTHTML_PLUGIN_NAME, + // 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..924731a --- /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"); + +export default function(eleventyConfig, pluginOptions = {}) { + let managers = eleventyConfig.getBundleManagers(); + let writeToFileSystem = true; + + function bundleTransform(content, stage = 0) { + // Only run if content is string + // Only run if managers are in play + if(typeof content !== "string" || Object.keys(managers).length === 0) { + 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, stage); + } + + eleventyConfig.on("eleventy.before", async ({ outputMode }) => { + if(Object.keys(managers).length === 0) { + return; + } + + 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)}`); + } + + 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)}`); + } + + return OutOfOrderRender.getAssetKey("file", type, bucket); + }); + + eleventyConfig.addTransform("@11ty/eleventy-bundle", function (content) { + let hasNonDelayedManagers = Boolean(Object.values(eleventyConfig.getBundleManagers()).find(manager => { + return typeof manager.isDelayed !== "function" || !manager.isDelayed(); + })); + if(hasNonDelayedManagers) { + return bundleTransform.call(this, content, 0); + } + return content; + }); + + eleventyConfig.addPlugin((eleventyConfig) => { + // Delayed bundles *MUST* not alter URLs + eleventyConfig.addTransform("@11ty/eleventy-bundle/delayed", function (content) { + let hasDelayedManagers = Boolean(Object.values(eleventyConfig.getBundleManagers()).find(manager => { + return typeof manager.isDelayed === "function" && manager.isDelayed(); + })); + if(hasDelayedManagers) { + return bundleTransform.call(this, content, 1); + } + return content; + }); + }); +}; diff --git a/node_modules/@11ty/eleventy-utils/LICENSE b/node_modules/@11ty/eleventy-utils/LICENSE new file mode 100644 index 0000000..d52e149 --- /dev/null +++ b/node_modules/@11ty/eleventy-utils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022–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-utils/README.md b/node_modules/@11ty/eleventy-utils/README.md new file mode 100644 index 0000000..e7b2cc8 --- /dev/null +++ b/node_modules/@11ty/eleventy-utils/README.md @@ -0,0 +1,27 @@ +

    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) + +## Installation + +``` +npm install @11ty/eleventy-utils +``` + +## Tests + +``` +npm run test +``` + +- We use the native NodeJS [test runner](https://nodejs.org/api/test.html#test-runner) and ([assertions](https://nodejs.org/api/assert.html#assert)) diff --git a/node_modules/@11ty/eleventy-utils/index.js b/node_modules/@11ty/eleventy-utils/index.js new file mode 100644 index 0000000..b329082 --- /dev/null +++ b/node_modules/@11ty/eleventy-utils/index.js @@ -0,0 +1,20 @@ +const TemplatePath = require("./src/TemplatePath.js"); +const isPlainObject = require("./src/IsPlainObject.js"); +const Merge = require("./src/Merge.js"); +const DateCompare = require("./src/DateCompare.js"); +const { DeepCopy } = Merge; +const { createHash, createHashHex, createHashSync, createHashHexSync } = require("./src/CreateHash.js"); +const Buffer = require("./src/Buffer.js"); + +module.exports = { + TemplatePath, + isPlainObject, + Merge, + DeepCopy, + DateCompare, + createHash, + createHashHex, + createHashSync, + createHashHexSync, + Buffer, +}; \ 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..8892430 --- /dev/null +++ b/node_modules/@11ty/eleventy-utils/package.json @@ -0,0 +1,42 @@ +{ + "name": "@11ty/eleventy-utils", + "version": "2.0.7", + "description": "Low level internal utilities to be shared amongst Eleventy projects", + "main": "index.js", + "files": [ + "src", + "src/**", + "index.js", + "!test", + "!test/**" + ], + "scripts": { + "test": "node --test", + "watch": "node --test --watch" + }, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "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/" +} diff --git a/node_modules/@11ty/eleventy-utils/src/Buffer.js b/node_modules/@11ty/eleventy-utils/src/Buffer.js new file mode 100644 index 0000000..8fb0cd4 --- /dev/null +++ b/node_modules/@11ty/eleventy-utils/src/Buffer.js @@ -0,0 +1,10 @@ +function isBuffer(inst) { + if(typeof Buffer !== "undefined") { + return Buffer.isBuffer(inst); + } + return inst instanceof Uint8Array; +} + +module.exports = { + isBuffer +} \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-utils/src/CreateHash.js b/node_modules/@11ty/eleventy-utils/src/CreateHash.js new file mode 100644 index 0000000..92adb0c --- /dev/null +++ b/node_modules/@11ty/eleventy-utils/src/CreateHash.js @@ -0,0 +1,27 @@ + +const { Hash } = require("./HashTypes.js"); + +// same output as node:crypto above (though now async). +async function createHash(...content) { + return Hash.create().toBase64Url(...content); +} + +async function createHashHex(...content) { + return Hash.create().toHex(...content); +} + +// Slower, but this feature does not require WebCrypto +function createHashSync(...content) { + return Hash.createSync().toBase64Url(...content); +} + +function createHashHexSync(...content) { + return Hash.createSync().toHex(...content); +} + +module.exports = { + createHash, + createHashSync, + createHashHex, + createHashHexSync, +}; \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-utils/src/DateCompare.js b/node_modules/@11ty/eleventy-utils/src/DateCompare.js new file mode 100644 index 0000000..a160ace --- /dev/null +++ b/node_modules/@11ty/eleventy-utils/src/DateCompare.js @@ -0,0 +1,41 @@ +class DateCompare { + static isTimestampWithinDuration(timestamp, duration, compareDate = Date.now()) { + // the default duration is Infinity (also "*") + if (!duration || duration === "*" || duration === Infinity) { + return true; + } + + let expiration = timestamp + this.getDurationMs(duration); + + // still valid + if (expiration > compareDate) { + return true; + } + + // expired + return false; + } + + static getDurationMs(duration = "0s") { + let durationUnits = duration.slice(-1); + let durationMultiplier; + if (durationUnits === "s") { + durationMultiplier = 1; + } else if (durationUnits === "m") { + durationMultiplier = 60; + } else if (durationUnits === "h") { + durationMultiplier = 60 * 60; + } else if (durationUnits === "d") { + durationMultiplier = 60 * 60 * 24; + } else if (durationUnits === "w") { + durationMultiplier = 60 * 60 * 24 * 7; + } else if (durationUnits === "y") { + durationMultiplier = 60 * 60 * 24 * 365; + } + + let durationValue = parseInt(duration.slice(0, duration.length - 1), 10); + return durationValue * durationMultiplier * 1000; + } +} + +module.exports = DateCompare; \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-utils/src/HashTypes.js b/node_modules/@11ty/eleventy-utils/src/HashTypes.js new file mode 100644 index 0000000..4f7454c --- /dev/null +++ b/node_modules/@11ty/eleventy-utils/src/HashTypes.js @@ -0,0 +1,158 @@ +const { base64UrlSafe } = require("./Url.js"); +const { isBuffer } = require("./Buffer.js"); +const sha256 = require("./lib-sha256.js"); + +function hasNodeCryptoModule() { + try { + require("node:crypto"); + return true; + } catch(e) { + return false; + } +} + +const HAS_NODE_CRYPTO = hasNodeCryptoModule(); + +class Hash { + static create() { + if(typeof globalThis.crypto === "undefined") { + // Backwards compat with Node Crypto, since WebCrypto (crypto global) is Node 20+ + if(HAS_NODE_CRYPTO) { + return NodeCryptoHash; + } + return ScriptHash; + } + return WebCryptoHash; + } + + // Does not use WebCrypto (as WebCrypto is async-only) + static createSync() { + if(HAS_NODE_CRYPTO) { + return NodeCryptoHash; + } + return ScriptHash; + } + + static toBase64(bytes) { + let str = Array.from(bytes, (b) => String.fromCodePoint(b)).join(""); + + // `btoa` Node 16+ + return btoa(str); + } + + // Thanks https://evanhahn.com/the-best-way-to-concatenate-uint8arrays/ (Public domain) + static mergeUint8Array(...arrays) { + let totalLength = arrays.reduce( + (total, uint8array) => total + uint8array.byteLength, + 0 + ); + + let result = new Uint8Array(totalLength); + let offset = 0; + arrays.forEach((uint8array) => { + result.set(uint8array, offset); + offset += uint8array.byteLength; + }); + + return result; + } + + static bufferToBase64Url(hashBuffer) { + return base64UrlSafe(this.toBase64(new Uint8Array(hashBuffer))); + } + + static bufferToHex(hashBuffer) { + return Array.from(new Uint8Array(hashBuffer)) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); + } +} + +class WebCryptoHash extends Hash { + static async toHash(...content) { + let encoder = new TextEncoder(); + let input = this.mergeUint8Array(...content.map(c => { + if(isBuffer(c)) { + return c; + } + return encoder.encode(c); + })); + + // `crypto` is Node 20+ + return crypto.subtle.digest("SHA-256", input); + } + + static async toBase64Url(...content) { + return this.toHash(...content).then(hashBuffer => { + return this.bufferToBase64Url(hashBuffer); + }); + } + + static async toHex(...content) { + return this.toHash(...content).then(hashBuffer => { + return this.bufferToHex(hashBuffer); + }); + } + + static toBase64UrlSync() { + throw new Error("Synchronous methods are not available in the Web Crypto API."); + } + + static toHexSync() { + throw new Error("Synchronous methods are not available in the Web Crypto API."); + } +} + +class NodeCryptoHash extends Hash { + static toHash(...content) { + // This *needs* to be a dynamic require for proper bundling. + const { createHash } = require("node:crypto"); + let hash = createHash("sha256"); + + for(let c of content) { + hash.update(c); + } + + return hash; + } + + static toBase64Url(...content) { + // Note that Node does include a `digest("base64url")` that is supposedly Node 14+ but curiously failed on Stackblitz’s Node 16. + let base64 = this.toHash(...content).digest("base64"); + return base64UrlSafe(base64); + } + + static toHex(...content) { + return this.toHash(...content).digest("hex"); + } + + // aliases + static toBase64UrlSync = this.toBase64Url; + static toHexSync = this.toHex; +} + +class ScriptHash extends Hash { + static toHash(...content) { + let hash = sha256(); + for(let c of content) { + hash.add(c); + } + return hash.digest(); + } + + static toBase64Url(...content) { + let hashBuffer = this.toHash(...content); + return this.bufferToBase64Url(hashBuffer); + } + + static toHex(...content) { + let hashBuffer = this.toHash(...content); + return this.bufferToHex(hashBuffer); + } + + // aliases + static toBase64UrlSync = this.toBase64Url; + static toHexSync = this.toHex; +} + +module.exports = { Hash, NodeCryptoHash, ScriptHash, WebCryptoHash } \ No newline at end of file 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..807af54 --- /dev/null +++ b/node_modules/@11ty/eleventy-utils/src/TemplatePath.js @@ -0,0 +1,373 @@ +const path = require("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 + * + * @returns {String} the directory portion of a path. + * @param {String} filePath - 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.slice(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) { + let filePath = path.normalize(thePath).split(path.sep).join("/"); + if(filePath !== "/" && filePath.endsWith("/")) { + return filePath.slice(0, -1); + } + return filePath; +}; + +/** + * Joins all given path segments together. + * + * It uses Node.js’ [`path.join`][1] method. + * + * [1]: https://nodejs.org/api/path.html#path_path_join_paths + * + * @param {...String} paths - An arbitrary amount of path segments. + * @returns {String} the normalized and joined path. + */ +TemplatePath.join = function (...paths) { + return TemplatePath.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} pathArg + * @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.slice(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 + * @param {String} [sep="/"] + * @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 + * e.g. `.\\my\\dir\\` becomes `./my/dir/` on *nix and Windows + * + * @param {String} filePath + * @param {String} [sep="/"] + * @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-utils/src/Url.js b/node_modules/@11ty/eleventy-utils/src/Url.js new file mode 100644 index 0000000..7f314ef --- /dev/null +++ b/node_modules/@11ty/eleventy-utils/src/Url.js @@ -0,0 +1,13 @@ +function base64UrlSafe(hashString = "") { + return hashString.replace(/[=\+\/]/g, function(match) { + if(match === "=") { + return ""; + } + if(match === "+") { + return "-"; + } + return "_"; + }); +} + +module.exports = { base64UrlSafe }; \ No newline at end of file diff --git a/node_modules/@11ty/eleventy-utils/src/lib-sha256.js b/node_modules/@11ty/eleventy-utils/src/lib-sha256.js new file mode 100644 index 0000000..7ebd37e --- /dev/null +++ b/node_modules/@11ty/eleventy-utils/src/lib-sha256.js @@ -0,0 +1,113 @@ +// https://github.com/6502/sha256 + +/* +Copyright 2022 Andrea Griffini + +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. +*/ + +// sha256(data) returns the digest +// sha256() returns an object you can call .add(data) zero or more time and .digest() at the end +// digest is a 32-byte Uint8Array instance with an added .hex() function. +// Input should be either a string (that will be encoded as UTF-8) or an array-like object with values 0..255. +module.exports = function sha256(data) { + let h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372, h3 = 0xa54ff53a, + h4 = 0x510e527f, h5 = 0x9b05688c, h6 = 0x1f83d9ab, h7 = 0x5be0cd19, + tsz = 0, bp = 0; + const k = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2], + rrot = (x, n) => (x >>> n) | (x << (32-n)), + w = new Uint32Array(64), + buf = new Uint8Array(64), + process = () => { + for (let j=0,r=0; j<16; j++,r+=4) { + w[j] = (buf[r]<<24) | (buf[r+1]<<16) | (buf[r+2]<<8) | buf[r+3]; + } + for (let j=16; j<64; j++) { + let s0 = rrot(w[j-15], 7) ^ rrot(w[j-15], 18) ^ (w[j-15] >>> 3); + let s1 = rrot(w[j-2], 17) ^ rrot(w[j-2], 19) ^ (w[j-2] >>> 10); + w[j] = (w[j-16] + s0 + w[j-7] + s1) | 0; + } + let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7; + for (let j=0; j<64; j++) { + let S1 = rrot(e, 6) ^ rrot(e, 11) ^ rrot(e, 25), + ch = (e & f) ^ ((~e) & g), + t1 = (h + S1 + ch + k[j] + w[j]) | 0, + S0 = rrot(a, 2) ^ rrot(a, 13) ^ rrot(a, 22), + maj = (a & b) ^ (a & c) ^ (b & c), + t2 = (S0 + maj) | 0; + h = g; g = f; f = e; e = (d + t1)|0; d = c; c = b; b = a; a = (t1 + t2)|0; + } + h0 = (h0 + a)|0; h1 = (h1 + b)|0; h2 = (h2 + c)|0; h3 = (h3 + d)|0; + h4 = (h4 + e)|0; h5 = (h5 + f)|0; h6 = (h6 + g)|0; h7 = (h7 + h)|0; + bp = 0; + }, + add = data => { + if (typeof data === "string") { + data = typeof TextEncoder === "undefined" ? Buffer.from(data) : (new TextEncoder).encode(data); + } + for (let i=0; i { + buf[bp++] = 0x80; if (bp == 64) process(); + if (bp + 8 > 64) { + while (bp < 64) buf[bp++] = 0x00; + process(); + } + while (bp < 58) buf[bp++] = 0x00; + // Max number of bytes is 35,184,372,088,831 + let L = tsz * 8; + buf[bp++] = (L / 1099511627776.) & 255; + buf[bp++] = (L / 4294967296.) & 255; + buf[bp++] = L >>> 24; + buf[bp++] = (L >>> 16) & 255; + buf[bp++] = (L >>> 8) & 255; + buf[bp++] = L & 255; + process(); + let reply = new Uint8Array(32); + reply[ 0] = h0 >>> 24; reply[ 1] = (h0 >>> 16) & 255; reply[ 2] = (h0 >>> 8) & 255; reply[ 3] = h0 & 255; + reply[ 4] = h1 >>> 24; reply[ 5] = (h1 >>> 16) & 255; reply[ 6] = (h1 >>> 8) & 255; reply[ 7] = h1 & 255; + reply[ 8] = h2 >>> 24; reply[ 9] = (h2 >>> 16) & 255; reply[10] = (h2 >>> 8) & 255; reply[11] = h2 & 255; + reply[12] = h3 >>> 24; reply[13] = (h3 >>> 16) & 255; reply[14] = (h3 >>> 8) & 255; reply[15] = h3 & 255; + reply[16] = h4 >>> 24; reply[17] = (h4 >>> 16) & 255; reply[18] = (h4 >>> 8) & 255; reply[19] = h4 & 255; + reply[20] = h5 >>> 24; reply[21] = (h5 >>> 16) & 255; reply[22] = (h5 >>> 8) & 255; reply[23] = h5 & 255; + reply[24] = h6 >>> 24; reply[25] = (h6 >>> 16) & 255; reply[26] = (h6 >>> 8) & 255; reply[27] = h6 & 255; + reply[28] = h7 >>> 24; reply[29] = (h7 >>> 16) & 255; reply[30] = (h7 >>> 8) & 255; reply[31] = h7 & 255; + reply.hex = () => { + let res = ""; + reply.forEach(x => res += ("0" + x.toString(16)).slice(-2)); + return res; + }; + return reply; + }; + if (data === undefined) return {add, digest}; + add(data); + return digest(); +} \ No newline at end of file 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..c4a4d5f --- /dev/null +++ b/node_modules/@11ty/eleventy/cmd.cjs @@ -0,0 +1,155 @@ +#!/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"); + +class SimpleError extends Error { + constructor(...args) { + super(...args); + this.skipOriginalStack = true; + } +} + +async function exec() { + // Notes about friendly error messaging with outdated Node versions: https://github.com/11ty/eleventy/issues/3761 + const { EleventyErrorHandler } = await import("./src/Errors/EleventyErrorHandler.js"); + + 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); + + await elev.init(); + + 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."); + } + + await elev.watch(); + + if (argv.serve) { + // TODO await here? + elev.serve(argv.port); + } + + process.on("SIGINT", async () => { + await elev.stopWatch(); + process.exitCode = 0; + }); + } else { + if (!argv.to || argv.to === "fs") { + await elev.write(); + } else if (argv.to === "json") { + let result = await elev.toJSON() + console.log(JSON.stringify(result, null, 2)); + } else if (argv.to === "ndjson") { + let stream = await elev.toNDJSON(); + stream.pipe(process.stdout); + } else { + throw new SimpleError( + `Invalid --to value: ${argv.to}. Supported values: \`fs\` (default), \`json\`, and \`ndjson\`.`, + ); + } + } + } catch (error) { + if(typeof EleventyErrorHandler !== "undefined") { + let ErrorHandler = new EleventyErrorHandler(); + ErrorHandler.fatal(error, "Eleventy Fatal Error (CLI)"); + } else { + console.error(error); + process.exitCode = 1; + } + } +} + +exec(); diff --git a/node_modules/@11ty/eleventy/package.json b/node_modules/@11ty/eleventy/package.json new file mode 100644 index 0000000..f300eec --- /dev/null +++ b/node_modules/@11ty/eleventy/package.json @@ -0,0 +1,166 @@ +{ + "name": "@11ty/eleventy", + "version": "3.1.5", + "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" + }, + "./UserConfig": { + "types": "./src/UserConfig.js" + } + }, + "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", + "nano-staged": "nano-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": "simple-git-hooks" + }, + "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*/**/*", + "./test/**/_site/**/*", + ".cache" + ] + } + }, + "nano-staged": { + "*.{js,css,md}": [ + "prettier --write" + ] + }, + "simple-git-hooks": { + "pre-commit": "npm test && npm run nano-staged", + "pre-push": "npm test" + }, + "devDependencies": { + "@11ty/eleventy-img": "^6.0.4", + "@11ty/eleventy-plugin-rss": "^2.0.4", + "@11ty/eleventy-plugin-syntaxhighlight": "^5.0.2", + "@11ty/eleventy-plugin-webc": "^0.12.0-beta.7", + "@eslint/eslintrc": "^3.3.5", + "@eslint/js": "^10.0.1", + "@iarna/toml": "^2.2.5", + "@mdx-js/node-loader": "^3.1.1", + "@types/node": "^25.5.0", + "@vue/server-renderer": "^3.5.30", + "@zachleat/noop": "^1.0.7", + "ava": "^6.4.1", + "c8": "^11.0.0", + "eslint": "^10.0.3", + "eslint-config-prettier": "^10.1.8", + "globals": "^17.4.0", + "jsx-async-runtime": "^2.0.3", + "markdown-it-abbr": "^2.0.0", + "markdown-it-emoji": "^3.0.0", + "marked": "^17.0.4", + "nano-staged": "^0.9.0", + "prettier": "^3.8.1", + "pretty": "^2.0.0", + "react": "^19.2.4", + "react-dom": "^19.2.4", + "sass": "^1.98.0", + "simple-git-hooks": "^2.13.1", + "tsx": "^4.21.0", + "typescript": "^5.9.3", + "vue": "^3.5.30", + "zod": "^4.3.6", + "zod-validation-error": "^5.0.0" + }, + "dependencies": { + "@11ty/dependency-tree": "^4.0.2", + "@11ty/dependency-tree-esm": "^2.0.4", + "@11ty/eleventy-dev-server": "^2.0.8", + "@11ty/eleventy-plugin-bundle": "^3.0.7", + "@11ty/eleventy-utils": "^2.0.7", + "@11ty/lodash-custom": "^4.17.21", + "@11ty/posthtml-urls": "^1.0.2", + "@11ty/recursive-copy": "^4.0.4", + "@sindresorhus/slugify": "^2.2.1", + "bcp-47-normalize": "^2.3.0", + "chokidar": "^3.6.0", + "debug": "^4.4.3", + "dependency-graph": "^1.0.0", + "entities": "^6.0.1", + "filesize": "^10.1.6", + "gray-matter": "^4.0.3", + "iso-639-1": "^3.1.5", + "js-yaml": "^4.1.1", + "kleur": "^4.1.5", + "liquidjs": "^10.25.0", + "luxon": "^3.7.2", + "markdown-it": "^14.1.1", + "minimist": "^1.2.8", + "moo": "0.5.2", + "node-retrieve-globals": "^6.0.1", + "nunjucks": "^3.2.4", + "picomatch": "^4.0.3", + "please-upgrade-node": "^3.2.0", + "posthtml": "^0.16.7", + "posthtml-match-helper": "^2.0.3", + "semver": "^7.7.4", + "slugify": "^1.6.8", + "tinyglobby": "^0.2.15" + }, + "overrides": { + "gray-matter": { + "js-yaml": "$js-yaml" + } + } +} 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..5350475 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Data/ComputedData.js @@ -0,0 +1,122 @@ +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, + }; + } + fns.tmpl = templateInstance; + + renderFn = renderFn.bind(fns); + } + + 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..6942892 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Data/TemplateData.js @@ -0,0 +1,710 @@ +import path from "node:path"; +import util from "node:util"; +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 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 TemplateDataParseError extends EleventyBaseError {} + +class TemplateData { + constructor(templateConfig) { + if (!templateConfig || templateConfig.constructor.name !== "TemplateConfig") { + throw new Error( + "Internal error: Missing `templateConfig` or was not an instance of `TemplateConfig`.", + ); + } + + this.templateConfig = templateConfig; + this.config = this.templateConfig.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.templateConfig); + } + + get dirs() { + return this.templateConfig.directories; + } + + get inputDir() { + return this.dirs.input; + } + + // if this was set but `falsy` we would fallback to inputDir + get dataDir() { + return this.dirs.data; + } + + get absoluteDataDir() { + return TemplatePath.absolutePath(this.dataDir); + } + + // 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; + } + + exists(pathname) { + // 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.templateConfig.existsCache.exists(pathname); + } + + setFileSystemSearch(fileSystemSearch) { + this.fileSystemSearch = fileSystemSearch; + } + + setProjectUsingEsm(isEsmProject) { + this.isEsm = !!isEsmProject; + } + + get extensionMap() { + if (!this._extensionMap) { + throw new Error("Internal error: missing `extensionMap` in TemplateData."); + } + 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; + } + + let pkgJson = getWorkingProjectPackageJson(); + this.rawImports[this.config.keys.package] = pkgJson; + + if (this.config.freezeReservedData) { + DeepFreeze(this.rawImports); + } + + 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 absoluteDataFilePath = TemplatePath.absolutePath(dataFilePath); + let reducedPath = TemplatePath.stripLeadingSubPath(absoluteDataFilePath, this.absoluteDataDir); + 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 + localDataPaths = localDataPaths.filter((path) => { + return this.exists(path); + }); + + 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, { + file: path, + }); + 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] = 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) + if (!this.exists(path)) { + 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(path, 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); + } + // TODO use DirContains + 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, options = {}) { + 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; + } else if (data.tags) { + throw new Error( + `String or Array expected for \`tags\`${options.file ? ` in ${options.isVirtualTemplate ? "virtual " : ""}template: ${options.file}` : ""}. Received: ${util.inspect(data.tags)}`, + ); + } + + // Deduplicate tags + // Coerce to string #3875 + return [...new Set(tags)].map((entry) => String(entry)); + } + + return tags; + } + + static cleanupData(data, options = {}) { + if (isPlainObject(data) && "tags" in data) { + data.tags = this.getCleanedTagsImmutable(data, options); + } + + 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, + }; + } + + static getIncludedCollectionNames(data) { + let tags = TemplateData.getCleanedTagsImmutable(data); + + let { excludes, excludeAll } = TemplateData.getNormalizedExcludedCollections(data); + if (excludeAll) { + return []; + } + + return ["all", ...tags].filter((tag) => !excludes.includes(tag)); + } + + static getIncludedTagNames(data) { + return this.getIncludedCollectionNames(data).filter((tagName) => tagName !== "all"); + } +} + +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..0568a3e --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Eleventy.js @@ -0,0 +1,1565 @@ +import chalk from "kleur"; +import { performance } from "node:perf_hooks"; +import debugUtil from "debug"; +import { filesize } from "filesize"; +import path from "node:path"; + +/* Eleventy Deps */ +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 TemplatePassthroughManager from "./TemplatePassthroughManager.js"; +import TemplateConfig from "./TemplateConfig.js"; +import FileSystemSearch from "./FileSystemSearch.js"; +import TemplateEngineManager from "./Engines/TemplateEngineManager.js"; + +/* Utils */ +import ConsoleLogger from "./Util/ConsoleLogger.js"; +import PathPrefixer from "./Util/PathPrefixer.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, + importJsonSync, + getWorkingProjectPackageJsonPath, +} from "./Util/ImportJsonSync.js"; +import { EleventyImport } from "./Util/Require.js"; +import ProjectTemplateFormats from "./Util/ProjectTemplateFormats.js"; +import { withResolvers } from "./Util/PromiseUtil.js"; + +/* Plugins */ +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 FileSystemRemap from "./Util/GlobRemap.js"; + +const pkg = getEleventyPackageJson(); +const debug = debugUtil("Eleventy"); + +/** + * Eleventy’s programmatic API + * @module 11ty/eleventy/Eleventy + */ + +class Eleventy { + /** + * Userspace package.json file contents + * @type {object|undefined} + */ + #projectPackageJson; + /** @type {string} */ + #projectPackageJsonPath; + /** @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()); + } + + // Careful to make sure the previous server closes on SIGINT, issue #3873 + if (!this.eleventyServe) { + /** @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; + + // after #hasConfigInitialized above + 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.extensionMap.reset(); + this.bench.reset(); + this.passthroughManager.reset(); + this.eleventyFiles.restart(); + } + + /** + * 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 = []; + + let { + copyCount, + copySize, + skipCount, + writeCount, + // renderCount, // files that render (costly) but may not write to disk + } = this.writer.getMetadata(); + + let slashRet = []; + + if (copyCount) { + debug("Total passthrough copy aggregate size: %o", filesize(copySize)); + slashRet.push(`Copied ${chalk.bold(copyCount)}`); + } + + slashRet.push( + `Wrote ${chalk.bold(writeCount)} ${simplePlural(writeCount, "file", "files")}${ + skipCount ? ` (skipped ${skipCount})` : "" + }`, + ); + + // slashRet.push( + // `${renderCount} rendered` + // ) + + 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 > 1) { + 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 = {}) { + let { viaConfigReset } = Object.assign({ viaConfigReset: false }, options); + if (!this.#hasConfigInitialized) { + await this.initializeConfig(); + } else { + // Note: Global event bus is different from user config event bus + this.config.events.reset(); + } + + 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(); + let engineManager = new TemplateEngineManager(this.eleventyConfig); + this.extensionMap = new EleventyExtensionMap(this.eleventyConfig); + this.extensionMap.setFormats(formats); + this.extensionMap.engineManager = engineManager; + 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.passthroughManager = new TemplatePassthroughManager(this.eleventyConfig); + this.passthroughManager.setRunMode(this.runMode); + this.passthroughManager.setDryRun(this.isDryRun); + this.passthroughManager.extensionMap = this.extensionMap; + this.passthroughManager.setFileSystemSearch(this.fileSystemSearch); + + this.eleventyFiles = new EleventyFiles(formats, this.eleventyConfig); + this.eleventyFiles.setPassthroughManager(this.passthroughManager); + 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 (!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.setPassthroughManager(this.passthroughManager); + 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) { + values.config = TemplatePath.absolutePath(configPath); + } + + // Fixed: instead of configuration directory, explicit root or working directory + values.root = TemplatePath.getWorkingDir(); + + 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); + + this.eleventyConfig.setPreviousBuildModifiedFile(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 + */ + resetConfig() { + delete this.eleventyConfig; + + // ensures `initializeConfig()` will run when `init()` is called next + this.#hasConfigInitialized = false; + } + + /** + * @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); + + // `eleventy.templateModified` is no longer used internally, remove in a future major version. + eventBus.emit("eleventy.templateModified", changedFilePath, { + usedByDependants, + relevantLayouts, + }); + + // These listeners are *global*, not cleared even on config reset + eventBus.emit("eleventy.resourceModified", changedFilePath, usedByDependants, { + viaConfigReset: isResetConfig, + relevantLayouts, + }); + + this.config.events.emit("eleventy#templateModified", changedFilePath); + + 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"); + 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 files = this.watchManager.getActiveQueue(); + + // Maps passthrough copy files to output URLs for CSS live reload + let stylesheetUrls = new Set(); + for (let entry of passthroughCopyResults) { + for (let filepath in entry.map) { + if ( + filepath.endsWith(".css") && + files.includes(TemplatePath.addLeadingDotSlash(filepath)) + ) { + stylesheetUrls.add( + "/" + TemplatePath.stripLeadingSubPath(entry.map[filepath], this.outputDir), + ); + } + } + } + + let normalizedPathPrefix = PathPrefixer.normalizePathPrefix(this.config.pathPrefix); + let matchingTemplates = templateResults + .flat() + .filter((entry) => Boolean(entry)) + .map((entry) => { + // only `url`, `inputPath`, and `content` are used: https://github.com/11ty/eleventy-dev-server/blob/1c658605f75224fdc76f68aebe7a412eeb4f1bc9/client/reload-client.js#L140 + entry.url = PathPrefixer.joinUrlParts(normalizedPathPrefix, entry.url); + delete entry.rawInput; // Issue #3481 + return entry; + }); + + await this.eleventyServe.reload({ + files, + subtype: onlyCssChanges ? "css" : undefined, + build: { + stylesheets: Array.from(stylesheetUrls), + templates: matchingTemplates, + }, + }); + } 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; + + if (this.projectPackageJsonPath) { + this.watchTargets.add([ + path.relative(TemplatePath.getWorkingDir(), this.projectPackageJsonPath), + ]); + } + 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 projectPackageJsonPath() { + if (this.#projectPackageJsonPath === undefined) { + this.#projectPackageJsonPath = getWorkingProjectPackageJsonPath() || false; + } + return this.#projectPackageJsonPath; + } + + get projectPackageJson() { + if (!this.#projectPackageJson) { + let p = this.projectPackageJsonPath; + this.#projectPackageJson = p ? importJsonSync(p) : {}; + } + 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") { + this.#isEsm = this.projectPackageJson?.type === "module"; + } 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; + } + + // TODO use DirContains + 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 options = this.getChokidarConfig(); + + // Remap all paths to `cwd` if in play (Issue #3854) + let remapper = new FileSystemRemap(rawFiles); + let cwd = remapper.getCwd(); + + if (cwd) { + options.cwd = cwd; + + rawFiles = remapper.getInput().map((entry) => { + return TemplatePath.stripLeadingDotSlash(entry); + }); + + options.ignored = remapper.getRemapped(options.ignored || []).map((entry) => { + return TemplatePath.stripLeadingDotSlash(entry); + }); + } + + let watcher = chokidar.watch(rawFiles, options); + + 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); + + let { promise, resolve, reject } = withResolvers(); + + watchDelay = setTimeout(async () => { + this.#watch(isResetConfig).then(resolve, reject); + }, this.config.watchThrottleWaitTime); + + await promise; + } 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(); + } + } + + this.config.events.emit("eleventy.afterwatch"); + }; + + watcher.on("change", async (path) => { + // Emulated passthrough copy logs from the server + if (!this.eleventyServe.isEmulatedPassthroughCopyMatch(path)) { + this.logger.forceLog(`File changed: ${TemplatePath.standardizeFilePath(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: ${TemplatePath.standardizeFilePath(path)}`); + } + + this.fileSystemSearch.add(path); + await watchRun(path); + }); + + watcher.on("unlink", (path) => { + this.logger.forceLog(`File deleted: ${TemplatePath.standardizeFilePath(path)}`); + this.fileSystemSearch.delete(path); + }); + + // wait for chokidar to be ready. + await new Promise((resolve) => { + watcher.on("ready", () => resolve()); + }); + + // Returns for testability + return watchRun; + } + + async stopWatch() { + // Prevent multiple invocations. + if (this.#isStopping) { + return this.#isStopping; + } + + debug("Cleaning up chokidar and server instances, if they exist."); + this.#isStopping = Promise.all([this.eleventyServe.close(), this.watcher?.close()]).then(() => { + this.#isStopping = false; + }); + + return this.#isStopping; + } + + /** + * 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.then(() => { + // #needsInit also set to false at the end of `init()` + this.#needsInit = false; + this.#initPromise = undefined; + }); + } + + 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 exitCode 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..5227265 --- /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. Upgrade your Node version (at time of writing, v22.12 or newer) to enable this behavior. If you use a version + of Node older than v22.12, try the --experimental-require-module command line flag in Node. Read more: + https://nodejs.org/api/modules.html#loading-ecmascript-modules-using-require`); + + 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..8f42640 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/EleventyExtensionMap.js @@ -0,0 +1,284 @@ +import { TemplatePath } from "@11ty/eleventy-utils"; + +class EleventyExtensionMap { + #engineManager; + + constructor(config) { + this.setTemplateConfig(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)); + } + + setTemplateConfig(config) { + if (!config || config.constructor.name !== "TemplateConfig") { + throw new Error("Internal error: Missing or invalid `config` argument."); + } + + this.templateConfig = config; + } + + get config() { + return this.templateConfig.getConfig(); + } + + get engineManager() { + if (!this.#engineManager) { + throw new Error("Internal error: Missing `#engineManager` in EleventyExtensionMap."); + } + + return this.#engineManager; + } + + set engineManager(mgr) { + this.#engineManager = mgr; + } + + 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 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); + } + } + + let dir = TemplatePath.convertToRecursiveGlobSync(inputDir); + 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..7ec6379 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/EleventyFiles.js @@ -0,0 +1,521 @@ +import fs from "node:fs"; + +import { TemplatePath, isPlainObject } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import DirContains from "./Util/DirContains.js"; +import TemplateData from "./Data/TemplateData.js"; +import TemplateGlob from "./TemplateGlob.js"; +import checkPassthroughCopyBehavior from "./Util/PassthroughCopyBehaviorCheck.js"; + +const debug = debugUtil("Eleventy:EleventyFiles"); + +class EleventyFiles { + #extensionMap; + #watcherGlobs; + + constructor(formats, templateConfig) { + if (!templateConfig) { + throw new Error("Internal error: Missing `templateConfig`` argument."); + } + + this.templateConfig = templateConfig; + this.config = templateConfig.getConfig(); + this.aggregateBench = this.config.benchmarkManager.get("Aggregate"); + + this.formats = formats; + this.eleventyIgnoreContent = false; + } + + get dirs() { + return this.templateConfig.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.setupGlobs(); + } + + #getWatcherGlobs() { + if (!this.#watcherGlobs) { + let globs; + // Input is a file + if (this.inputFile) { + globs = this.templateGlobs; + } else { + // input is a directory + globs = this.extensionMap.getValidGlobs(this.inputDir); + } + this.#watcherGlobs = globs; + } + + return this.#watcherGlobs; + } + + 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.setupGlobs(); + this._glob = null; + } + + /* For testing */ + _setConfig(config) { + if (!config.ignores) { + config.ignores = new Set(); + config.ignores.add("**/node_modules/**"); + } + + this.config = config; + + this.init(); + } + + /* 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) { + throw new Error("Internal error: missing `extensionMap` in EleventyFiles."); + } + return this.#extensionMap; + } + + setRunMode(runMode) { + this.runMode = runMode; + } + + setPassthroughManager(mgr) { + this.passthroughManager = mgr; + } + + set templateData(templateData) { + this._templateData = templateData; + } + + get templateData() { + if (!this._templateData) { + this._templateData = new TemplateData(this.templateConfig); + } + + 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; + } + + normalizeIgnoreEntry(entry) { + if (!entry.startsWith("**/")) { + return TemplateGlob.normalizePath(this.localPathRoot || ".", entry); + } + return entry; + } + + 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(this.normalizeIgnoreEntry(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; + } + + /* Tests only */ + _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); + } + + // Make sure output dir isn’t in the input dir (or it will ignore all input!) + // input: . and output: . (skip ignore) + // input: ./content and output . (skip ignore) + // input: . and output: ./_site (add ignore) + let outputContainsInputDir = DirContains(this.outputDir, this.inputDir); + if (!outputContainsInputDir) { + // 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.templateConfig.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(); + + let globs = this.#getWatcherGlobs(); + + if (checkPassthroughCopyBehavior(this.config, this.runMode)) { + return globs.concat(directoryGlobs); + } + + // Revert to old passthroughcopy copy files behavior + return globs.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/**", + ".git/**", + // TODO outputDir + // this.outputDir, + ], + }), + ); + 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(this.normalizeIgnoreEntry(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..65525ef --- /dev/null +++ b/node_modules/@11ty/eleventy/src/EleventyServe.js @@ -0,0 +1,321 @@ +import assert from "node:assert"; + +import debugUtil from "debug"; +import { Merge, DeepCopy, TemplatePath } from "@11ty/eleventy-utils"; + +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() {}, + // ready: function(server) {}, + // logger: { info: function() {}, error: function() {} } +}; + +class EleventyServe { + #eleventyConfig; + + 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 import("@11ty/eleventy-dev-server").then((i) => i.default); + } + + // 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 import("@11ty/eleventy-dev-server").then((i) => i.default); + } + } + + 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); + + if (typeof this.config.serverOptions?.ready === "function") { + if (typeof this.server.ready === "function") { + // Dev Server 2.0.7+ + // wait for ready promise to resolve before triggering ready callback + await this.server.ready(); + await this.config.serverOptions?.ready(this.server); + } else { + throw new Error( + "The `ready` option in Eleventy’s `setServerOptions` method requires a `ready` function on the Dev Server instance. If you’re using Eleventy Dev Server, you will need Dev Server 2.0.7+ or newer to use this feature.", + ); + } + } + } + + 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..17a0da1 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Engines/Custom.js @@ -0,0 +1,339 @@ +import TemplateEngine from "./TemplateEngine.js"; +import getJavaScriptData from "../Util/GetJavaScriptData.js"; + +export default 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.setDefaultEngine(undefined); + } + + 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; + } + + get cacheable() { + // Enable cacheability for this template + if (this.entry?.compileOptions?.cache !== undefined) { + return this.entry.compileOptions.cache; + } else if (this.needsToReadFileContents()) { + return true; + } else if (this._defaultEngine?.cacheable !== undefined) { + return this._defaultEngine.cacheable; + } + + return super.cacheable; + } + + 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 compiledFn = 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 (compiledFn) { + // Bind defaultRenderer to render function + if ("then" in compiledFn && typeof compiledFn.then === "function") { + // Promise, wait to bind + return compiledFn.then((fn) => { + if (typeof fn === "function") { + return fn.bind({ + defaultRenderer: defaultCompilationFn, + }); + } + return fn; + }); + } else if ("bind" in compiledFn && typeof compiledFn.bind === "function") { + return compiledFn.bind({ + defaultRenderer: defaultCompilationFn, + }); + } + } + + return compiledFn; + } + + 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) { + let lastModifiedFile = this.eleventyConfig.getPreviousBuildModifiedFile(); + // 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 isRelevant = this.isFileRelevantTo(inputPath, lastModifiedFile, false); + let useCache = !isRelevant; + + 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 + // Note: `false` is the same as "raw" here. + return false; + } + + static shouldSpiderJavaScriptDependencies(entry) { + if (entry.compileOptions && "spiderJavaScriptDependencies" in entry.compileOptions) { + return entry.compileOptions.spiderJavaScriptDependencies; + } + + return false; + } +} 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..a0f4101 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Engines/Html.js @@ -0,0 +1,33 @@ +import TemplateEngine from "./TemplateEngine.js"; + +export default class Html extends TemplateEngine { + constructor(name, eleventyConfig) { + super(name, eleventyConfig); + } + + get cacheable() { + return true; + } + + async #getPreEngine(preTemplateEngine) { + return this.engineManager.getEngine(preTemplateEngine, this.extensionMap); + } + + async compile(str, inputPath, preTemplateEngine) { + if (preTemplateEngine) { + let engine = await this.#getPreEngine(preTemplateEngine); + let fnReady = engine.compile(str, inputPath); + + return async function (data) { + let fn = await fnReady; + + return fn(data); + }; + } + + return function () { + // do nothing with data if preTemplateEngine is falsy + return str; + }; + } +} 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..29b3b7c --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Engines/JavaScript.js @@ -0,0 +1,240 @@ +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 { EleventyImport } from "../Util/Require.js"; +import { augmentFunction, augmentObject } from "./Util/ContextAugmenter.js"; + +class JavaScriptTemplateNotDefined extends EleventyBaseError {} + +export default class JavaScript extends TemplateEngine { + constructor(name, templateConfig) { + super(name, templateConfig); + this.instances = {}; + + this.config.events.on("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]; + } + } + }); + } + + get cacheable() { + return false; + } + + 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(); + let cacheBust = !this.cacheable || !this.config.useTemplateCache; + mod = await EleventyImport(inputPath, isEsm ? "esm" : "cjs", { + cacheBust, + }); + } + + 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 (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)); + }; + } + } + + static shouldSpiderJavaScriptDependencies() { + return true; + } +} 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..44fdab4 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Engines/Liquid.js @@ -0,0 +1,331 @@ +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"); + +export default 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); + } + + get cacheable() { + return 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, Boolean(this.config.libraryOverrides.liquid)); + + 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) { + if (!str) { + return []; + } + + 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); + }; + } +} 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..ec1e1f6 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Engines/Markdown.js @@ -0,0 +1,100 @@ +import markdownIt from "markdown-it"; + +import TemplateEngine from "./TemplateEngine.js"; + +export default class Markdown extends TemplateEngine { + constructor(name, eleventyConfig) { + super(name, eleventyConfig); + + this.markdownOptions = {}; + + this.setLibrary(this.config.libraryOverrides.md); + } + + get cacheable() { + return 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, Boolean(this.config.libraryOverrides.md)); + } + + 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 || {}, + ); + } + + // TODO use preTemplateEngine to help inform this + // needsCompilation() { + // return super.needsCompilation(); + // } + + async #getPreEngine(preTemplateEngine) { + if (typeof preTemplateEngine === "string") { + return this.engineManager.getEngine(preTemplateEngine, this.extensionMap); + } + + return preTemplateEngine; + } + + async compile(str, inputPath, preTemplateEngine, bypassMarkdown) { + let mdlib = this.mdLib; + + if (preTemplateEngine) { + let engine = await this.#getPreEngine(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); + }; + } + } + } +} 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..70cca17 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Engines/Nunjucks.js @@ -0,0 +1,482 @@ +import NunjucksLib from "nunjucks"; +import debugUtil from "debug"; +import { TemplatePath } from "@11ty/eleventy-utils"; + +import TemplateEngine from "./TemplateEngine.js"; +import EleventyBaseError from "../Errors/EleventyBaseError.js"; +import { augmentObject } from "./Util/ContextAugmenter.js"; +import { withResolvers } from "../Util/PromiseUtil.js"; + +const debug = debugUtil("Eleventy:Nunjucks"); + +class EleventyNunjucksError extends EleventyBaseError {} + +export default 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); + } + + // v3.1.0-alpha.1 we’ve moved to use Nunjucks’ internal cache instead of Eleventy’s + // get cacheable() { + // return false; + // } + + #getFileSystemDirs() { + let paths = new Set(); + paths.add(super.getIncludesDir()); + paths.add(TemplatePath.getWorkingDir()); + + // Filter out undefined paths + return Array.from(paths).filter(Boolean); + } + + #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 fsLoader = new NunjucksLib.FileSystemLoader(this.#getFileSystemDirs()); + 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); + + // Note that a new Nunjucks engine instance is created for subsequent builds + // Eleventy Nunjucks is set to `cacheable` false above to opt out of Eleventy cache + this.config.events.on("eleventy#templateModified", (templatePath) => { + // NunjucksEnvironment: + // loader.pathToNames: {'ABSOLUTE_PATH/src/_includes/components/possum-home.css': 'components/possum-home.css'} + // loader.cache: { 'components/possum-home.css': [Template] } + // Nunjucks stores these as Operating System native paths + let absTmplPath = TemplatePath.normalizeOperatingSystemFilePath( + TemplatePath.absolutePath(templatePath), + ); + for (let loader of this.njkEnv.loaders) { + let nunjucksName = loader.pathsToNames[absTmplPath]; + if (nunjucksName) { + debug( + "Match found in Nunjucks cache via templateModified for %o, clearing this entry", + templatePath, + ); + delete loader.pathsToNames[absTmplPath]; + delete loader.cache[nunjucksName]; + } + } + + // Behavior prior to v3.1.0-alpha.1: + // this.njkEnv.invalidateCache(); + }); + + this.setEngineLib(this.njkEnv, Boolean(this.config.libraryOverrides.njk)); + + 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) { + if (!str) { + return []; + } + const { parser, nodes } = NunjucksLib; + let obj = parser.parse(str, this._getParseExtensions()); + if (!obj) { + return []; + } + 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) { + let { promise, resolve, reject } = withResolvers(); + + tmpl.render(data, (error, result) => { + if (error) { + reject(error); + } else { + resolve(result); + } + }); + + return promise; + }; + } +} 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..234aa4e --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Engines/TemplateEngine.js @@ -0,0 +1,206 @@ +import debugUtil from "debug"; +import EleventyBaseError from "../Errors/EleventyBaseError.js"; + +class TemplateEngineConfigError extends EleventyBaseError {} + +const debug = debugUtil("Eleventy:TemplateEngine"); + +const AMENDED_INSTANCES = new Set(); + +export default class TemplateEngine { + #extensionMap; + #engineManager; + #benchmarks; + + constructor(name, eleventyConfig) { + this.name = name; + + this.engineLib = null; + + if (!eleventyConfig) { + throw new TemplateEngineConfigError("Missing `eleventyConfig` argument."); + } + this.eleventyConfig = eleventyConfig; + } + + get cacheable() { + return false; + } + + 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) { + throw new Error("Internal error: missing `extensionMap` in TemplateEngine."); + } + 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, isOverrideViaSetLibrary = false) { + this.engineLib = engineLib; + + // Run engine amendments (via issue #2438) + // Issue #3816: this isn’t ideal but there is no other way to reset a markdown instance if it was also overridden by addLibrary + if (AMENDED_INSTANCES.has(engineLib)) { + return; + } + + if (isOverrideViaSetLibrary) { + AMENDED_INSTANCES.add(engineLib); + } + debug( + "Running amendLibrary for %o (number of amendments: %o)", + this.name, + this.config.libraryAmendments[this.name]?.length, + ); + + 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); + } +} 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..913a803 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Engines/TemplateEngineManager.js @@ -0,0 +1,193 @@ +import debugUtil from "debug"; +import EleventyBaseError from "../Errors/EleventyBaseError.js"; + +const debug = debugUtil("Eleventy:TemplateEngineManager"); + +class TemplateEngineManager { + constructor(eleventyConfig) { + if (!eleventyConfig || eleventyConfig.constructor.name !== "TemplateConfig") { + throw new EleventyBaseError("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); + } + + 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 = import("./Markdown.js").then((mod) => mod.default); + } else if (extension === "html") { + promise = import("./Html.js").then((mod) => mod.default); + } else if (extension === "njk") { + promise = import("./Nunjucks.js").then((mod) => mod.default); + } else if (extension === "liquid") { + promise = import("./Liquid.js").then((mod) => mod.default); + } else if (extension === "11ty.js") { + promise = import("./JavaScript.js").then((mod) => mod.default); + } else { + promise = this.getCustomEngineClass(); + } + + this.importCache[extension] = promise; + + return promise; + } + + async getCustomEngineClass() { + if (!this._CustomEngine) { + this._CustomEngine = import("./Custom.js").then((mod) => mod.default); + } + 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; + } + + isEngineRemovedFromCore(name) { + return ["ejs", "hbs", "mustache", "haml", "pug"].includes(name) && !this.hasEngine(name); + } + + async getEngine(name, extensionMap) { + // Bundled 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 engine 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..879e65c --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Errors/EleventyErrorHandler.js @@ -0,0 +1,152 @@ +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) { + // Don’t show the full error stack trace + showStack = false; + } + + let totalErrorCount = EleventyErrorHandler.getTotalErrorCount(e); + let ref = e; + let index = 1; + while (ref) { + let nextRef = ref.originalError; + + // Unwrap cause from error and assign it to what Eleventy expects + if (nextRef?.cause) { + nextRef.originalError = nextRef.cause?.originalError ?? nextRef?.cause; + } + + 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..6b374d0 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Errors/EleventyErrorUtil.js @@ -0,0 +1,70 @@ +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?.cause instanceof TemplateContentPrematureUseError || // Custom (per Node-convention) + ["RenderError", "UndefinedVariableError"].includes(e?.originalError?.name) && e?.originalError?.originalError instanceof TemplateContentPrematureUseError || // Liquid + e?.message?.includes("TemplateContentPrematureUseError") // 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..0aa4126 --- /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); // defaults to 10 + +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..972e80b --- /dev/null +++ b/node_modules/@11ty/eleventy/src/FileSystemSearch.js @@ -0,0 +1,129 @@ +import { glob } from "tinyglobby"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import FileSystemRemap from "./Util/GlobRemap.js"; +import { isGlobMatch } from "./Util/GlobMatcher.js"; + +const debug = debugUtil("Eleventy:FileSystemSearch"); + +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)); + + let cwd = FileSystemRemap.getCwd(globs); + if (cwd) { + options.cwd = cwd; + } + + if (options.ignore && Array.isArray(options.ignore)) { + options.ignore = options.ignore.map((entry) => { + entry = TemplatePath.stripLeadingDotSlash(entry); + + return FileSystemRemap.remapInput(entry, cwd); + }); + 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++; + + globs = globs.map((entry) => { + if (cwd && entry.startsWith(cwd)) { + return FileSystemRemap.remapInput(entry, cwd); + } + + return entry; + }); + + this.promises[cacheKey] = glob( + globs, + Object.assign( + { + caseSensitiveMatch: false, // insensitive + dot: true, + }, + options, + ), + ).then((results) => { + this.outputs[cacheKey] = new Set( + results.map((entry) => { + let remapped = FileSystemRemap.remapOutput(entry, options.cwd); + return TemplatePath.standardizeFilePath(remapped); + }), + ); + + 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.standardizeFilePath(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"); + } + + // Issue #3859 get rid of chokidar globs + // getAllOutputFiles() { + // return Object.values(this.outputs).map(set => Array.from(set)).flat(); + // } +} + +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..7e169da --- /dev/null +++ b/node_modules/@11ty/eleventy/src/GlobalDependencyMap.js @@ -0,0 +1,463 @@ +import debugUtil from "debug"; +import { TemplatePath } from "@11ty/eleventy-utils"; + +import JavaScriptDependencies from "./Util/JavaScriptDependencies.js"; +import PathNormalizer from "./Util/PathNormalizer.js"; +import { TemplateDepGraph } from "./Util/TemplateDepGraph.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:"; // must match TemplateDepGraph key + + #map; + #templateConfig; + #cachedUserConfigurationCollectionApiNames; + + static isCollection(entry) { + return entry.startsWith(this.COLLECTION_PREFIX); + } + + static getTagName(entry) { + if (this.isCollection(entry)) { + return entry.slice(this.COLLECTION_PREFIX.length); + } + } + + static getCollectionKeyForEntry(entry) { + return `${GlobalDependencyMap.COLLECTION_PREFIX}${entry}`; + } + + reset() { + this.#map = undefined; + } + + setIsEsm(isEsm) { + this.isEsm = isEsm; + } + + setTemplateConfig(templateConfig) { + this.#templateConfig = templateConfig; + + // These have leading dot slashes, but so do the paths from Eleventy + this.#templateConfig.userConfig.events.once("eleventy.layouts", async (layouts) => { + await this.addLayoutsToMap(layouts); + }); + } + + get userConfigurationCollectionApiNames() { + if (this.#cachedUserConfigurationCollectionApiNames) { + return this.#cachedUserConfigurationCollectionApiNames; + } + return Object.keys(this.#templateConfig.userConfig.getCollections()) || []; + } + + initializeUserConfigurationApiCollections() { + this.addCollectionApiNames(this.userConfigurationCollectionApiNames); + } + + // For Testing + setCollectionApiNames(names = []) { + this.#cachedUserConfigurationCollectionApiNames = names; + } + + addCollectionApiNames(names = []) { + if (!names || names.length === 0) { + return; + } + + for (let collectionName of names) { + this.map.addConfigCollectionName(collectionName); + } + } + + filterOutLayouts(nodes = []) { + return nodes.filter((node) => { + if (GlobalDependencyMap.isLayoutNode(this.map, node)) { + return false; + } + return true; + }); + } + + filterOutCollections(nodes = []) { + return nodes.filter((node) => !node.startsWith(GlobalDependencyMap.COLLECTION_PREFIX)); + } + + static removeLayoutNodes(graph, nodeList) { + return nodeList.filter((node) => { + if (this.isLayoutNode(graph, node)) { + return false; + } + return true; + }); + } + + removeLayoutNodes(normalizedLayouts) { + let nodes = this.map.overallOrder(); + for (let node of nodes) { + if (!GlobalDependencyMap.isLayoutNode(this.map, node)) { + 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 }); + this.#map = new TemplateDepGraph(); + } + + 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 []; + } + + node = this.normalizeNode(node); + + if (!this.map.hasNode(node)) { + return []; + } + + // 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) + .map((entry) => GlobalDependencyMap.getTagName(entry)) + .filter(Boolean); + + 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 collectionKey = GlobalDependencyMap.getCollectionKeyForEntry(name); + if (!this.map.hasNode(collectionKey)) { + continue; + } + for (let node of this.map.dependantsOf(collectionKey)) { + if (!node.startsWith(GlobalDependencyMap.COLLECTION_PREFIX)) { + if (!GlobalDependencyMap.isLayoutNode(this.map, node)) { + templates.add(node); + } + } + } + } + return templates; + } + + static isLayoutNode(graph, node) { + if (!graph.hasNode(node)) { + return false; + } + return graph.getNodeData(node)?.type === GlobalDependencyMap.LAYOUT_KEY; + } + + getLayoutsUsedBy(node) { + node = this.normalizeNode(node); + + if (!this.map.hasNode(node)) { + return []; + } + + let layouts = []; + + // include self, if layout + if (GlobalDependencyMap.isLayoutNode(this.map, node)) { + layouts.push(node); + } + + this.map.dependantsOf(node).forEach((node) => { + // we only want layouts + if (GlobalDependencyMap.isLayoutNode(this.map, node)) { + 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; + } + + if (includeLayouts) { + return this.map.dependenciesOf(node).filter(Boolean); + } + + return GlobalDependencyMap.removeLayoutNodes(this.map, this.map.dependenciesOf(node)); + } + + #addNode(name) { + if (this.map.hasNode(name)) { + return; + } + + this.map.addNode(name); + } + + // node arguments are already normalized + #addDependency(from, toArray = []) { + this.#addNode(from); // only if not already added + + 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) { + this.#addNode(to); // only if not already added + if (from !== to) { + this.map.addDependency(from, to); + } + } + } + + addDependency(from, toArray = []) { + this.#addDependency( + this.normalizeNode(from), + toArray.map((to) => this.normalizeNode(to)), + ); + } + + addNewNodeRelationships(from, consumes = [], publishes = []) { + consumes = consumes.filter(Boolean); + publishes = publishes.filter(Boolean); + + debug("%o consumes %o and publishes to %o", from, consumes, publishes); + from = this.normalizeNode(from); + + this.map.addTemplate(from, consumes, publishes); + } + + // 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; + } + + getTemplateOrder() { + let order = []; + for (let entry of this.map.overallOrder()) { + order.push(entry); + } + + return order; + } + + 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 TemplateDepGraph(); + + // 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/LayoutCache.js b/node_modules/@11ty/eleventy/src/LayoutCache.js new file mode 100644 index 0000000..006f502 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/LayoutCache.js @@ -0,0 +1,98 @@ +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 LayoutCache { + constructor() { + this.cache = {}; + this.cacheByInputPath = {}; + } + + clear() { + this.cache = {}; + this.cacheByInputPath = {}; + } + + // alias + removeAll() { + for (let layoutFilePath in this.cacheByInputPath) { + this.remove(layoutFilePath); + } + 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 LayoutCache->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 LayoutCache.`); + } + + 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 LayoutCache(); + +eventBus.on("eleventy.resourceModified", () => { + // https://github.com/11ty/eleventy-plugin-bundle/issues/10 + layoutCache.removeAll(); +}); + +// singleton +export default layoutCache; 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..304c0a2 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Plugins/HtmlBasePlugin.js @@ -0,0 +1,160 @@ +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, htmlContext } = opts; + + // Warning, this will not work with HtmlTransformer, as we’ll receive "false" (string) here instead of `false` (boolean) + if (url === false) { + throw new Error( + `Invalid url transformed in the HTML \`\` plugin.${url === false ? ` Did you attempt to link to a \`permalink: false\` page?` : ""} Received: ${url}`, + ); + } + + // 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 `baseHref` 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, htmlContext) => { + return transformUrl(url.trim(), base, { + pathPrefix: eleventyConfig.pathPrefix, + pageUrl: pageUrlOverride || this.page?.url, + htmlContext, + }); + }); + }, + ); + + // Apply to all HTML output in your project + eleventyConfig.htmlTransformer.addUrlTransform( + opts.extensions, + + /** @this {object} */ + function (urlInMarkup, htmlContext) { + // 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, + htmlContext, + }); + }, + { + priority: -2, // priority is descending, so this runs last (especially after AutoCopy and InputPathToUrl transform) + enabled: function (context) { + // Enabled when pathPrefix is non-default or via renderTransforms + return Boolean(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/HtmlRelativeCopyPlugin.js b/node_modules/@11ty/eleventy/src/Plugins/HtmlRelativeCopyPlugin.js new file mode 100644 index 0000000..ac1391d --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Plugins/HtmlRelativeCopyPlugin.js @@ -0,0 +1,52 @@ +import { HtmlRelativeCopy } from "../Util/HtmlRelativeCopy.js"; + +// one HtmlRelativeCopy instance per entry +function init(eleventyConfig, options) { + let opts = Object.assign( + { + extensions: "html", + match: false, // can be one glob string or an array of globs + paths: [], // directories to also look in for files + failOnError: true, // fails when a path matches (via `match`) but not found on file system + copyOptions: undefined, + }, + options, + ); + + let htmlrel = new HtmlRelativeCopy(); + htmlrel.setUserConfig(eleventyConfig); + htmlrel.addMatchingGlob(opts.match); + htmlrel.setFailOnError(opts.failOnError); + htmlrel.setCopyOptions(opts.copyOptions); + + eleventyConfig.htmlTransformer.addUrlTransform( + opts.extensions, + function (targetFilepathOrUrl) { + // @ts-ignore + htmlrel.copy(targetFilepathOrUrl, this.page.inputPath, this.page.outputPath); + + // TODO front matter option for manual copy + return targetFilepathOrUrl; + }, + { + enabled: () => htmlrel.isEnabled(), + // - MUST run after other plugins but BEFORE HtmlBase plugin + priority: -1, + }, + ); + + htmlrel.addPaths(opts.paths); +} + +function HtmlRelativeCopyPlugin(eleventyConfig) { + // Important: if this is empty, no URL transforms are added + for (let options of eleventyConfig.passthroughCopiesHtmlRelative) { + init(eleventyConfig, options); + } +} + +Object.defineProperty(HtmlRelativeCopyPlugin, "eleventyPackage", { + value: "@11ty/eleventy/html-relative-copy-plugin", +}); + +export { HtmlRelativeCopyPlugin }; 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..a55a13e --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Plugins/IdAttributePlugin.js @@ -0,0 +1,110 @@ +import matchHelper from "posthtml-match-helper"; +import { decodeHTML } from "entities"; + +import slugifyFilter from "../Filters/Slugify.js"; +import MemoizeUtil from "../Util/MemoizeFunction.js"; + +const POSTHTML_PLUGIN_NAME = "11ty/eleventy/id-attribute"; + +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 idAttributePosthtmlPlugin(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( + 'You have more than one HTML `id` attribute using the same value (id="' + + id + + '") in your template (' + + pluginOptions.page.inputPath + + "). You can disable this error in the IdAttribute plugin with the `checkDuplicates: false` option.", + ); + } + } 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 + name: POSTHTML_PLUGIN_NAME, + }, + ); +} + +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..aca148b --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Plugins/InputPathToUrl.js @@ -0,0 +1,191 @@ +import path from "node:path"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import isValidUrl from "../Util/ValidUrl.js"; + +function getValidPath(contentMap, testPath) { + // if the path is coming from Markdown, it may be encoded + let normalized = TemplatePath.addLeadingDotSlash(decodeURIComponent(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) { + if (filepath.startsWith("#") || filepath.startsWith("?")) { + return [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, ""); // includes ? + filepath = filepath.replace(u.hash, ""); // includes # + + 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); + if (targetFilePath) { + targetFilePath = normalizeInputPath( + targetFilePath, + inputDir, + // @ts-ignore + 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); + if (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..8e5b1de --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Plugins/Pagination.js @@ -0,0 +1,379 @@ +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]) || + Boolean(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) { + 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..974b0e1 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Plugins/RenderPlugin.js @@ -0,0 +1,520 @@ +import fs from "node: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 EleventyExtensionMap from "../EleventyExtensionMap.js"; +import TemplateEngineManager from "../Engines/TemplateEngineManager.js"; +import Liquid from "../Engines/Liquid.js"; + +class EleventyNunjucksError extends EleventyBaseError {} + +/** @this {object} */ +async function compile(content, templateLang, options = {}) { + let { templateConfig, extensionMap } = options; + let strictMode = options.strictMode ?? false; + + 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; + } + + if (!extensionMap) { + if (strictMode) { + throw new Error("Internal error: missing `extensionMap` in RenderPlugin->compile."); + } + extensionMap = new EleventyExtensionMap(templateConfig); + extensionMap.engineManager = new TemplateEngineManager(templateConfig); + } + 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; + let strictMode = options.strictMode ?? false; + if (!inputPath) { + throw new Error("Missing file path argument passed to the `renderFile` shortcode."); + } + + 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 normalizedPath = TemplatePath.normalizeOperatingSystemFilePath(inputPath); + // Prefer the exists cache, if it’s available + if (!templateConfig.existsCache.exists(normalizedPath)) { + throw new Error( + "Could not find render plugin file for the `renderFile` shortcode, looking for: " + inputPath, + ); + } + + if (!extensionMap) { + if (strictMode) { + throw new Error("Internal error: missing `extensionMap` in RenderPlugin->compileFile."); + } + + extensionMap = new EleventyExtensionMap(templateConfig); + extensionMap.engineManager = new TemplateEngineManager(templateConfig); + } + 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 = {}) { + let templateConfig; + eleventyConfig.on("eleventy.config", (tmplConfigInstance) => { + templateConfig = tmplConfigInstance; + }); + + let extensionMap; + eleventyConfig.on("eleventy.extensionmap", (map) => { + extensionMap = map; + }); + + /** + * @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 {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; + } + + // TODO Render plugin `templateLang` is feeding bad input paths to the addDependencies call in Custom.js + 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; + #extensionMap; + #templateConfig; + + constructor() { + this.templateConfig = new TemplateConfig(null, false); + this.templateConfig.setDirectories(new ProjectDirectories()); + } + + get templateConfig() { + return this.#templateConfig; + } + + set templateConfig(templateConfig) { + if (!templateConfig || templateConfig === this.#templateConfig) { + return; + } + + this.#templateConfig = templateConfig; + + // This is the only plugin running on the Edge + this.#templateConfig.userConfig.addPlugin(eleventyRenderPlugin, { + templateConfig: this.#templateConfig, + accessGlobalData: true, + }); + + this.#extensionMap = new EleventyExtensionMap(this.#templateConfig); + this.#extensionMap.engineManager = new TemplateEngineManager(this.#templateConfig); + } + + 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(); + + options.templateConfig = this.templateConfig; + options.extensionMap = this.#extensionMap; + options.strictMode = true; + + // 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..64c4709 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Template.js @@ -0,0 +1,1200 @@ +import util from "node:util"; +import os from "node:os"; +import path from "node:path"; +import fs from "node: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"; +import { FileSystemManager } from "./Util/FileSystemManager.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 { + #logger; + #fsManager; + + 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.templateData = templateData; + this.#initFileSlug(); + + this.linters = []; + this.transforms = {}; + + 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); + } + + #initFileSlug() { + this.fileSlug = new TemplateFileSlug(this.inputPath, this.extensionMap, this.eleventyConfig); + this.fileSlugStr = this.fileSlug.getSlug(); + this.filePathStem = this.fileSlug.getFullPathWithoutExtension(); + } + + /* mimic constructor arg order */ + resetCachedTemplate({ templateData, extensionMap, eleventyConfig }) { + super.resetCachedTemplate({ eleventyConfig }); + this.templateData = templateData; + this.extensionMap = extensionMap; + // this.#fsManager = undefined; + this.#initFileSlug(); + } + + get fsManager() { + if (!this.#fsManager) { + this.#fsManager = new FileSystemManager(this.eleventyConfig); + } + return this.#fsManager; + } + + 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() { + let dir = TemplatePath.absolutePath(this.parsed.dir); + let inputDir = TemplatePath.absolutePath(this.inputDir); + return TemplatePath.stripLeadingSubPath(dir, inputDir); + } + + templateUsesLayouts(pageData) { + if (this.hasTemplateRender()) { + return pageData?.[this.config.keys.layout] && this.templateRender.engine.useLayouts(); + } + + // If `layout` prop is set, default to true when engine is unknown + return Boolean(pageData?.[this.config.keys.layout]); + } + + 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("Internal error: data argument missing in Template->_getLink"); + } + + let permalink = + data[this.config.keys.permalink] ?? + data?.[this.config.keys.computed]?.[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 tr = await this.getTemplateRender(); + let permalinkCompilation = tr.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 = {}; + let tr = await this.getTemplateRender(); + if (tr.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; + } + + setLinters(linters) { + if (!isPlainObject(linters)) { + throw new Error("Object expected in setLinters"); + } + // this acts as a reset + this.linters = []; + for (let linter of Object.values(linters).filter((l) => typeof l === "function")) { + this.addLinter(linter); + } + } + + 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, + }); + } + + async #renderComputedUnit(entry, data) { + if (typeof entry === "string") { + return this.renderComputedData(entry, data); + } + + if (isPlainObject(entry)) { + for (let key in entry) { + entry[key] = await this.#renderComputedUnit(entry[key], data); + } + } + + if (Array.isArray(entry)) { + for (let j = 0, k = entry.length; j < k; j++) { + entry[j] = await this.#renderComputedUnit(entry[j], data); + } + } + + return entry; + } + + _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) || typeof obj === "string") { + // Arrays are treated as one entry in the dependency graph now, Issue #3728 + computedData.addTemplateString( + parentKey, + async function (innerData) { + return this.tmpl.#renderComputedUnit(obj, innerData); + }, + declaredDependencies, + this.getParseForSymbolsFunction(obj), + this, + ); + } else if (isPlainObject(obj)) { + // Arrays used to be computed here + for (let key in obj) { + let keys = []; + if (parentKey) { + keys.push(parentKey); + } + keys.push(key); + this._addComputedEntry(computedData, obj[key], keys.join("."), declaredDependencies); + } + } 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); + return 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 []; + } + + // Raw Input *includes* preprocessor modifications + // 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) { + if (this.logger.isLoggingEnabled()) { + let isVirtual = this.isVirtualTemplate(); + let tr = await this.getTemplateRender(); + let engineList = tr.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(); + + if (this.eleventyConfig.templateHandling?.writeMode === "async") { + await this.fsManager.createDirectoryForFile(outputPath); + } else { + this.fsManager.createDirectoryForFileSync(outputPath); + } + + 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(); + + if (this.eleventyConfig.templateHandling?.writeMode === "async") { + await this.fsManager.writeFile(outputPath, finalContent); + } else { + this.fsManager.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 + // Does not yet include .computedData + 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) { + 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?.constructor?.name === "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; + } + + if (typeof dateValue !== "string") { + throw new Error( + `Data cascade value for \`date\` (${dateValue}) is invalid for ${this.inputPath}. Expected a JavaScript Date instance, luxon DateTime instance, or String value.`, + ); + } + + // special strings + if (!this.isVirtualTemplate()) { + if (dateValue.toLowerCase() === "git last modified") { + let d = await 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 = await 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/TemplateCollection.js b/node_modules/@11ty/eleventy/src/TemplateCollection.js new file mode 100755 index 0000000..6e99a32 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateCollection.js @@ -0,0 +1,77 @@ +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 = new Set(TemplateData.getIncludedTagNames(item.data)); + return tags.every((requiredTag) => { + return itemTags.has(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..e1fff8f --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateConfig.js @@ -0,0 +1,565 @@ +import fs from "node:fs"; +import chalk from "kleur"; +import { Merge, TemplatePath, isPlainObject } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import { EleventyImportRaw } 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(); + #existsCache = new ExistsCache(); + #usesGraph; + #previousBuildModifiedFile; + + 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; + + this.userConfig.events.on("eleventy#templateModified", (inputPath, metadata = {}) => { + // Might support multiple at some point + this.setPreviousBuildModifiedFile(inputPath, metadata); + + // Issue #3569, set that this file exists in the cache + this.#existsCache.set(inputPath, true); + }); + } + + setPreviousBuildModifiedFile(inputPath, metadata = {}) { + this.#previousBuildModifiedFile = inputPath; + } + + getPreviousBuildModifiedFile() { + return this.#previousBuildModifiedFile; + } + + 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(); + + let configFile = configFiles.find((path) => path && fs.existsSync(path)); + if (configFile) { + return configFile; + } + } + + getLocalProjectConfigFiles() { + let paths = this.projectConfigPaths; + if (paths?.length > 0) { + return TemplatePath.addLeadingDotSlashArray(paths.filter((path) => Boolean(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(); + this.usesGraph.reset(); // needs to be before forceReloadConfig #3711 + + // await this.initializeRootConfig(); + await this.forceReloadConfig(); + + // 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 import("./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; + + 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() { + 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..97d440f --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateContent.js @@ -0,0 +1,748 @@ +import os from "node:os"; + +import fs from "node:fs"; +import matter from "gray-matter"; +import lodash from "@11ty/lodash-custom"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +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"; + +import { withResolvers } from "./Util/PromiseUtil.js"; + +const { set: lodashSet } = lodash; +const debug = debugUtil("Eleventy:TemplateContent"); +const debugDev = debugUtil("Dev:Eleventy:TemplateContent"); + +class TemplateContentFrontMatterError extends EleventyBaseError {} +class TemplateContentCompileError extends EleventyBaseError {} +class TemplateContentRenderError extends EleventyBaseError {} + +class TemplateContent { + #initialized = false; + #config; + #templateRender; + #preprocessorEngine; + #extensionMap; + #configOptions; + + constructor(inputPath, templateConfig) { + if (!templateConfig || templateConfig.constructor.name !== "TemplateConfig") { + throw new Error("Missing or invalid `templateConfig` argument"); + } + this.eleventyConfig = templateConfig; + this.inputPath = inputPath; + } + + async asyncTemplateInitialization() { + if (!this.hasTemplateRender()) { + await this.getTemplateRender(); + } + + if (this.#initialized) { + return; + } + this.#initialized = true; + + let preprocessorEngineName = this.templateRender.getPreprocessorEngineName(); + if (preprocessorEngineName && this.templateRender.engine.getName() !== preprocessorEngineName) { + let engine = await this.templateRender.getEngineByName(preprocessorEngineName); + this.#preprocessorEngine = engine; + } + } + + resetCachedTemplate({ eleventyConfig }) { + this.eleventyConfig = eleventyConfig; + } + + 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; + } + if (types.render) { + this.#templateRender = undefined; + } + } + + get extensionMap() { + if (!this.#extensionMap) { + throw new Error("Internal error: Missing `extensionMap` in TemplateContent."); + } + 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 Error("Tried to get an TemplateConfig but none was found."); + } + } + + get eleventyConfig() { + if (this.#config.constructor.name === "TemplateConfig") { + return this.#config; + } + throw new Error("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; + + return this.#templateRender.init().then(() => { + return this.#templateRender; + }); + } + + 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 === "") { + let tr = await this.getTemplateRender(); + if (tr.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); + + 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 tr = await this.getTemplateRender(); + let extraData = await tr.engine.getExtraDataFromFile(this.inputPath); + + let virtualTemplateDefinition = this.getVirtualTemplateDefinition(); + let virtualTemplateData; + if (virtualTemplateDefinition) { + virtualTemplateData = virtualTemplateDefinition.data; + } + + let data = Object.assign(fm.data, extraData, virtualTemplateData); + + TemplateData.cleanupData(data, { + file: this.inputPath, + isVirtualTemplate: Boolean(virtualTemplateData), + }); + + return { + data, + excerpt: fm.excerpt, + }; + } + + async getFrontMatterData() { + if (!this._frontMatterDataCache) { + // @cachedproperty + this._frontMatterDataCache = this.#getFrontMatterData(); + } + + return this._frontMatterDataCache; + } + + async getEngineOverride() { + return this.getFrontMatterData().then((data) => { + return data[this.config.keys.engineOverride]; + }); + } + + // checks engines + isTemplateCacheable() { + if (this.#preprocessorEngine) { + return this.#preprocessorEngine.cacheable; + } + return this.engine.cacheable; + } + + _getCompileCache(str) { + // Caches used to be bifurcated based on engine name, now they’re based on inputPath + // TODO does `cacheable` need to help inform whether a cache is used here? + let inputPathMap = TemplateContent._compileCache.get(this.inputPath); + if (!inputPathMap) { + inputPathMap = new Map(); + TemplateContent._compileCache.set(this.inputPath, inputPathMap); + } + + let cacheable = this.isTemplateCacheable(); + 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; + + // Must happen before cacheable fetch below + // Likely only necessary for Eleventy Layouts, see TemplateMap->initDependencyMap + await this.asyncTemplateInitialization(); + + // this.templateRender is guaranteed here + 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 + let withRes = withResolvers(); + res = withRes.resolve; + + cache.set(key, withRes.promise); + } + } + + 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 + if (this.#preprocessorEngine) { + engine = this.#preprocessorEngine; + } + + if ("parseForSymbols" in engine) { + return () => { + if (Array.isArray(str)) { + return str + .filter((entry) => typeof entry === "string") + .map((entry) => engine.parseForSymbols(entry)) + .flat(); + } + if (typeof str === "string") { + return engine.parseForSymbols(str); + } + return []; + }; + } + } + + // 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 tr = await this.getTemplateRender(); + let permalinkCompilation = tr.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 && typeof permalink !== "function") { + 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, { + type: "Content", + bypassMarkdown, + }); + } + + _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", () => { + 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..f8526f2 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateLayout.js @@ -0,0 +1,240 @@ +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 layoutCache from "./LayoutCache.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 (!layoutCache.has(fullKey)) { + let layout = new TemplateLayout(key, extensionMap, eleventyConfig); + + layoutCache.add(layout); + debugDev("Added %o to LayoutCache", key); + + return layout; + } + + return layoutCache.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(); + return this.compile(rawInput); + } + + // 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 LayoutCache after error."); + layoutCache.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..9f5a8ee --- /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, templateConfig) { + if (!templateConfig) { + throw new Error("Expected `templateConfig` in TemplateLayoutPathResolver constructor"); + } + + this.templateConfig = templateConfig; + 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.templateConfig.directories.getLayoutPathRelativeToInputDirectory(layoutPath); + return this.config.virtualTemplates[inputDirRelativePath]; + } + + get dirs() { + return this.templateConfig.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.templateConfig) { + throw new Error("Internal error: Missing this.templateConfig"); + } + + return this.templateConfig.getConfig(); + } + + exists(layoutPath) { + if (this.getVirtualTemplate(layoutPath)) { + return true; + } + let fullPath = this.templateConfig.directories.getLayoutPath(layoutPath); + if (this.templateConfig.existsCache.exists(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.templateConfig.directories.getLayoutPath(this.path); + } else if (useLayoutResolution) { + this.filename = this.findFileName(); + this.fullPath = this.templateConfig.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..52cceb1 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateMap.js @@ -0,0 +1,684 @@ +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"; +import GlobalDependencyMap from "./GlobalDependencyMap.js"; + +const debug = debugUtil("Eleventy:TemplateMap"); + +class EleventyMapPagesError 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 +]; + +// must match TemplateDepGraph +const SPECIAL_COLLECTION_NAMES = { + keys: "[keys]", + all: "all", +}; + +class TemplateMap { + #dependencyMapInitialized = false; + + constructor(eleventyConfig) { + if (!eleventyConfig || eleventyConfig.constructor.name !== "TemplateConfig") { + throw new Error("Missing or invalid `eleventyConfig` 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; + } + + 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 === "collections") { + // special, means targeting `collections` specifically + return SPECIAL_COLLECTION_NAMES.keys; + } + + if (str.startsWith("collections.")) { + return str.slice("collections.".length); + } + + // Fixes #2851 + if (str.startsWith("collections['") || str.startsWith('collections["')) { + return str.slice("collections['".length, -2); + } + } + + getPaginationTagTarget(entry) { + if (entry.data.pagination?.data) { + return this.getTagTarget(entry.data.pagination.data); + } + } + + #addEntryToGlobalDependencyGraph(entry) { + let consumes = []; + consumes.push(this.getPaginationTagTarget(entry)); + + if (Array.isArray(entry.data.eleventyImport?.collections)) { + for (let tag of entry.data.eleventyImport.collections) { + consumes.push(tag); + } + } + + // Important: consumers must come before publishers + + // TODO it’d be nice to set the dependency relationship for addCollection here + // But collections are not yet populated (they populate after template order) + let publishes = TemplateData.getIncludedCollectionNames(entry.data); + + this.config.uses.addNewNodeRelationships(entry.inputPath, consumes, publishes); + } + + addAllToGlobalDependencyGraph() { + this.#dependencyMapInitialized = true; + + // Should come before individual entry additions + this.config.uses.initializeUserConfigurationApiCollections(); + + 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(fullTemplateOrder) { + // Temporary workaround for async constructor work in templates + // Issue #3170 #3870 + let inputPathSet = new Set(fullTemplateOrder); + await Promise.all( + this.map + .filter(({ inputPath }) => { + return inputPathSet.has(inputPath); + }) + .map(({ template }) => { + // This also happens for layouts in TemplateContent->compile + return template.asyncTemplateInitialization(); + }), + ); + + for (let depEntry of fullTemplateOrder) { + if (GlobalDependencyMap.isCollection(depEntry)) { + let tagName = GlobalDependencyMap.getTagName(depEntry); + // [keys] should initialize `all` + if (tagName === SPECIAL_COLLECTION_NAMES.keys) { + await this.setCollectionByTagName("all"); + // [NAME] is special and implied (e.g. [keys]) + } else if (!tagName.startsWith("[") && !tagName.endsWith("]")) { + // is a tag (collection) entry + await this.setCollectionByTagName(tagName); + } + continue; + } + + // is a template entry + let map = this.getMapEntryForInputPath(depEntry); + await this.#initDependencyMapEntry(map); + } + } + + async #initDependencyMapEntry(map) { + try { + map._pages = await map.template.getTemplates(map.data); + } catch (e) { + throw new EleventyMapPagesError( + "Error generating template page(s) for " + map.inputPath + ".", + e, + ); + } + + 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++; + } + } + } + + getTemplateOrder() { + // 1. Templates that don’t use Pagination + // 2. Pagination templates that consume config API collections + // 3. Pagination templates consuming `collections` + // 4. Pagination templates consuming `collections.all` + let fullTemplateOrder = this.config.uses.getTemplateOrder(); + + return fullTemplateOrder + .map((entry) => { + if (GlobalDependencyMap.isCollection(entry)) { + return entry; + } + + let inputPath = TemplatePath.addLeadingDotSlash(entry); + if (!this.hasMapEntryForInputPath(inputPath)) { + return false; + } + return inputPath; + }) + .filter(Boolean); + } + + async cache() { + if (!this.#dependencyMapInitialized) { + this.addAllToGlobalDependencyGraph(); + } + + this.collectionsData = {}; + + for (let entry of this.map) { + entry.data.collections = this.collectionsData; + } + + let fullTemplateOrder = this.getTemplateOrder(); + debug( + "Rendering templates in order (%o concurrency): %O", + this.userConfig.getConcurrency(), + fullTemplateOrder, + ); + + await this.initDependencyMap(fullTemplateOrder); + await this.resolveRemainingComputedData(); + + let orderedPaths = this.#removeTagsFromTemplateOrder(fullTemplateOrder); + + 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; + } + + hasMapEntryForInputPath(inputPath) { + return Boolean(this.getMapEntryForInputPath(inputPath)); + } + + // TODO(slightlyoff): hot inner loop? + getMapEntryForInputPath(inputPath) { + let absoluteInputPath = TemplatePath.absolutePath(inputPath); + return this.map.find((entry) => { + if (entry.inputPath === inputPath || entry.inputPath === absoluteInputPath) { + return entry; + } + }); + } + + #removeTagsFromTemplateOrder(maps) { + return maps.filter((dep) => !GlobalDependencyMap.isCollection(dep)); + } + + 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()); + + // Get concurrency level from user config + const concurrency = this.userConfig.getConcurrency(); + + // Process the templates in chunks to limit concurrency + // This replaces the functionality of p-map's concurrency option + for (let i = 0; i < filteredMap.length; i += concurrency) { + // Create a chunk of tasks that will run in parallel + const chunk = filteredMap.slice(i, i + concurrency); + + // Run the chunk of tasks in parallel + await Promise.all( + chunk.map(async (map) => { + 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)) { + // Add to list of templates that need to be processed again + usedTemplateContentTooEarlyMap.push(map); + + // Reset cached render promise + for (let pageEntry of map._pages) { + pageEntry.template.resetCaches({ render: true }); + } + } else { + throw e; + } + } + }), + ); + } + + // Process templates that had premature template content errors + // This is the second pass for templates that couldn't be rendered in the first pass + 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)) { + // If we still have template content errors after the second pass, + // it's likely a circular reference + 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); + } + + // May not return an array (can be anything) + // https://www.11ty.dev/docs/collections-api/#return-values + 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); + + // May not return an array (can be anything) + // https://www.11ty.dev/docs/collections-api/#return-values + 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(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; + if (tmpl.templateUsesLayouts(page.data)) { + let layoutKey = page.data[this.config.keys.layout]; + 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 outputPaths = {}; + 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 (!outputPaths[page.outputPath]) { + outputPaths[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} +${outputPaths[page.outputPath] + .map(function (inputPath, index) { + return ` ${index + 2}. ${inputPath}\n`; + }) + .join("")} +`; + outputPaths[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..b27b634 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplatePassthrough.js @@ -0,0 +1,389 @@ +import path from "node:path"; + +import { isDynamicPattern } from "tinyglobby"; +import { filesize } from "filesize"; +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 debug = debugUtil("Eleventy:TemplatePassthrough"); + +class TemplatePassthroughError extends EleventyBaseError {} + +class TemplatePassthrough { + isDryRun = false; + #isInputPathGlob; + #benchmarks; + #isAlreadyNormalized = false; + #projectDirCheck = false; + + // paths already guaranteed from the autocopy plugin + static factory(inputPath, outputPath, opts = {}) { + let p = new TemplatePassthrough( + { + inputPath, + outputPath, + copyOptions: opts.copyOptions, + }, + opts.templateConfig, + ); + + return p; + } + + constructor(path, templateConfig) { + if (!templateConfig || templateConfig.constructor.name !== "TemplateConfig") { + throw new Error( + "Internal error: Missing `templateConfig` or was not an instance of `TemplateConfig`.", + ); + } + this.templateConfig = templateConfig; + + 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.normalizeIfDirectory(path.inputPath); + this.#isInputPathGlob = isDynamicPattern(this.inputPath); + + this.outputPath = path.outputPath; + this.copyOptions = path.copyOptions; // custom options for recursive-copy + } + + get benchmarks() { + if (!this.#benchmarks) { + this.#benchmarks = { + aggregate: this.config.benchmarkManager.get("Aggregate"), + }; + } + + return this.#benchmarks; + } + + get config() { + return this.templateConfig.getConfig(); + } + + get directories() { + return this.templateConfig.directories; + } + + // inputDir is used when stripping from output path in `getOutputPath` + get inputDir() { + return this.templateConfig.directories.input; + } + + get outputDir() { + return this.templateConfig.directories.output; + } + + // Skips `getFiles()` normalization + setIsAlreadyNormalized(isNormalized) { + this.#isAlreadyNormalized = Boolean(isNormalized); + } + + setCheckSourceDirectory(check) { + this.#projectDirCheck = Boolean(check); + } + + /* { 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 && + this.isExists(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 = Boolean(isDryRun); + } + + setRunMode(runMode) { + this.runMode = runMode; + } + + 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(); + + if (!this.fileSystemSearch) { + throw new Error("Internal error: Missing `fileSystemSearch` property."); + } + + // TODO perf this globs once per addPassthroughCopy entry + let files = TemplatePath.addLeadingDotSlashArray( + await this.fileSystemSearch.search("passthrough", glob, { + ignore: [ + // *only* ignores output dir (not node_modules!) + this.outputDir, + ], + }), + ); + b.after(); + return files; + } + + isExists(filePath) { + return this.templateConfig.existsCache.exists(filePath); + } + + isDirectory(filePath) { + return this.templateConfig.existsCache.isDirectory(filePath); + } + + // dir is guaranteed to exist by context + // dir may not be a directory + normalizeIfDirectory(input) { + if (typeof input === "string") { + if (input.endsWith(path.sep) || input.endsWith("/")) { + return input; + } + + // 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(input)) { + return `${input}/`; + } + } + + return input; + } + + // maps input paths to output paths + async getFileMap() { + if (this.#isAlreadyNormalized) { + return [ + { + inputPath: this.inputPath, + outputPath: this.outputPath, + }, + ]; + } + + // TODO VirtualFileSystem candidate + if (!isDynamicPattern(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 (this.#projectDirCheck && !this.directories.isFileInProjectFolder(src)) { + return Promise.reject( + new TemplatePassthroughError( + "Source file is not in the project directory. Check your passthrough paths.", + ), + ); + } + + if (!this.directories.isFileInOutputFolder(dest)) { + 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` + map[copyOp.src] = copyOp.dest; + b.before(); + }) + .on(copy.events.COPY_FILE_COMPLETE, (copyOp) => { + fileCopyCount++; + fileSizeCount += copyOp.stats.size; + if (copyOp.stats.size > 5000000) { + debug(`Copied %o (⚠️ large) file from %o`, filesize(copyOp.stats.size), copyOp.src); + } else { + debug(`Copied %o file from %o`, filesize(copyOp.stats.size), copyOp.src); + } + b.after(); + }) + .then( + () => { + return { + count: fileCopyCount, + size: fileSizeCount, + map, + }; + }, + (error) => { + if (copyOptions.overwrite === false && error.code === "EEXIST") { + // just ignore if the output already exists and overwrite: false + debug("Overwrite error ignored: %O", error); + return { + count: 0, + size: 0, + map, + }; + } + + return Promise.reject(error); + }, + ); + } + + 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..114dfa9 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplatePassthroughManager.js @@ -0,0 +1,368 @@ +import { isDynamicPattern } from "tinyglobby"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import debugUtil from "debug"; + +import EleventyBaseError from "./Errors/EleventyBaseError.js"; +import TemplatePassthrough from "./TemplatePassthrough.js"; +import checkPassthroughCopyBehavior from "./Util/PassthroughCopyBehaviorCheck.js"; +import { isGlobMatch } from "./Util/GlobMatcher.js"; +import { withResolvers } from "./Util/PromiseUtil.js"; + +const debug = debugUtil("Eleventy:TemplatePassthroughManager"); + +class TemplatePassthroughManagerCopyError extends EleventyBaseError {} + +class TemplatePassthroughManager { + #isDryRun = false; + #afterBuild; + #queue = new Map(); + #extensionMap; + + constructor(templateConfig) { + if (!templateConfig || templateConfig.constructor.name !== "TemplateConfig") { + throw new Error("Internal error: Missing or invalid `templateConfig` argument."); + } + + this.templateConfig = templateConfig; + this.config = templateConfig.getConfig(); + + // eleventy# event listeners are removed on each build + this.config.events.on("eleventy#copy", ({ source, target, options }) => { + this.enqueueCopy(source, target, options); + }); + + this.config.events.on("eleventy#beforerender", () => { + this.#afterBuild = withResolvers(); + }); + + this.config.events.on("eleventy#render", () => { + let { resolve } = this.#afterBuild; + resolve(); + }); + + this.reset(); + } + + reset() { + this.count = 0; + this.size = 0; + this.conflictMap = {}; + this.incrementalFile; + + this.#queue = new Map(); + } + + set extensionMap(extensionMap) { + this.#extensionMap = extensionMap; + } + + get extensionMap() { + if (!this.#extensionMap) { + throw new Error("Internal error: missing `extensionMap` in TemplatePassthroughManager."); + } + return this.#extensionMap; + } + + get inputDir() { + return this.templateConfig.directories.input; + } + + get outputDir() { + return this.templateConfig.directories.output; + } + + setDryRun(isDryRun) { + this.#isDryRun = Boolean(isDryRun); + } + + setRunMode(runMode) { + this.runMode = runMode; + } + + setIncrementalFile(path) { + if (path) { + this.incrementalFile = path; + } + } + + resetIncrementalFile() { + this.incrementalFile = undefined; + } + + _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; + } + + getMetadata() { + return { + copyCount: this.getCopyCount(), + copySize: this.getCopySize(), + }; + } + + setFileSystemSearch(fileSystemSearch) { + this.fileSystemSearch = fileSystemSearch; + } + + getTemplatePassthroughForPath(path) { + let inst = new TemplatePassthrough(path, this.templateConfig); + + inst.setFileSystemSearch(this.fileSystemSearch); + 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]) { + let paths = [src, this.conflictMap[dest]].sort(); + throw new TemplatePassthroughManagerCopyError( + `Multiple passthrough copy files are trying to write to the same output file (${TemplatePath.standardizeFilePath(dest)}). ${paths.map((p) => TemplatePath.standardizeFilePath(p)).join(" and ")}`, + ); + } 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, + ); + } + } + + 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 && + isDynamicPattern(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 [isPassthrough]; + } + + 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; + } + + async #waitForTemplatesRendered() { + if (!this.#afterBuild) { + return Promise.resolve(); // immediately resolve + } + + let { promise } = this.#afterBuild; + return promise; + } + + enqueueCopy(source, target, copyOptions) { + let key = `${source}=>${target}`; + + // light de-dupe the same source/target combo (might be in the same file, might be viaTransforms) + if (this.#queue.has(key)) { + return; + } + + let passthrough = TemplatePassthrough.factory(source, target, { + templateConfig: this.templateConfig, + copyOptions, + }); + + passthrough.setCheckSourceDirectory(true); + passthrough.setIsAlreadyNormalized(true); + passthrough.setRunMode(this.runMode); + passthrough.setDryRun(this.#isDryRun); + + this.#queue.set(key, this.copyPassthrough(passthrough)); + } + + async copyAll(templateExtensionPaths) { + debug("TemplatePassthrough copy started."); + let normalizedPaths = this.getAllNormalizedPaths(templateExtensionPaths); + + let passthroughs = normalizedPaths.map((path) => this.getTemplatePassthroughForPath(path)); + + let promises = passthroughs.map((pass) => this.copyPassthrough(pass)); + + await this.#waitForTemplatesRendered(); + + for (let [key, afterBuildCopyPromises] of this.#queue) { + promises.push(afterBuildCopyPromises); + } + + 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..9ad5111 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplatePermalink.js @@ -0,0 +1,195 @@ +import path from "node: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) { + if (typeof buildLink !== "string") { + let stringToString = "toString" in buildLink ? `:\n\n${buildLink.toString()}` : ""; + throw new Error( + "Expected permalink value to be a string. Received `" + + typeof buildLink + + "`" + + stringToString, + ); + } + 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 TemplatePath.addLeadingDotSlash(TemplatePath.normalize(outputDir + "/" + uri)); + } + + toPathFromRoot() { + if (!this.buildLink) { + return false; + } + + let uri = this.toOutputPath(); + + if (uri === false) { + return false; + } + + return TemplatePath.addLeadingDotSlash(TemplatePath.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..776f16e --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateRender.js @@ -0,0 +1,292 @@ +import EleventyBaseError from "./Errors/EleventyBaseError.js"; +import TemplateEngineManager from "./Engines/TemplateEngineManager.js"; + +// import debugUtil from "debug"; +// const debug = debugUtil("Eleventy:TemplateRender"); + +class TemplateRenderUnknownEngineError extends EleventyBaseError {} + +// works with full path names or short engine name +class TemplateRender { + #extensionMap; + #config; + + constructor(tmplPath, config) { + if (!tmplPath) { + throw new Error(`TemplateRender requires a tmplPath argument, instead of ${tmplPath}`); + } + this.#setConfig(config); + + this.engineNameOrPath = tmplPath; + this.parseMarkdownWith = this.config.markdownTemplateEngine; + this.parseHtmlWith = this.config.htmlTemplateEngine; + } + + #setConfig(config) { + if (config?.constructor?.name !== "TemplateConfig") { + throw new Error("TemplateRender must receive a TemplateConfig instance."); + } + + this.eleventyConfig = config; + this.config = config.getConfig(); + } + + 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) { + throw new Error("Internal error: missing `extensionMap` in TemplateRender."); + } + return this.#extensionMap; + } + + async getEngineByName(name) { + // WARNING: eleventyConfig assignment removed here + return this.extensionMap.engineManager.getEngine(name, this.extensionMap); + } + + // Runs once per template + async init(engineNameOrPath) { + let name = engineNameOrPath || this.engineNameOrPath; + this.extensionMap.setTemplateConfig(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?.constructor?.name === "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 + getPreprocessorEngineName() { + if (this.engineName === "md" && this.parseMarkdownWith) { + return this.parseMarkdownWith; + } + if (this.engineName === "html" && this.parseHtmlWith) { + return this.parseHtmlWith; + } + // TODO do we need this? + 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..79b0fee --- /dev/null +++ b/node_modules/@11ty/eleventy/src/TemplateWriter.js @@ -0,0 +1,508 @@ +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 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; + #passthroughManager; + #errorHandler; + #extensionMap; + + constructor( + templateFormats, // TODO remove this, see `get eleventyFiles` first + templateData, + templateConfig, + ) { + if (!templateConfig) { + throw new TemplateWriterMissingConfigArgError("Missing config argument."); + } + this.templateConfig = templateConfig; + this.config = templateConfig.getConfig(); + this.userConfig = templateConfig.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.templateConfig.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) { + throw new Error("Internal error: missing `extensionMap` in TemplateWriter."); + } + return this.#extensionMap; + } + + setPassthroughManager(mgr) { + this.#passthroughManager = mgr; + } + + setEleventyFiles(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.templateConfig); + + 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 + // TODO reset other constructor things here like inputDir/outputDir + tmpl.resetCachedTemplate({ + templateData: this.templateData, + extensionMap: this.extensionMap, + eleventyConfig: this.templateConfig, + }); + } else { + tmpl = new Template(path, this.templateData, this.extensionMap, this.templateConfig); + tmpl.setOutputFormat(to); + tmpl.logger = this.logger; + this._templatePathCache.set(path, tmpl); + } + + tmpl.setTransforms(this.config.transforms); + tmpl.setLinters(this.config.linters); + 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) + // Related: #3870, improved configuration reset + + templates.push(tmpl); + + // This must happen before data is generated for the incremental file only + if (incrementalFileShape === "template" && tmpl.inputPath === this.incrementalFile) { + tmpl.resetCaches(); + } else if ( + // Issue #3824 #3870 + tmpl.isFileRelevantToThisTemplate(this.incrementalFile, { + isFullTemplate: incrementalFileShape === "template", + }) + ) { + 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++; + } + } + } + + async _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; + }); + + if (this.incrementalFile) { + // Top level async to get at the promises returned. + return await this._addToTemplateMapIncrementalBuild(incrementalFileShape, paths, to); + } + + // Full Build + let ret = await this._addToTemplateMapFullBuild(paths, to); + + // write new template relationships to the global dependency graph for next time + this.templateMap.addAllToGlobalDependencyGraph(); + + return ret; + } + + async _createTemplateMap(paths, to) { + this.templateMap = new TemplateMap(this.templateConfig); + + await this._addToTemplateMap(paths, to); + await this.templateMap.cache(); + + // Return is used by tests + 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) { + if (!this.#passthroughManager) { + throw new Error("Internal error: Missing `passthroughManager` instance."); + } + + return this.#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 = []; + // TODO optimize await here + await this._createTemplateMap(paths, to); + 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(); + + // This must happen before writePassthroughCopy + this.templateConfig.userConfig.emit("eleventy#beforerender"); + + let aggregatePassthroughCopyPromise = this.writePassthroughCopy(paths); + + let templatesPromise = Promise.all(await this.generateTemplates(paths)).then((results) => { + this.templateConfig.userConfig.emit("eleventy#render"); + + return results; + }); + + return Promise.all([aggregatePassthroughCopyPromise, templatesPromise]).then( + async ([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 = Boolean(isDryRun); + } + + setRunInitialBuild(runInitialBuild) { + this.isRunInitialBuild = runInitialBuild; + } + setIncrementalBuild(isIncremental) { + this.isIncremental = isIncremental; + } + setIncrementalFile(incrementalFile) { + this.incrementalFile = incrementalFile; + this.#passthroughManager.setIncrementalFile(incrementalFile); + } + resetIncrementalFile() { + this.incrementalFile = null; + this.#passthroughManager.resetIncrementalFile(); + } + + getMetadata() { + return { + // copyCount, copySize + ...(this.#passthroughManager?.getMetadata() || {}), + skipCount: this.skippedCount, + writeCount: this.writeCount, + renderCount: this.renderCount, + }; + } + + 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..215327f --- /dev/null +++ b/node_modules/@11ty/eleventy/src/UserConfig.js @@ -0,0 +1,1339 @@ +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 EventEmitter 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; + /** @type {number} */ + #concurrency = 1; + // Before using os.availableParallelism(); see https://github.com/11ty/eleventy/issues/3596 + + 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 EventEmitter(); + + /** @type {object} */ + this.directories = {}; + /** @type {undefined} */ + this.logger; + /** @type {string} */ + this.dir; + /** @type {string} */ + this.pathPrefix; + /** @type {object} */ + this.errorReporting = {}; + /** @type {object} */ + this.templateHandling = {}; + + 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 {EventEmitter} */ + this.events = new EventEmitter(); + this.events.setMaxListeners(25); // defaults to 10 + + /** @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 = {}; + this.passthroughCopiesHtmlRelative = new Set(); + + /** @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/**"); // TODO `**/.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 = {}; + /** @type {object} */ + this.templateHandling = {}; + + // Before using os.availableParallelism(); see https://github.com/11ty/eleventy/issues/3596 + this.#concurrency = 1; + } + + // 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 (copyOptions.mode) { + if (copyOptions.mode !== "html-relative") { + throw new Error( + "Invalid `mode` option for `addPassthroughCopy`. Received: '" + copyOptions.mode + "'", + ); + } + if (isPlainObject(fileOrDir)) { + throw new Error( + "mode: 'html-relative' does not yet support passthrough copy objects (input -> output mapping). Use a string glob or an Array of string globs.", + ); + } + + this.passthroughCopiesHtmlRelative?.add({ + match: fileOrDir, + ...copyOptions, + }); + } else 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); + } + + configureTemplateHandling(options = {}) { + // writeMode: "sync" // "async" + Object.assign(this.templateHandling, 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); + } + + setConcurrency(number) { + if (typeof number !== "number") { + throw new UserConfigError("Argument passed to `setConcurrency` must be a number."); + } + + this.#concurrency = number; + } + + getConcurrency() { + return this.#concurrency; + } + + 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, + passthroughCopiesHtmlRelative: this.passthroughCopiesHtmlRelative, + 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, + templateHandling: this.templateHandling, + }; + + 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/ArrayUtil.js b/node_modules/@11ty/eleventy/src/Util/ArrayUtil.js new file mode 100644 index 0000000..bcb61de --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/ArrayUtil.js @@ -0,0 +1,24 @@ +export function arrayDelete(arr, match) { + if (!Array.isArray(arr)) { + return []; + } + + if (!match) { + return arr; + } + + // only mutates if found + if (typeof match === "function") { + if (arr.find(match)) { + return arr.filter((entry) => { + return !match(entry); + }); + } + } else if (arr.includes(match)) { + return arr.filter((entry) => { + return entry !== match; + }); + } + + return arr; +} 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..0bc471f --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/AsyncEventEmitter.js @@ -0,0 +1,88 @@ +import { EventEmitter } from "node:events"; + +/** + * This class emits events asynchronously. + * + * Note that Eleventy has two separate event emitter instances it uses: + * 1. a userland one (UserConfig.js) + * 2. a global one for internals (EventBus.js) + */ +class AsyncEventEmitter extends EventEmitter { + #handlerMode = "parallel"; + + // TypeScript slop + constructor(...args) { + super(...args); + } + + reset() { + // `eleventy#` event type listeners are removed at the start of each build (singletons) + for (let type of this.eventNames()) { + if (typeof type === "string" && type.startsWith("eleventy#")) { + this.removeAllListeners(type); + } + } + + } + + /** + * @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..c90a9b3 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/Compatibility.js @@ -0,0 +1,59 @@ +import semver from "semver"; + +import { getEleventyPackageJson, getWorkingProjectPackageJson } from "./ImportJsonSync.js"; + +const pkg = getEleventyPackageJson(); + +// Used in user config versionCheck method. +class Compatibility { + static NORMALIZE_PRERELEASE_REGEX = /-canary\b/g; + + static #projectPackageJson; + + constructor(compatibleRange) { + this.compatibleRange = Compatibility.getCompatibilityValue(compatibleRange); + } + + static get projectPackageJson() { + if (!this.#projectPackageJson) { + this.#projectPackageJson = getWorkingProjectPackageJson(); + } + + return this.#projectPackageJson; + } + + static normalizeIdentifier(identifier) { + return identifier.replace(Compatibility.NORMALIZE_PRERELEASE_REGEX, "-alpha"); + } + + static getCompatibilityValue(compatibleRange) { + if (compatibleRange) { + return compatibleRange; + } + + // fetch from project’s package.json + if (this.projectPackageJson?.["11ty"]?.compatibility) { + return this.projectPackageJson["11ty"].compatibility; + } + } + + 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..ba41196 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/ConsoleLogger.js @@ -0,0 +1,140 @@ +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; + /** @type {Readable|undefined} */ + #outputStream; + + constructor() {} + + isLoggingEnabled() { + if (!this.isVerbose || process.env.DEBUG) { + return true; + } + return this.#logger !== false; + } + + 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"); + } + + get outputStream() { + if (!this.#outputStream) { + this.#outputStream = new Readable({ + read() {}, + }); + } + return this.#outputStream; + } + + /** @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..0cc5959 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/DateGitFirstAdded.js @@ -0,0 +1,23 @@ +import { spawnAsync } from "./SpawnAsync.js"; + +async function getGitFirstAddedTimeStamp(filePath) { + try { + let timestamp = await spawnAsync( + "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], + ); + return parseInt(timestamp, 10) * 1000; + } catch (e) { + // do nothing + } +} + +// return a Date +export default async function (inputPath) { + let timestamp = await 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..1f58c11 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/DateGitLastUpdated.js @@ -0,0 +1,23 @@ +import { spawnAsync } from "./SpawnAsync.js"; + +async function getGitLastUpdatedTimeStamp(filePath) { + try { + let timestamp = await spawnAsync( + "git", + // Formats https://www.git-scm.com/docs/git-log#_pretty_formats + // %at author date, UNIX timestamp + ["log", "-1", "--format=%at", filePath], + ); + return parseInt(timestamp, 10) * 1000; + } catch (e) { + // do nothing + } +} + +// return a Date +export default async function (inputPath) { + let timestamp = await 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..c19990c --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/DirContains.js @@ -0,0 +1,10 @@ +import path from "node:path"; + +// Returns true if subfolder is in parent (accepts absolute or relative paths for both) +export default function (parentFolder, subFolder) { + // path.resolve returns an absolute path + if (path.resolve(subFolder).startsWith(path.resolve(parentFolder))) { + 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..c098ed8 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/EsmResolver.js @@ -0,0 +1,53 @@ +import debugUtil from "debug"; +import { fileURLToPath } from "node:url"; +import PathNormalizer from "./PathNormalizer.js"; + +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 = PathNormalizer.normalizeSeperator(fileURLToPath(fileUrl)); + // 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..c749fe9 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/EventBusUtil.js @@ -0,0 +1,14 @@ +import eventBus from "../EventBus.js"; +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:EventBus"); + +class EventBusUtil { + static debugCurrentListenerCounts() { + 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..433d743 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/ExistsCache.js @@ -0,0 +1,62 @@ +import fs from "node:fs"; +import { TemplatePath } from "@11ty/eleventy-utils"; + +// Checks both files and directories +class ExistsCache { + #exists = new Map(); + #dirs = new Map(); + + constructor() { + this.lookupCount = 0; + } + + get size() { + return this.#exists.size; + } + + has(path) { + return this.#exists.has(path); + } + + set(path, isExist) { + this.#exists.set(TemplatePath.addLeadingDotSlash(path), Boolean(isExist)); + } + + // Not yet needed + // setDirectory(path, isExist) {} + + // Relative paths (to root directory) expected (but not enforced due to perf costs) + exists(path) { + if (!this.#exists.has(path)) { + let exists = fs.existsSync(path); + this.lookupCount++; + + // mark for next time + this.#exists.set(path, Boolean(exists)); + + return exists; + } + + return this.#exists.get(path); + } + + isDirectory(path) { + if (!this.exists(path)) { + return false; + } + + if (!this.#dirs.has(path)) { + let isDir = fs.statSync(path).isDirectory(); + this.lookupCount++; + + // mark for next time + this.#dirs.set(path, isDir); + + return isDir; + } + + return this.#dirs.get(path); + } +} + +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/FileSystemManager.js b/node_modules/@11ty/eleventy/src/Util/FileSystemManager.js new file mode 100644 index 0000000..12881d7 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/FileSystemManager.js @@ -0,0 +1,48 @@ +import path from "node:path"; +import fs from "node:fs"; +import { mkdir, writeFile } from "node:fs/promises"; + +class FileSystemManager { + constructor(templateConfig) { + if (!templateConfig || templateConfig.constructor.name !== "TemplateConfig") { + throw new Error( + "Internal error: Missing `templateConfig` or was not an instance of `TemplateConfig`.", + ); + } + this.templateConfig = templateConfig; + } + + exists(pathname) { + return this.templateConfig.existsCache.exists(pathname); + } + + async createDirectoryForFile(filePath) { + let dir = path.parse(filePath).dir; + if (!dir || this.exists(dir)) { + return; + } + + return mkdir(dir, { recursive: true }); + } + + createDirectoryForFileSync(filePath) { + let dir = path.parse(filePath).dir; + if (!dir || this.exists(dir)) { + return; + } + + fs.mkdirSync(dir, { recursive: true }); + } + + async writeFile(filePath, content) { + return writeFile(filePath, content); + } + + writeFileSync(filePath, content) { + // Note: This deliberately uses the synchronous version to avoid + // unbounded concurrency: https://github.com/11ty/eleventy/issues/3271 + fs.writeFileSync(filePath, content); + } +} + +export { FileSystemManager }; 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..a4a6c55 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/GlobMatcher.js @@ -0,0 +1,22 @@ +import picomatch from "picomatch"; +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, + ); + + // globs: string or array of strings + return picomatch.isMatch(inputPath, globs, opts); +} + +export { isGlobMatch }; diff --git a/node_modules/@11ty/eleventy/src/Util/GlobRemap.js b/node_modules/@11ty/eleventy/src/Util/GlobRemap.js new file mode 100644 index 0000000..5e2bea3 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/GlobRemap.js @@ -0,0 +1,85 @@ +import path from "node:path"; +import ProjectDirectories from "./ProjectDirectories.js"; +import PathNormalizer from "./PathNormalizer.js"; + +// even on Windows (in cmd.exe) these paths are normalized to forward slashes +// tinyglobby expects forward slashes on Windows +const SEP = "/"; + +class GlobRemap { + constructor(paths = []) { + this.paths = paths; + this.cwd = GlobRemap.getCwd(paths); + } + + getCwd() { + return this.cwd; + } + + getRemapped(paths) { + return paths.map((entry) => GlobRemap.remapInput(entry, this.cwd)); + } + + getInput() { + return this.getRemapped(this.paths); + } + + getOutput(paths = []) { + return paths.map((entry) => GlobRemap.remapOutput(entry, this.cwd)); + } + + static getParentDirPrefix(filePath = "") { + let count = []; + for (let p of filePath.split(SEP)) { + if (p === "..") { + count.push(".."); + } else { + break; + } + } + + if (count.length > 0) { + // trailing slash + return count.join(SEP) + SEP; + } + return ""; + } + + static getLongestParentDirPrefix(filePaths) { + let longest = ""; + filePaths + .map((entry) => { + return this.getParentDirPrefix(entry); + }) + .filter((entry) => Boolean(entry)) + .forEach((prefix) => { + if (!longest || prefix.length > longest.length) { + longest = prefix; + } + }); + return longest; + } + + // alias + static getCwd(filePaths) { + return this.getLongestParentDirPrefix(filePaths); + } + + static remapInput(entry, cwd) { + if (cwd) { + if (!entry.startsWith("**" + SEP) && !entry.startsWith(`.git${SEP}**`)) { + return PathNormalizer.normalizeSeperator(ProjectDirectories.getRelativeTo(entry, cwd)); + } + } + return entry; + } + + static remapOutput(entry, cwd) { + if (cwd) { + return PathNormalizer.normalizeSeperator(path.join(cwd, entry)); + } + return entry; + } +} + +export default GlobRemap; diff --git a/node_modules/@11ty/eleventy/src/Util/HtmlRelativeCopy.js b/node_modules/@11ty/eleventy/src/Util/HtmlRelativeCopy.js new file mode 100644 index 0000000..3059014 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/HtmlRelativeCopy.js @@ -0,0 +1,149 @@ +import path from "node:path"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import isValidUrl from "./ValidUrl.js"; +import { isGlobMatch } from "./GlobMatcher.js"; + +class HtmlRelativeCopy { + #userConfig; + #matchingGlobs = new Set(); + #matchingGlobsArray; + #dirty = false; + #paths = new Set(); + #failOnError = true; + #copyOptions = { + dot: false, // differs from standard passthrough copy + }; + + isEnabled() { + return this.#matchingGlobs.size > 0; + } + + setFailOnError(failOnError) { + this.#failOnError = Boolean(failOnError); + } + + setCopyOptions(opts) { + if (opts) { + Object.assign(this.#copyOptions, opts); + } + } + + setUserConfig(userConfig) { + if (!userConfig || userConfig.constructor.name !== "UserConfig") { + throw new Error( + "Internal error: Missing `userConfig` or was not an instance of `UserConfig`.", + ); + } + this.#userConfig = userConfig; + } + + addPaths(paths = []) { + for (let path of paths) { + this.#paths.add(TemplatePath.getDir(path)); + } + } + + get matchingGlobs() { + if (this.#dirty || !this.#matchingGlobsArray) { + this.#matchingGlobsArray = Array.from(this.#matchingGlobs); + this.#dirty = false; + } + + return this.#matchingGlobsArray; + } + + addMatchingGlob(glob) { + if (glob) { + if (Array.isArray(glob)) { + for (let g of glob) { + this.#matchingGlobs.add(g); + } + } else { + this.#matchingGlobs.add(glob); + } + this.#dirty = true; + } + } + + isSkippableHref(rawRef) { + if ( + this.#matchingGlobs.size === 0 || + !rawRef || + path.isAbsolute(rawRef) || + isValidUrl(rawRef) + ) { + return true; + } + return false; + } + + isCopyableTarget(target) { + if (!isGlobMatch(target, this.matchingGlobs)) { + return false; + } + + return true; + } + + exists(filePath) { + return this.#userConfig.exists(filePath); + } + + getAliasedPath(ref) { + for (let dir of this.#paths) { + let found = TemplatePath.join(dir, ref); + if (this.isCopyableTarget(found) && this.exists(found)) { + return found; + } + } + } + + getFilePathRelativeToProjectRoot(ref, contextFilePath) { + let dir = TemplatePath.getDirFromFilePath(contextFilePath); + return TemplatePath.join(dir, ref); + } + + copy(fileRef, tmplInputPath, tmplOutputPath) { + // original ref is a full URL or no globs exist + if (this.isSkippableHref(fileRef)) { + return; + } + + // Relative to source file’s input path + let source = this.getFilePathRelativeToProjectRoot(fileRef, tmplInputPath); + if (!this.isCopyableTarget(source)) { + return; + } + + if (!this.exists(source)) { + // Try to alias using `options.paths` + let alias = this.getAliasedPath(fileRef); + if (!alias) { + if (this.#failOnError) { + throw new Error( + "Missing input file for `html-relative` Passthrough Copy file: " + + TemplatePath.absolutePath(source), + ); + } + + // don’t fail on error + return; + } + + source = alias; + } + + let target = this.getFilePathRelativeToProjectRoot(fileRef, tmplOutputPath); + + // We use a Set here to allow passthrough copy manager to properly error on conflicts upstream + // Only errors when different inputs write to the same output + // Also errors if attempts to write outside the output folder. + this.#userConfig.emit("eleventy#copy", { + source, + target, + options: this.#copyOptions, + }); + } +} + +export { HtmlRelativeCopy }; 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..f28910f --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/HtmlTransformer.js @@ -0,0 +1,172 @@ +import posthtml from "posthtml"; +import urls from "@11ty/posthtml-urls"; +import { FilePathUtil } from "./FilePathUtil.js"; + +import { arrayDelete } from "./ArrayUtil.js"; + +class HtmlTransformer { + // feature test for Eleventy Bundle Plugin + static SUPPORTS_PLUGINS_ENABLED_CALLBACK = true; + + static TYPES = ["callbacks", "plugins"]; + + 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, attrName, tagName) => { + for (let { fn: callback } of callbacks) { + // already sorted by priority when added + url = callback.call(context, url, { attribute: attrName, tag: tagName }); + } + + 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({ + // *could* fallback to function name, `value.name` + name: options.name, // for `remove` and debugging + fn: value, // callback or plugin + priority: options.priority, // sorted in descending order + enabled: options.enabled || (() => true), + options: options.pluginOptions, + }); + + target[ext].sort(HtmlTransformer.prioritySort); + } + } + + addPosthtmlPlugin(extensions, plugin, options = {}) { + this._add(extensions, "plugins", plugin, options); + } + + // match can be a plugin function or a filter callback(plugin => true); + remove(extensions, match) { + for (let removeType of HtmlTransformer.TYPES) { + for (let ext of (extensions || "").split(",")) { + this[removeType][ext] = arrayDelete(this[removeType][ext], match); + } + } + } + + 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..fa59365 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/ImportJsonSync.js @@ -0,0 +1,77 @@ +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(); + // TODO use DirContains + 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 || !filePath.endsWith(".json")) { + throw new Error(`importJsonSync expects a .json file extension (received: ${filePath})`); + } + + return require(filePath); +} + +function getEleventyPackageJson() { + let filePath = normalizeFilePathInEleventyPackage("package.json"); + return importJsonSync(filePath); +} + +function getModulePackageJson(dir) { + let filePath = findFilePathInParentDirs(TemplatePath.absolutePath(dir), "package.json"); + + // optional! + if (!filePath) { + return {}; + } + + return importJsonSync(filePath); +} + +// This will *not* find a package.json in a parent directory above root +function getWorkingProjectPackageJsonPath() { + let dir = TemplatePath.absolutePath(TemplatePath.getWorkingDir()); + return findFilePathInParentDirs(dir, "package.json"); +} + +function getWorkingProjectPackageJson() { + let filePath = getWorkingProjectPackageJsonPath(); + + // optional! + if (!filePath) { + return {}; + } + + return importJsonSync(filePath); +} + +export { + importJsonSync, + findFilePathInParentDirs, + getEleventyPackageJson, + getModulePackageJson, + getWorkingProjectPackageJson, + getWorkingProjectPackageJsonPath, +}; 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..38730fd --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/Objects/ProxyWrap.js @@ -0,0 +1,118 @@ +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(); + // The fallback keys need to come first to preserve proper key order + // https://github.com/11ty/eleventy/issues/3849 + if (isPlainObject(fallback)) { + for (let k of Reflect.ownKeys(fallback)) { + s.add(k); + } + } + for (let k of Reflect.ownKeys(target)) { + if (!s.has(k)) { + 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 ( + (typeof fallback === "object" || typeof fallback === "function") && + 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..cdc3253 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/PathNormalizer.js @@ -0,0 +1,58 @@ +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { TemplatePath } from "@11ty/eleventy-utils"; + +export default 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)), + ); + } +} 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..e15e985 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/ProjectDirectories.js @@ -0,0 +1,369 @@ +import fs from "node:fs"; +import path from "node:path"; +import { TemplatePath } from "@11ty/eleventy-utils"; +import { isDynamicPattern } from "tinyglobby"; + +import DirContains from "./DirContains.js"; + +/* 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; + } + + // Normalize absolute paths to relative, #3805 + // if(path.isAbsolute(dirOrFile)) { + // dirOrFile = path.relative(".", dirOrFile); + // } + + // 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 (!isDynamicPattern(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 \`tinyglobby\` 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); + // TODO use DirContains + if (this.layouts && inputPath.startsWith(this.layouts)) { + return false; + } + + // if this.includes is "" (and thus is the same directory as this.input) + // we don’t actually know if this is a template file, so defer + if (this.includes && this.includes !== this.input) { + if (inputPath.startsWith(this.includes)) { + return false; + } + } + + // TODO use DirContains + 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)), + ); + } + + isFileInProjectFolder(filePath) { + return DirContains(TemplatePath.getWorkingDir(), filePath); + } + + isFileInOutputFolder(filePath) { + return DirContains(this.output, filePath); + } + + static getRelativeTo(targetPath, cwd) { + return path.relative(cwd, path.join(path.resolve("."), targetPath)); + } + + // 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/PromiseUtil.js b/node_modules/@11ty/eleventy/src/Util/PromiseUtil.js new file mode 100644 index 0000000..fa88da0 --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/PromiseUtil.js @@ -0,0 +1,15 @@ +function withResolvers() { + if ("withResolvers" in Promise) { + return Promise.withResolvers(); + } + + let resolve; + let reject; + let promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +export { withResolvers }; 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..5f6412d --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/Require.js @@ -0,0 +1,258 @@ +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 EleventyBaseError from "../Errors/EleventyBaseError.js"; +import eventBus from "../EventBus.js"; + +class EleventyImportError extends EleventyBaseError {} + +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(); + +function getImportErrorMessage(filePath, type) { + return `There was a problem importing '${path.relative(".", filePath)}' via ${type}`; +} + +// 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 (error) { + // @ts-expect-error Temporary + if (error?.code === "ENOENT") { + // if file does not exist, return nothing + return; + } + + throw error; + } + + // 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]; + } + } +}); + +// raw means we don’t normalize away the `default` export +async function dynamicImportAbsolutePath(absolutePath, options = {}) { + let { type, returnRaw, cacheBust } = Object.assign( + { + type: undefined, + returnRaw: false, + cacheBust: false, // force cache bust + }, + options, + ); + + // Short circuit for JSON files (that are optional and can be empty) + if (absolutePath.endsWith(".json") || type === "json") { + try { + // https://v8.dev/features/import-assertions#dynamic-import() is still experimental in Node 20 + let rawInput = loadContents(absolutePath); + if (!rawInput) { + // should not error when file exists but is _empty_ + return; + } + return JSON.parse(rawInput); + } catch (e) { + return Promise.reject( + new EleventyImportError(getImportErrorMessage(absolutePath, "fs.readFile(json)"), e), + ); + } + } + + // Removed a `require` short circuit from this piece originally added + // in https://github.com/11ty/eleventy/pull/3493 Was a bit faster but + // error messaging was worse for require(esm) + + let urlPath; + try { + let u = new URL(`file:${absolutePath}`); + + // Bust the import cache if this is the last modified file (or cache busting is forced) + if (cacheBust) { + lastModifiedPaths.set(absolutePath, Date.now()); + } + + if (cacheBust || 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); + } + + return promise.then( + (target) => { + if (returnRaw) { + return 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 (key === "module.exports") { + 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); + }, + (error) => { + return Promise.reject( + new EleventyImportError(getImportErrorMessage(absolutePath, `import(${type})`), error), + ); + }, + ); +} + +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, { type: "esm" }); +} + +async function dynamicImport(localPath, type, options = {}) { + let absolutePath = TemplatePath.absolutePath(localPath); + options.type = type; + + // Returns promise + return dynamicImportAbsolutePath(absolutePath, options); +} + +/* 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, { type: "esm", returnRaw: true }); +} + +/* Used to import app 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, returnRaw: true }); +} + +export { + loadContents as EleventyLoadContent, + dynamicImport as EleventyImport, + dynamicImportRaw as EleventyImportRaw, + normalizeFilePathInEleventyPackage, + + // no longer used in core + dynamicImportFromEleventyPackage as EleventyImportFromEleventy, + dynamicImportRawFromEleventyPackage as EleventyImportRawFromEleventy, +}; 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/SpawnAsync.js b/node_modules/@11ty/eleventy/src/Util/SpawnAsync.js new file mode 100644 index 0000000..5e6a20f --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/SpawnAsync.js @@ -0,0 +1,29 @@ +import { spawn } from "node:child_process"; +import { withResolvers } from "./PromiseUtil.js"; + +export function spawnAsync(command, args, options) { + let { promise, resolve, reject } = withResolvers(); + + const cmd = spawn(command, args, options); + let res = []; + cmd.stdout.on("data", (data) => { + res.push(data.toString("utf8")); + }); + + let err = []; + cmd.stderr.on("data", (data) => { + err.push(data.toString("utf8")); + }); + + cmd.on("close", (code) => { + if (err.length > 0) { + reject(err.join("\n")); + } else if (code === 1) { + reject("Internal error: process closed with error exit code."); + } else { + resolve(res.join("\n")); + } + }); + + return promise; +} diff --git a/node_modules/@11ty/eleventy/src/Util/TemplateDepGraph.js b/node_modules/@11ty/eleventy/src/Util/TemplateDepGraph.js new file mode 100644 index 0000000..795453d --- /dev/null +++ b/node_modules/@11ty/eleventy/src/Util/TemplateDepGraph.js @@ -0,0 +1,160 @@ +import { DepGraph as DependencyGraph } from "dependency-graph"; +import debugUtil from "debug"; + +const debug = debugUtil("Eleventy:TemplateDepGraph"); + +const COLLECTION_PREFIX = "__collection:"; + +export class TemplateDepGraph extends DependencyGraph { + static STAGES = ["[basic]", "[userconfig]", "[keys]", "all"]; + + #configCollectionNames = new Set(); + + constructor() { + // BREAKING TODO move this back to non-circular with errors + super({ circular: true }); + + let previous; + // establish stage relationships, all uses keys, keys uses userconfig, userconfig uses tags + for (let stageName of TemplateDepGraph.STAGES.filter(Boolean).reverse()) { + let stageKey = `${COLLECTION_PREFIX}${stageName}`; + if (previous) { + this.uses(previous, stageKey); + } + previous = stageKey; + } + } + + uses(from, to) { + this.addDependency(from, to); + } + + addTag(tagName, type) { + if ( + tagName === "all" || + (tagName.startsWith("[") && tagName.endsWith("]")) || + this.#configCollectionNames.has(tagName) + ) { + return; + } + if (!type) { + throw new Error( + `Missing tag type for addTag. Expecting one of ${TemplateDepGraph.STAGES.map((entry) => entry.slice(1, -1)).join(" or ")}. Received: ${type}`, + ); + } + + debug("collection type %o uses tag %o", tagName, type); + + this.uses(`${COLLECTION_PREFIX}[${type}]`, `${COLLECTION_PREFIX}${tagName}`); + } + + addConfigCollectionName(collectionName) { + if (collectionName === "all") { + return; + } + + this.#configCollectionNames.add(collectionName); + // Collection relationships to `[userconfig]` are added last, in unfilteredOrder() + } + + cleanupCollectionNames(collectionNames = []) { + let s = new Set(collectionNames); + if (s.has("[userconfig]")) { + return collectionNames; + } + + let hasAnyConfigCollections = collectionNames.find((name) => { + if (this.#configCollectionNames.has(name)) { + return true; + } + return false; + }); + + if (hasAnyConfigCollections) { + s.add("[userconfig]"); + } + + return Array.from(s); + } + + addTemplate(filePath, consumes = [], publishesTo = []) { + // Move to the beginning if it doesn’t consume anything + if (consumes.length === 0) { + this.uses(`${COLLECTION_PREFIX}[basic]`, filePath); + } + + consumes = this.cleanupCollectionNames(consumes); + publishesTo = this.cleanupCollectionNames(publishesTo); + // Can’t consume AND publish to `all` simultaneously + let consumesAll = consumes.includes("all"); + if (consumesAll) { + publishesTo = publishesTo.filter((entry) => entry !== "all"); + } + + debug("%o consumes %o and publishes to %o", filePath, consumes, publishesTo); + + for (let collectionName of publishesTo) { + if (!consumesAll) { + let tagType = "basic"; + + let consumesUserConfigCollection = consumes.includes("[userconfig]"); + if (consumesUserConfigCollection) { + // must finish before [keys] + tagType = "keys"; + } + + this.addTag(collectionName, tagType); + } + + this.uses(`${COLLECTION_PREFIX}${collectionName}`, filePath); + } + + for (let collectionName of consumes) { + this.uses(filePath, `${COLLECTION_PREFIX}${collectionName}`); + + let stageIndex = TemplateDepGraph.STAGES.indexOf(collectionName); + let nextStage = stageIndex > 0 ? TemplateDepGraph.STAGES[stageIndex + 1] : undefined; + if (nextStage) { + this.uses(`${COLLECTION_PREFIX}${nextStage}`, filePath); + } + } + } + + addDependency(from, to) { + if (!this.hasNode(from)) { + this.addNode(from); + } + if (!this.hasNode(to)) { + this.addNode(to); + } + super.addDependency(from, to); + } + + unfilteredOrder() { + // these need to be added last, after the template map has been added (see addConfigCollectionName) + for (let collectionName of this.#configCollectionNames) { + this.uses(`${COLLECTION_PREFIX}[keys]`, `${COLLECTION_PREFIX}${collectionName}`); + } + + return super.overallOrder(); + } + + overallOrder() { + let unfiltered = this.unfilteredOrder(); + + let filtered = unfiltered.filter((entry) => { + if (entry === `${COLLECTION_PREFIX}[keys]`) { + return true; + } + return !entry.startsWith(`${COLLECTION_PREFIX}[`) && !entry.endsWith("]"); + }); + + let allKey = `${COLLECTION_PREFIX}all`; + // Add another collections.all entry to the end (if not already the last one) + if (filtered[filtered.length - 1] !== allKey) { + filtered.push(allKey); + } + + return filtered; + } +} 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..fb1ab5d --- /dev/null +++ b/node_modules/@11ty/eleventy/src/defaultConfig.js @@ -0,0 +1,178 @@ +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"; +import { HtmlRelativeCopyPlugin } from "./Plugins/HtmlRelativeCopyPlugin.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.exists = (filePath) => { + return this.existsCache.exists(filePath); + }; + + // Remember: the transform added here runs before the `htmlTransformer` transform + 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) { + // Runs **AFTER** the bundle plugin transform (except: delayed bundles) + return ut.transformContent(this.outputPath, content, this); + }); + + // Requires user configuration, so must run as second-stage + config.addPlugin(HtmlRelativeCopyPlugin); + + 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..3b915fb --- /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('@11ty/posthtml-urls'); + +const options = { + eachURL: (url, attr, tagName, rawNode) => `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`. The `rawNode` argument was added in `v1.0.3`. + +### `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 `