This commit is contained in:
2026-04-29 08:30:52 -07:00
commit b053d27321
1660 changed files with 329972 additions and 0 deletions

12
.editorconfig Normal file
View File

@ -0,0 +1,12 @@
root = true
[*]
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
charset = utf-8
indent_style = tab
indent_size = 2
[*.{yaml,yml,md,njk}]
indent_style = space

661
COPYING Normal file
View File

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

15
LICENSE Normal file
View File

@ -0,0 +1,15 @@
Fediverse Classifieds
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 <https://www.gnu.org/licenses/>.

48
_config/filters.js Normal file
View File

@ -0,0 +1,48 @@
export default function(eleventyConfig) {
// Return the keys used in an object
eleventyConfig.addFilter("getKeys", target => {
return Object.keys(target);
});
/* */
eleventyConfig.addFilter("getTagline", tag => {
let tagline;
switch (tag) {
case "animals and the outdoors":
tagline = "grass touchin'";
break;
case "art and crafts":
/* tagline = */
break;
case "food and drink":
tagline = "good eatin'";
break;
case "history and science":
/* tagline = */
break;
case "home improvement and diy":
tagline = "fixin' stuff";
break;
case "interpersonal and life":
/* tagline = */
break;
case "technology":
tagline = "computer touchin'";
break;
case "writing, editing, and literature":
/* tagline = */
break;
};
return tagline;
});
/* Filter out structural tags */
eleventyConfig.addFilter("removeCoreTags", (tags) => {
return tags.filter(tag => ["all"].indexOf(tag) === -1);
});
/* What it says on the tin */
eleventyConfig.addFilter("sortAlphabetically", strings =>
(strings || []).sort((b, a) => b.localeCompare(a))
);
};

6
_data/metadata.js Normal file
View File

@ -0,0 +1,6 @@
export default {
title: "Fedi Classifieds",
description: "Skillshares and more",
url: "",
author: "Lee Cattarin"
}

2
_includes/footer.njk Normal file
View File

@ -0,0 +1,2 @@
<footer>
</footer>

4
_includes/header.njk Normal file
View File

@ -0,0 +1,4 @@
<header>
<nav>
</nav>
</header>

View File

@ -0,0 +1,47 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{% if title %}
{% set pageTitle %}{{ title }} | {{ metadata.title }}{% endset %}
{% else %}
{% set pageTitle = metadata.title %}
{% endif %}
<title>{{ pageTitle }}</title>
<meta name="description" content="{{ description or metadata.description }}">
<link rel="alternate" href="/feed.xml" type="application/atom+xml" title="{{ metadata.title }}">
<meta property="og:title" content="{{ pageTitle }}" />
<meta property="og:type" content="website" />
<meta property="og:description" content="{{ description or metadata.description }}" />
<meta property="og:site_name" content="{{ metadata.title }}" />
<meta name="generator" content="{{ eleventy.generator }}">
{# Styles #}
<style>{% include "css/main.css" %}</style>
<style>{% getBundle "css" %}</style>
{# JS #}
<script type="module">{% getBundle "js" %}</script>
{# Fonts #}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Fraunces:opsz,wght@9..144,100..900&display=swap" rel="stylesheet">
</head>
<body>
{% include "header.njk" %}
<main id="main">
{{ content | safe }}
</main>
{% include "footer.njk" %}
<!-- This page `{{ page.url }}` was built on {% currentBuildDate %} -->
</body>
</html>

153
_live/index.html Normal file
View File

@ -0,0 +1,153 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fedi Classifieds</title>
<meta name="description" content="Skillshares and more">
<link rel="alternate" href="/feed.xml" type="application/atom+xml" title="Fedi Classifieds">
<meta property="og:title" content="Fedi Classifieds">
<meta property="og:type" content="website">
<meta property="og:description" content="Skillshares and more">
<meta property="og:site_name" content="Fedi Classifieds">
<meta name="generator" content="Eleventy v3.1.5">
<style>* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
width: 65%;
margin: 0 auto;
}
#ads {
columns: 3;
}
h1 {
font-family: "Fraunces";
font-weight: 400;
text-align: center;
font-size: 4rem;
margin: 3rem auto 1rem;
}
h2 {
font-family: "Bebas Neue";
background-color: lightgray;
}
h3 {
font-family: "Fraunces";
font-weight: 400;
text-transform: capitalize;
}</style>
<script type="module"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="">
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Fraunces:opsz,wght@9..144,100..900&display=swap" rel="stylesheet">
</head>
<body>
<header>
<nav>
</nav>
</header>
<main id="main">
<h1>Fediverse Classifieds</h1>
<div id="ads">
<h2 class="category">animals and the outdoors</h2>
<p class="tagline">grass touchin&#39;</p>
<h3>bug identification for beginners</h3>
<a href="https://test.test/@5" target="_blank">@5@test.test</a>
<p>Duis interdum purus non iaculis convallis. Nunc mi lorem, consequat sed luctus vitae, lobortis in arcu.</p>
<h2 class="category">art and crafts</h2>
<p class="tagline"></p>
<h3>film photography</h3>
<a href="https://test.test/@0" target="_blank">@0@test.test</a>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<h2 class="category">food and drink</h2>
<p class="tagline">good eatin&#39;</p>
<h3>sourdough starting!</h3>
<a href="https://test.test/@4" target="_blank">@4@test.test</a>
<p>Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Vivamus vitae augue ac neque congue pellentesque vitae a enim. Donec euismod dolor sit amet dui dapibus posuere. Donec eget blandit ligula, ac tempor nunc.</p>
<h2 class="category">history and science</h2>
<p class="tagline"></p>
<h3>let&#39;s talk about the roman empire</h3>
<a href="https://test.test/@1" target="_blank">@1@test.test</a>
<p>Quisque mauris erat, tempor non egestas sollicitudin, feugiat id risus. Duis eget ornare nunc. Cras sodales, eros quis finibus luctus, enim sem dictum ante, sed sodales ipsum ante a metus.</p>
<h2 class="category">home improvement and diy</h2>
<p class="tagline">fixin&#39; stuff</p>
<h3>fix your sink or toilet</h3>
<a href="https://test.test/@6" target="_blank">@6@test.test</a>
<p>Aliquam justo justo, scelerisque a ligula sed, elementum pharetra quam. Ut augue nibh, finibus vel dui nec, sagittis bibendum leo. Quisque libero diam, maximus in dui ac, sollicitudin congue enim.</p>
<h2 class="category">interpersonal and life</h2>
<p class="tagline"></p>
<h3>neurodivergent coping strats</h3>
<a href="https://test.test/@2" target="_blank">@2@test.test</a>
<p>Fusce faucibus mauris ut metus molestie viverra. In varius erat in lectus scelerisque, vitae ornare sapien euismod. Pellentesque ornare aliquam erat, pellentesque eleifend tellus consequat ut. Donec mollis, lacus vitae bibendum hendrerit, nisi metus dignissim lacus, nec tincidunt nisl ligula vel metus.</p>
<h2 class="category">technology</h2>
<p class="tagline">computer touchin&#39;</p>
<h3>intro web development and terminal basics</h3>
<a href="https://flipping.rocks/@inherentlee" target="_blank">@inherentlee@flipping.rocks</a>
<p>I&#39;m happy to help you set up a personal or hobby site with HTML, CSS, and JS basics, or maybe a static site generator! Alternately, I&#39;ll talk about git and the terminal.</p>
<h2 class="category">writing editing and literature</h2>
<p class="tagline"></p>
<h3>editing 102</h3>
<a href="https://test.test/@3" target="_blank">@3@test.test</a>
<p>Sed a commodo lectus. Curabitur tincidunt, eros vel mollis dapibus, mauris dui pharetra mauris, et dapibus leo nisi vitae eros.</p>
</div>
</main>
<footer>
</footer>
<!-- This page `/` was built on 2026-04-29T15:29:16.700Z -->
</body>
</html>

151
_live/robots.txt Normal file
View File

@ -0,0 +1,151 @@
# Sourced from https://codeberg.org/superseriousbusiness/gotosocial/
# AI scrapers and the like.
# https://github.com/ai-robots-txt/ai.robots.txt/
User-agent: AddSearchBot
User-agent: AI2Bot
User-agent: AI2Bot-DeepResearchEval
User-agent: Ai2Bot-Dolma
User-agent: aiHitBot
User-agent: amazon-kendra
User-agent: Amazonbot
User-agent: AmazonBuyForMe
User-agent: Andibot
User-agent: Anomura
User-agent: anthropic-ai
User-agent: Applebot
User-agent: Applebot-Extended
User-agent: atlassian-bot
User-agent: Awario
User-agent: bedrockbot
User-agent: bigsur.ai
User-agent: Bravebot
User-agent: Brightbot 1.0
User-agent: BuddyBot
User-agent: Bytespider
User-agent: CCBot
User-agent: Channel3Bot
User-agent: ChatGLM-Spider
User-agent: ChatGPT Agent
User-agent: ChatGPT-User
User-agent: Claude-SearchBot
User-agent: Claude-User
User-agent: Claude-Web
User-agent: ClaudeBot
User-agent: Cloudflare-AutoRAG
User-agent: CloudVertexBot
User-agent: cohere-ai
User-agent: cohere-training-data-crawler
User-agent: Cotoyogi
User-agent: Crawl4AI
User-agent: Crawlspace
User-agent: Datenbank Crawler
User-agent: DeepSeekBot
User-agent: Devin
User-agent: Diffbot
User-agent: DuckAssistBot
User-agent: Echobot Bot
User-agent: EchoboxBot
User-agent: FacebookBot
User-agent: facebookexternalhit
User-agent: Factset_spyderbot
User-agent: FirecrawlAgent
User-agent: FriendlyCrawler
User-agent: Gemini-Deep-Research
User-agent: Google-CloudVertexBot
User-agent: Google-Extended
User-agent: Google-Firebase
User-agent: Google-NotebookLM
User-agent: GoogleAgent-Mariner
User-agent: GoogleOther
User-agent: GoogleOther-Image
User-agent: GoogleOther-Video
User-agent: GPTBot
User-agent: iAskBot
User-agent: iaskspider
User-agent: iaskspider/2.0
User-agent: IbouBot
User-agent: ICC-Crawler
User-agent: ImagesiftBot
User-agent: imageSpider
User-agent: img2dataset
User-agent: ISSCyberRiskCrawler
User-agent: Kangaroo Bot
User-agent: KlaviyoAIBot
User-agent: KunatoCrawler
User-agent: laion-huggingface-processor
User-agent: LAIONDownloader
User-agent: LCC
User-agent: LinerBot
User-agent: Linguee Bot
User-agent: LinkupBot
User-agent: Manus-User
User-agent: meta-externalagent
User-agent: Meta-ExternalAgent
User-agent: meta-externalfetcher
User-agent: Meta-ExternalFetcher
User-agent: meta-webindexer
User-agent: MistralAI-User
User-agent: MistralAI-User/1.0
User-agent: MyCentralAIScraperBot
User-agent: netEstate Imprint Crawler
User-agent: NotebookLM
User-agent: NovaAct
User-agent: OAI-SearchBot
User-agent: omgili
User-agent: omgilibot
User-agent: OpenAI
User-agent: Operator
User-agent: PanguBot
User-agent: Panscient
User-agent: panscient.com
User-agent: Perplexity-User
User-agent: PerplexityBot
User-agent: PetalBot
User-agent: PhindBot
User-agent: Poggio-Citations
User-agent: Poseidon Research Crawler
User-agent: QualifiedBot
User-agent: QuillBot
User-agent: quillbot.com
User-agent: SBIntuitionsBot
User-agent: Scrapy
User-agent: SemrushBot-OCOB
User-agent: SemrushBot-SWA
User-agent: ShapBot
User-agent: Sidetrade indexer bot
User-agent: Spider
User-agent: TerraCotta
User-agent: Thinkbot
User-agent: TikTokSpider
User-agent: Timpibot
User-agent: TwinAgent
User-agent: VelenPublicWebCrawler
User-agent: WARDBot
User-agent: Webzio-Extended
User-agent: webzio-extended
User-agent: wpbot
User-agent: WRTNBot
User-agent: YaK
User-agent: YandexAdditional
User-agent: YandexAdditionalBot
User-agent: YouBot
User-agent: ZanistaBot
Disallow: /
# Marketing/SEO "intelligence" data scrapers
User-agent: AwarioRssBot
User-agent: AwarioSmartBot
User-agent: DataForSeoBot
User-agent: magpie-crawler
User-agent: Meltwater
User-agent: peer39_crawler
User-agent: peer39_crawler/1.0
User-agent: PiplBot
User-agent: scoop.it
User-agent: Seekr
Disallow: /
# Rules for everything else
User-agent: *
Crawl-delay: 500

33
css/main.css Normal file
View File

@ -0,0 +1,33 @@
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
width: 65%;
margin: 0 auto;
}
#ads {
columns: 3;
}
h1 {
font-family: "Fraunces";
font-weight: 400;
text-align: center;
font-size: 4rem;
margin: 3rem auto 1rem;
}
h2 {
font-family: "Bebas Neue";
background-color: lightgray;
}
h3 {
font-family: "Fraunces";
font-weight: 400;
text-transform: capitalize;
}

47
eleventy.config.js Normal file
View File

@ -0,0 +1,47 @@
import pluginFilters from "./_config/filters.js";
export default async function(eleventyConfig) {
/* Bundles */
/* CSS */
eleventyConfig.addBundle("css", {
toFileDirectory: "dist",
bundleHtmlContentFromSelector: "style",
});
/* Javascript */
eleventyConfig.addBundle("js", {
toFileDirectory: "dist",
bundleHtmlContentFromSelector: "script",
});
/* Passthrough */
eleventyConfig
.addPassthroughCopy("favicon.ico")
.addPassthroughCopy("robots.txt");
/* Plugins */
/* 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"],
};

1
node_modules/.bin/acorn generated vendored Symbolic link
View File

@ -0,0 +1 @@
../acorn/bin/acorn

1
node_modules/.bin/eleventy generated vendored Symbolic link
View File

@ -0,0 +1 @@
../@11ty/eleventy/cmd.cjs

1
node_modules/.bin/eleventy-dev-server generated vendored Symbolic link
View File

@ -0,0 +1 @@
../@11ty/eleventy-dev-server/cmd.js

1
node_modules/.bin/errno generated vendored Symbolic link
View File

@ -0,0 +1 @@
../errno/cli.js

1
node_modules/.bin/esparse generated vendored Symbolic link
View File

@ -0,0 +1 @@
../esprima/bin/esparse.js

1
node_modules/.bin/esvalidate generated vendored Symbolic link
View File

@ -0,0 +1 @@
../esprima/bin/esvalidate.js

1
node_modules/.bin/js-yaml generated vendored Symbolic link
View File

@ -0,0 +1 @@
../js-yaml/bin/js-yaml.js

1
node_modules/.bin/liquid generated vendored Symbolic link
View File

@ -0,0 +1 @@
../liquidjs/bin/liquid.js

1
node_modules/.bin/liquidjs generated vendored Symbolic link
View File

@ -0,0 +1 @@
../liquidjs/bin/liquid.js

1
node_modules/.bin/markdown-it generated vendored Symbolic link
View File

@ -0,0 +1 @@
../markdown-it/bin/markdown-it.mjs

1
node_modules/.bin/mime generated vendored Symbolic link
View File

@ -0,0 +1 @@
../mime/cli.js

1
node_modules/.bin/nunjucks-precompile generated vendored Symbolic link
View File

@ -0,0 +1 @@
../nunjucks/bin/precompile

1
node_modules/.bin/semver generated vendored Symbolic link
View File

@ -0,0 +1 @@
../semver/bin/semver.js

1630
node_modules/.package-lock.json generated vendored Normal file

File diff suppressed because it is too large Load Diff

21
node_modules/@11ty/dependency-tree-esm/LICENSE generated vendored Normal file
View File

@ -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.

53
node_modules/@11ty/dependency-tree-esm/README.md generated vendored Normal file
View File

@ -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 Eleventys build.
## Installation
```
npm install --save-dev @11ty/dependency-tree-esm
```
## Features
* Ignores bare specifiers (e.g. `import "my-package"`)
* Ignores Nodes 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"]
```

173
node_modules/@11ty/dependency-tree-esm/main.js generated vendored Normal file
View File

@ -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,
};

26
node_modules/@11ty/dependency-tree-esm/package.json generated vendored Normal file
View File

@ -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"
}
}

21
node_modules/@11ty/dependency-tree/LICENSE generated vendored Normal file
View File

@ -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.

109
node_modules/@11ty/dependency-tree/README.md generated vendored Normal file
View File

@ -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 Eleventys 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 dont 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 Nodes 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: [] }
```

157
node_modules/@11ty/dependency-tree/main.js generated vendored Normal file
View File

@ -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;

42
node_modules/@11ty/dependency-tree/package.json generated vendored Normal file
View File

@ -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"
}
}

60
node_modules/@11ty/eleventy-dev-server/README.md generated vendored Normal file
View File

@ -0,0 +1,60 @@
<p align="center"><img src="https://www.11ty.dev/img/logo-github.svg" width="200" height="200" alt="11ty Logo"></p>
# 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 youre 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.

89
node_modules/@11ty/eleventy-dev-server/cli.js generated vendored Normal file
View File

@ -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
}

View File

@ -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 <html> 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
// Dont update a <link> if the _11ty searchParam is the only thing thats 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 wont 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();

77
node_modules/@11ty/eleventy-dev-server/cmd.js generated vendored Executable file
View File

@ -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 dont 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)
}

57
node_modules/@11ty/eleventy-dev-server/package.json generated vendored Normal file
View File

@ -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"
}
}

1024
node_modules/@11ty/eleventy-dev-server/server.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
const os = require("node:os");
const INTERFACE_FAMILIES = ["IPv4"];
module.exports = function() {
return Object.values(os.networkInterfaces()).flat().filter(interface => {
return interface.internal === false && INTERFACE_FAMILIES.includes(interface.family);
}).map(interface => interface.address);
};

View File

@ -0,0 +1,130 @@
function getContentType(headers) {
if(!headers) {
return;
}
for(let key in headers) {
if(key.toLowerCase() === "content-type") {
return headers[key];
}
}
}
// Inspired by `resp-modifier` https://github.com/shakyShane/resp-modifier/blob/4a000203c9db630bcfc3b6bb8ea2abc090ae0139/index.js
function wrapResponse(resp, transformHtml) {
resp._wrappedOriginalWrite = resp.write;
resp._wrappedOriginalWriteHead = resp.writeHead;
resp._wrappedOriginalEnd = resp.end;
resp._wrappedHeaders = [];
resp._wrappedTransformHtml = transformHtml;
resp._hasEnded = false;
resp._shouldForceEnd = false;
// Compatibility with web standards Response()
Object.defineProperty(resp, "body", {
// Returns write cache
get: function() {
if(typeof this._writeCache === "string") {
return this._writeCache;
}
},
// Usage:
// res.body = ""; // overwrite existing content
// res.body += ""; // append to existing content, can also res.write("") to append
set: function(data) {
if(typeof data === "string") {
this._writeCache = data;
}
}
});
// Compatibility with web standards Response()
Object.defineProperty(resp, "bodyUsed", {
get: function() {
return this._hasEnded;
}
})
// Original signature writeHead(statusCode[, statusMessage][, headers])
resp.writeHead = function(statusCode, ...args) {
let headers = args[args.length - 1];
// statusMessage is a string
if(typeof headers !== "string") {
this._contentType = getContentType(headers);
}
if((this._contentType || "").startsWith("text/html")) {
this._wrappedHeaders.push([statusCode, ...args]);
} else {
return this._wrappedOriginalWriteHead(statusCode, ...args);
}
return this;
}
// data can be a String or Buffer
resp.write = function(data, ...args) {
if(typeof data === "string") {
if(!this._writeCache) {
this._writeCache = "";
}
// TODO encoding and callback args
this._writeCache += data;
} else {
// Buffers
return this._wrappedOriginalWrite(data, ...args);
}
return this;
}
// data can be a String or Buffer
resp.end = function(data, encoding, callback) {
resp._hasEnded = true;
if(typeof this._writeCache === "string" || typeof data === "string") {
// Strings
if(!this._writeCache) {
this._writeCache = "";
}
if(typeof data === "string") {
this._writeCache += data;
}
let result = this._writeCache;
// Only transform HTML
// Note the “setHeader versus writeHead” note on https://nodejs.org/api/http.html#responsewriteheadstatuscode-statusmessage-headers
let contentType = this._contentType || getContentType(this.getHeaders());
if(contentType?.startsWith("text/html")) {
if(this._wrappedTransformHtml && typeof this._wrappedTransformHtml === "function") {
result = this._wrappedTransformHtml(result);
// uncompressed size: https://github.com/w3c/ServiceWorker/issues/339
this.setHeader("Content-Length", Buffer.byteLength(result));
}
}
for(let headers of this._wrappedHeaders) {
this._wrappedOriginalWriteHead(...headers);
}
this._writeCache = [];
this._wrappedOriginalWrite(result, encoding)
return this._wrappedOriginalEnd(callback);
} else {
// Buffer or Uint8Array
for(let headers of this._wrappedHeaders) {
this._wrappedOriginalWriteHead(...headers);
}
if(data) {
this._wrappedOriginalWrite(data, encoding);
}
return this._wrappedOriginalEnd(callback);
}
}
return resp;
}
module.exports = wrapResponse;

337
node_modules/@11ty/eleventy-plugin-bundle/README.md generated vendored Normal file
View File

@ -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 youd 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, theyll 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.
Heres 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
<h1>My Blog Post</h1>
<p>This is some content, I am writing markup.</p>
<h2>More Markdown</h2>
```
Note that the bundled code is excluded!
_There are a few [more examples below](#examples)!_
### Render bundle code
```html
<!-- Use this *anywhere*: a layout file, content template, etc -->
<style>{% getBundle "css" %}</style>
<!--
You can add more code to the bundle after calling
getBundle and it will be included.
-->
{% 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
<link rel="stylesheet" href="{% getBundleFileUrl "css" %}">
```
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
<!-- This goes into a `defer` bucket (the bucket can be any string value) -->
{% css "defer" %}em { font-style: italic; }{% endcss %}
```
```html
<!-- Pass the arbitrary `defer` bucket name as an additional argument -->
<style>{% getBundle "css", "defer" %}</style>
<link rel="stylesheet" href="{% getBundleFileUrl 'css', 'defer' %}">
```
A `default` bucket is implied:
```html
<!-- These two statements are the same -->
{% css %}em { font-style: italic; }{% endcss %}
{% css "default" %}em { font-style: italic; }{% endcss %}
<!-- These two are the same too -->
<style>{% getBundle "css" %}</style>
<style>{% getBundle "css", "default" %}</style>
```
### 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
<!-- … -->
<head>
<!-- Inlined critical styles -->
<style>{% getBundle "css" %}</style>
<!-- Deferred non-critical styles -->
<link rel="stylesheet" href="{% getBundleFileUrl 'css', 'defer' %}" media="print" onload="this.media='all'">
<noscript>
<link rel="stylesheet" href="{% getBundleFileUrl 'css', 'defer' %}">
</noscript>
</head>
<body>
<!-- This goes into a `default` bucket -->
{% css %}/* Inline in the head, great with @font-face! */{% endcss %}
<!-- This goes into a `defer` bucket (the bucket can be any string value) -->
{% css "defer" %}/* Load me later */{% endcss %}
</body>
<!-- … -->
```
**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 width="0" height="0" aria-hidden="true" style="position: absolute;">
<defs>{% getBundle "svg" %}</defs>
</svg>
<!-- And anywhere on your page you can add icons to the set -->
{% svg %}
<g id="icon-close"><path d="…" /></g>
{% endsvg %}
And now you can use `icon-close` in as many SVG instances as youd like (without repeating the heftier SVG content).
<svg><use xlink:href="#icon-close"></use></svg>
<svg><use xlink:href="#icon-close"></use></svg>
<svg><use xlink:href="#icon-close"></use></svg>
<svg><use xlink:href="#icon-close"></use></svg>
```
#### React Helmet-style `<head>` additions
```js
// .eleventy.js
export default function(eleventyConfig) {
eleventyConfig.addBundle("html");
};
```
This might exist in an Eleventy layout file:
```html
<head>
{% getBundle "html", "head" %}
</head>
```
And then in your content you might want to page-specific `preconnect`:
```html
{% html "head" %}
<link href="https://v1.opengraph.11ty.dev" rel="preconnect" crossorigin>
{% endhtml %}
```
#### Bundle Sass with the Render Plugin
You can render template syntax inside of the `{% css %}` shortcode too, if youd 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 `<style>` element in a WebC page or component:
```html
<style>/* This is bundled. */</style>
<style webc:keep>/* Do not bundle me—leave as is */</style>
```
To add JS to a page bundle in WebC, you would use a `<script>` element in a WebC page or component:
```html
<script>/* This is bundled. */</script>
<script webc:keep>/* Do not bundle me—leave as is */</script>
```
* Existing calls via WebC helpers `getCss` or `getJs` (e.g. `<style @raw="getCss(page.url)">`) have been wired up to `getBundle` (for `"css"` and `"js"` respectively) automatically.
* For consistency, you may prefer using the bundle plugin method names everywhere: `<style @raw="getBundle('css')">` and `<script @raw="getBundle('js')">` both work fine.
* Outside of WebC, the Universal Filters `webcGetCss` and `webcGetJs` were removed in Eleventy `v3.0.0-alpha.10` in favor of the `getBundle` Universal Shortcode (`{% getBundle "css" %}` and `{% getBundle "js" %}` respectively).
#### Modify the bundle output
You can wire up your own async-friendly callbacks to transform the bundle output too. Heres a quick example of [`postcss` integration](https://github.com/postcss/postcss#js-api).
```js
const postcss = require("postcss");
const postcssNested = require("postcss-nested");
export default function(eleventyConfig) {
eleventyConfig.addBundle("css", {
transforms: [
async function(content) {
// this.type returns the bundle name.
// Same as Eleventy transforms, this.page is available here.
let result = await postcss([postcssNested]).process(content, { from: this.page.inputPath, to: null });
return result.css;
}
]
});
};
```
## Advanced
### Limitations
Bundles do not support nesting or recursion (yet?). If this will be useful to you, please file an issue!
<!--
Version Two:
* Think about Eleventy transform order, scenarios where this transform needs to run first.
* JavaScript API independent of eleventy
* Clean up the _site/bundle folder on exit?
* Example ideas:
* App bundle and page bundle
* can we make this work for syntax highlighting? or just defer to WebC for this?
{% css %}
<style>
em { font-style: italic; }
</style>
{% 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)
-->

View File

@ -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 cant be unique (dont 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 };

62
node_modules/@11ty/eleventy-plugin-bundle/package.json generated vendored Normal file
View File

@ -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"
}
}

View File

@ -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 };

View File

@ -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 doesnt 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 };

View File

@ -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 };

View File

@ -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 };

View File

@ -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) { // dont add if a file doesnt 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;

View File

@ -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;
}
// <link rel="stylesheet" href="">
if(node.tag === "link") {
if(node.attrs?.rel === "stylesheet" && (node.attrs?.href || "").trim().length === 0) {
return false;
}
} else {
let content = getTextNodeContent(node);
if(!content) {
// <script></script> or <script src=""></script>
if(node.tag === "script" && (node.attrs?.src || "").trim().length === 0) {
return false;
}
// <style></style>
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;

View File

@ -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;
});
});
};

21
node_modules/@11ty/eleventy-utils/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 20222024 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.

27
node_modules/@11ty/eleventy-utils/README.md generated vendored Normal file
View File

@ -0,0 +1,27 @@
<p align="center"><img src="https://www.11ty.dev/img/logo-github.png" alt="eleventy Logo"></p>
# 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))

20
node_modules/@11ty/eleventy-utils/index.js generated vendored Normal file
View File

@ -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,
};

42
node_modules/@11ty/eleventy-utils/package.json generated vendored Normal file
View File

@ -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/"
}

10
node_modules/@11ty/eleventy-utils/src/Buffer.js generated vendored Normal file
View File

@ -0,0 +1,10 @@
function isBuffer(inst) {
if(typeof Buffer !== "undefined") {
return Buffer.isBuffer(inst);
}
return inst instanceof Uint8Array;
}
module.exports = {
isBuffer
}

27
node_modules/@11ty/eleventy-utils/src/CreateHash.js generated vendored Normal file
View File

@ -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,
};

41
node_modules/@11ty/eleventy-utils/src/DateCompare.js generated vendored Normal file
View File

@ -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;

158
node_modules/@11ty/eleventy-utils/src/HashTypes.js generated vendored Normal file
View File

@ -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 Stackblitzs 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 }

24
node_modules/@11ty/eleventy-utils/src/IsPlainObject.js generated vendored Normal file
View File

@ -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;
};

84
node_modules/@11ty/eleventy-utils/src/Merge.js generated vendored Normal file
View File

@ -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;

373
node_modules/@11ty/eleventy-utils/src/TemplatePath.js generated vendored Normal file
View File

@ -0,0 +1,373 @@
const path = require("path");
const fs = require("fs");
function TemplatePath() {}
/**
* @returns {String} the absolute path to Eleventys 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 paths 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;

13
node_modules/@11ty/eleventy-utils/src/Url.js generated vendored Normal file
View File

@ -0,0 +1,13 @@
function base64UrlSafe(hashString = "") {
return hashString.replace(/[=\+\/]/g, function(match) {
if(match === "=") {
return "";
}
if(match === "+") {
return "-";
}
return "_";
});
}
module.exports = { base64UrlSafe };

113
node_modules/@11ty/eleventy-utils/src/lib-sha256.js generated vendored Normal file
View File

@ -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<data.length; i++) {
buf[bp++] = data[i];
if (bp === 64) process();
}
tsz += data.length;
},
digest = () => {
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();
}

48
node_modules/@11ty/eleventy/CODE_OF_CONDUCT.md generated vendored Normal file
View File

@ -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/

21
node_modules/@11ty/eleventy/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 20172024 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.

47
node_modules/@11ty/eleventy/README.md generated vendored Normal file
View File

@ -0,0 +1,47 @@
<p align="center"><img src="https://www.11ty.dev/img/logo-github.svg" width="200" height="200" alt="eleventy Logo"></p>
# 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/).

9
node_modules/@11ty/eleventy/SECURITY.md generated vendored Normal file
View File

@ -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`.

155
node_modules/@11ty/eleventy/cmd.cjs generated vendored Executable file
View File

@ -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 dont 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();

166
node_modules/@11ty/eleventy/package.json generated vendored Normal file
View File

@ -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 <zachleatherman@gmail.com> (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"
}
}
}

55
node_modules/@11ty/eleventy/src/Benchmark/Benchmark.js generated vendored Normal file
View File

@ -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;

View File

@ -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();
// // dont 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;

View File

@ -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 dont 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;

122
node_modules/@11ty/eleventy/src/Data/ComputedData.js generated vendored Normal file
View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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 doesnt work
* in some template languages that visit all available data even if
* it isnt 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 wont 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
// cant use proxies here as some template languages trigger proxy for all
// keys in data
for (let key of this.computedKeys) {
// TODO dont 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 shouldnt 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;

710
node_modules/@11ty/eleventy/src/Data/TemplateData.js generated vendored Normal file
View File

@ -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 doesnt 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 shouldnt 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, lets 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 required 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` isnt 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;

View File

@ -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;

1565
node_modules/@11ty/eleventy/src/Eleventy.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

43
node_modules/@11ty/eleventy/src/EleventyCommonJs.cjs generated vendored Normal file
View File

@ -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;

284
node_modules/@11ty/eleventy/src/EleventyExtensionMap.js generated vendored Normal file
View File

@ -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;

521
node_modules/@11ty/eleventy/src/EleventyFiles.js generated vendored Normal file
View File

@ -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 dont 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 isnt 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 thats 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 isnt 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;

321
node_modules/@11ty/eleventy/src/EleventyServe.js generated vendored Normal file
View File

@ -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("Its 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. Were 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 Eleventys `setServerOptions` method requires a `ready` function on the Dev Server instance. If youre 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 dont 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, were restarting the server");
await this.restart();
} else {
await this.server.reload(reloadEvent);
}
}
}
export default EleventyServe;

131
node_modules/@11ty/eleventy/src/EleventyWatch.js generated vendored Executable file
View File

@ -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 dont 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;

164
node_modules/@11ty/eleventy/src/EleventyWatchTargets.js generated vendored Normal file
View File

@ -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 targets 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;

339
node_modules/@11ty/eleventy/src/Engines/Custom.js generated vendored Normal file
View File

@ -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;
}
}

View File

@ -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 its handled in Eleventy upstream.
return vm.getGlobalContext(data, {
reuseGlobal: true,
dynamicImport: true,
// addRequire: true,
});
}

33
node_modules/@11ty/eleventy/src/Engines/Html.js generated vendored Normal file
View File

@ -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;
};
}
}

240
node_modules/@11ty/eleventy/src/Engines/JavaScript.js generated vendored Normal file
View File

@ -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;
}
}

331
node_modules/@11ty/eleventy/src/Engines/Liquid.js generated vendored Normal file
View File

@ -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 *dont* 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;
}
// Dont 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);
};
}
}

100
node_modules/@11ty/eleventy/src/Engines/Markdown.js generated vendored Normal file
View File

@ -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);
};
}
}
}
}

482
node_modules/@11ty/eleventy/src/Engines/Nunjucks.js generated vendored Executable file
View File

@ -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 weve moved to use Nunjucks internal cache instead of Eleventys
// 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());
}
// Dont 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;
};
}
}

View File

@ -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 isnt 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 itd 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);
}
}

View File

@ -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 theyre 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;

View File

@ -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 };

View File

@ -0,0 +1,9 @@
import EleventyBaseError from "./EleventyBaseError.js";
class DuplicatePermalinkOutputError extends EleventyBaseError {
get removeDuplicateErrorStringFromOutput() {
return true;
}
}
export default DuplicatePermalinkOutputError;

View File

@ -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;

View File

@ -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) {
// Dont 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 };

Some files were not shown because too many files have changed in this diff Show More