Release Font Tools v0.1.0
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
node_modules/
|
||||
dist/
|
||||
release/*.zip
|
||||
release/*.zip.sha256
|
||||
coverage/
|
||||
playwright-report/
|
||||
test-results/
|
||||
*.tsbuildinfo
|
||||
.DS_Store
|
||||
@@ -0,0 +1 @@
|
||||
@add-ideas:registry=https://git.add-ideas.de/api/packages/lotobo/npm/
|
||||
@@ -0,0 +1,9 @@
|
||||
# Changelog
|
||||
|
||||
## 0.1.0 - 2026-09-01
|
||||
|
||||
- Add bounded TTF/OTF/WOFF inspection in an isolated worker.
|
||||
- Add metadata, table, coverage, variable-axis and embedding-rights reports.
|
||||
- Add sandboxed arbitrary-text/fallback previews and inert CSS generation.
|
||||
- Add restriction-aware static outline subsetting with an explicit loss report.
|
||||
- Add Toolbox shell integration, offline PWA and reproducible release tooling.
|
||||
@@ -0,0 +1,5 @@
|
||||
# Contributing
|
||||
|
||||
Use Node.js 22 and `npm ci`. Keep all parsing bounded and local, add regression
|
||||
coverage for malformed fonts, and run `npm run check` plus `npm run test:browser`
|
||||
before proposing a change. Contributions are licensed GPL-3.0-or-later.
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 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 General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<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 General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,4 @@
|
||||
# Runtime licenses
|
||||
|
||||
Generated package-license metadata is included in production builds and release
|
||||
archives as `npm-runtime-licenses.txt`.
|
||||
@@ -0,0 +1,19 @@
|
||||
# Font Tools
|
||||
|
||||
Font Tools is a GPL-3.0-or-later, local-first browser workbench for inspecting
|
||||
TTF, OTF and WOFF fonts. It inventories SFNT tables, names, metrics, Unicode
|
||||
coverage, variable axes and OS/2 embedding restrictions; previews arbitrary
|
||||
text against local fallbacks; generates inert CSS; and can rebuild a deliberately
|
||||
simple static outline subset when the machine-readable restrictions permit it.
|
||||
|
||||
Files never leave the browser. Parsing and subsetting run in a disposable worker
|
||||
with an 8-second operation limit. Preview rendering is contained in a scriptless
|
||||
sandboxed frame. WOFF2 is detected but not parsed in v0.1.0.
|
||||
|
||||
Limits: 16 MiB input, 64 MiB declared expanded SFNT size, 128 tables, 65,535
|
||||
glyphs, 250,000 Unicode mappings, 20,000 preview characters and 1,024 subset
|
||||
glyphs. Suspicious WOFF ratios and invalid table bounds are rejected before the
|
||||
font library sees the data.
|
||||
|
||||
Run `npm ci`, then `npm run check`, `npm run test:browser`, and
|
||||
`npm run package:release -- --force`. Copyright © 2026 Albrecht Degering.
|
||||
@@ -0,0 +1,6 @@
|
||||
# Security
|
||||
|
||||
Do not send font files to third parties when reporting issues. Describe the
|
||||
failure and provide a minimal redistributable sample if possible. Report
|
||||
sensitive findings privately to the repository owner. Font parsing must remain
|
||||
worker-isolated, bounded and free of network resolution.
|
||||
@@ -0,0 +1,9 @@
|
||||
# Source identity
|
||||
|
||||
- Repository: https://git.add-ideas.de/lotobo/font-tools
|
||||
- Application ID: `de.add-ideas.font-tools`
|
||||
- Version: `0.1.0`
|
||||
- License: `GPL-3.0-or-later`
|
||||
|
||||
The release ZIP is deterministically assembled from the production build and
|
||||
the source/licensing documentation recorded in this repository.
|
||||
@@ -0,0 +1,5 @@
|
||||
# Third-party notices
|
||||
|
||||
Font Tools uses React, the add·ideas Toolbox packages, and opentype.js. The
|
||||
generated runtime-license inventory in `LICENSES/npm-runtime-licenses.txt`
|
||||
records package versions and license metadata. No third-party font is bundled.
|
||||
@@ -0,0 +1,6 @@
|
||||
# Accessibility
|
||||
|
||||
The workbench is keyboard operable, preserves visible focus, labels every input,
|
||||
announces load/subset results, exposes coverage as text and tables, and provides
|
||||
system-font comparison samples. Colour never carries the only indication of a
|
||||
missing glyph or blocked operation.
|
||||
@@ -0,0 +1,12 @@
|
||||
# Architecture
|
||||
|
||||
`core/sfnt.ts` validates SFNT/WOFF headers and table boundaries before parsing.
|
||||
`font.worker.ts` owns the opentype.js instance and the source bytes; the UI only
|
||||
receives bounded serializable inspection records. Each load gets a new worker,
|
||||
and an unresponsive operation is terminated after eight seconds. Subsetting is
|
||||
a separate worker command that rebuilds a static outline font from requested
|
||||
Unicode glyphs only after OS/2 restrictions are checked.
|
||||
|
||||
React keeps the last successful inspection after errors. Font rendering occurs
|
||||
in a scriptless sandboxed iframe. Relative assets and a same-origin service
|
||||
worker support nested offline deployment.
|
||||
@@ -0,0 +1,11 @@
|
||||
# Privacy and security
|
||||
|
||||
Font bytes, preview text and generated output stay in memory. There is no
|
||||
telemetry, URL import, remote font lookup or automatic upload. Explicit local
|
||||
downloads are the only output. Parsing uses strict size/table/expansion/glyph
|
||||
caps, a disposable worker and a deadline. User metadata is rendered as text;
|
||||
preview HTML is escaped and confined to a scriptless sandbox.
|
||||
|
||||
The OS/2 `fsType` field is technical metadata, not legal advice. Font Tools
|
||||
blocks subsetting when it declares restricted embedding, no-subsetting or
|
||||
bitmap-only embedding, but users must still comply with the actual licence.
|
||||
@@ -0,0 +1,37 @@
|
||||
import js from "@eslint/js";
|
||||
import globals from "globals";
|
||||
import reactHooks from "eslint-plugin-react-hooks";
|
||||
import reactRefresh from "eslint-plugin-react-refresh";
|
||||
import tseslint from "typescript-eslint";
|
||||
|
||||
export default tseslint.config(
|
||||
{
|
||||
ignores: [
|
||||
"dist",
|
||||
"release",
|
||||
"coverage",
|
||||
"test-results",
|
||||
"playwright-report",
|
||||
],
|
||||
},
|
||||
{
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||
files: ["**/*.{ts,tsx}"],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2023,
|
||||
globals: { ...globals.browser, ...globals.worker },
|
||||
},
|
||||
plugins: { "react-hooks": reactHooks, "react-refresh": reactRefresh },
|
||||
rules: {
|
||||
...reactHooks.configs.recommended.rules,
|
||||
"react-refresh/only-export-components": [
|
||||
"warn",
|
||||
{ allowConstantExport: true },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ["scripts/**/*.mjs", "playwright.config.ts"],
|
||||
languageOptions: { globals: globals.node },
|
||||
},
|
||||
);
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#352742" />
|
||||
<meta
|
||||
name="description"
|
||||
content="Inspect, compare, preview, and safely subset local fonts."
|
||||
/>
|
||||
<link rel="icon" href="./favicon.svg" type="image/svg+xml" />
|
||||
<link rel="manifest" href="./manifest.webmanifest" />
|
||||
<title>Font Tools</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+3997
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,73 @@
|
||||
{
|
||||
"name": "font-tools",
|
||||
"version": "0.1.0",
|
||||
"description": "Inspect, compare, preview, and safely subset local fonts.",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"author": "Albrecht Degering",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://git.add-ideas.de/lotobo/font-tools.git"
|
||||
},
|
||||
"homepage": "https://git.add-ideas.de/lotobo/font-tools",
|
||||
"bugs": {
|
||||
"url": "https://git.add-ideas.de/lotobo/font-tools/issues"
|
||||
},
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"scripts": {
|
||||
"predev": "npm run manifest:generate",
|
||||
"dev": "vite",
|
||||
"prebuild": "npm run release:prepare && npm run manifest:generate",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc -b --pretty false",
|
||||
"lint": "eslint . --max-warnings=0",
|
||||
"format": "prettier --write .",
|
||||
"format:check": "prettier --check .",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:browser": "playwright test",
|
||||
"manifest:generate": "node scripts/generate-toolbox-manifest.mjs",
|
||||
"manifest:check": "node scripts/generate-toolbox-manifest.mjs --check",
|
||||
"release:prepare": "node scripts/prepare-release-files.mjs",
|
||||
"toolbox:check": "toolbox-check dist",
|
||||
"package:release": "node scripts/package-release.mjs",
|
||||
"check": "npm run manifest:check && npm run typecheck && npm run lint && npm run format:check && npm run test && npm run build && npm run toolbox:check",
|
||||
"release:artifact": "npm run check && npm run test:browser && npm run package:release -- --force"
|
||||
},
|
||||
"dependencies": {
|
||||
"@add-ideas/toolbox-contract": "0.2.3",
|
||||
"@add-ideas/toolbox-helpers": "0.1.0",
|
||||
"@add-ideas/toolbox-shell-react": "0.2.3",
|
||||
"opentype.js": "2.0.0",
|
||||
"react": "19.2.8",
|
||||
"react-dom": "19.2.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@add-ideas/toolbox-testkit": "0.2.3",
|
||||
"@eslint/js": "10.0.1",
|
||||
"@playwright/test": "1.62.1",
|
||||
"@testing-library/jest-dom": "6.9.1",
|
||||
"@testing-library/react": "16.3.2",
|
||||
"@testing-library/user-event": "14.6.1",
|
||||
"@types/node": "25.9.5",
|
||||
"@types/opentype.js": "1.3.10",
|
||||
"@types/react": "19.2.17",
|
||||
"@types/react-dom": "19.2.5",
|
||||
"@vitejs/plugin-react": "6.0.3",
|
||||
"eslint": "10.7.0",
|
||||
"eslint-plugin-react-hooks": "7.1.1",
|
||||
"eslint-plugin-react-refresh": "0.5.2",
|
||||
"globals": "17.7.0",
|
||||
"jsdom": "29.1.1",
|
||||
"prettier": "3.9.5",
|
||||
"typescript": "6.0.3",
|
||||
"typescript-eslint": "8.64.0",
|
||||
"vite": "8.2.2",
|
||||
"vitest": "4.1.11"
|
||||
},
|
||||
"packageManager": "npm@11.17.0"
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { defineConfig, devices } from "@playwright/test";
|
||||
|
||||
export default defineConfig({
|
||||
testDir: "./tests/browser",
|
||||
workers: 1,
|
||||
timeout: 120_000,
|
||||
expect: { timeout: 12_000 },
|
||||
use: {
|
||||
baseURL: "http://127.0.0.1:4202",
|
||||
trace: "retain-on-failure",
|
||||
},
|
||||
webServer: {
|
||||
command: "npm run build && node scripts/serve-test.mjs",
|
||||
url: "http://127.0.0.1:4202/font/",
|
||||
reuseExistingServer: !process.env.CI,
|
||||
timeout: 180_000,
|
||||
},
|
||||
projects: [
|
||||
{ name: "chromium", use: { ...devices["Desktop Chrome"] } },
|
||||
{ name: "firefox", use: { ...devices["Desktop Firefox"] } },
|
||||
],
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
# Changelog
|
||||
|
||||
## 0.1.0 - 2026-09-01
|
||||
|
||||
- Add bounded TTF/OTF/WOFF inspection in an isolated worker.
|
||||
- Add metadata, table, coverage, variable-axis and embedding-rights reports.
|
||||
- Add sandboxed arbitrary-text/fallback previews and inert CSS generation.
|
||||
- Add restriction-aware static outline subsetting with an explicit loss report.
|
||||
- Add Toolbox shell integration, offline PWA and reproducible release tooling.
|
||||
@@ -0,0 +1,5 @@
|
||||
# Contributing
|
||||
|
||||
Use Node.js 22 and `npm ci`. Keep all parsing bounded and local, add regression
|
||||
coverage for malformed fonts, and run `npm run check` plus `npm run test:browser`
|
||||
before proposing a change. Contributions are licensed GPL-3.0-or-later.
|
||||
+674
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 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 General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<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 General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,4 @@
|
||||
# Runtime licenses
|
||||
|
||||
Generated package-license metadata is included in production builds and release
|
||||
archives as `npm-runtime-licenses.txt`.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,19 @@
|
||||
# Font Tools
|
||||
|
||||
Font Tools is a GPL-3.0-or-later, local-first browser workbench for inspecting
|
||||
TTF, OTF and WOFF fonts. It inventories SFNT tables, names, metrics, Unicode
|
||||
coverage, variable axes and OS/2 embedding restrictions; previews arbitrary
|
||||
text against local fallbacks; generates inert CSS; and can rebuild a deliberately
|
||||
simple static outline subset when the machine-readable restrictions permit it.
|
||||
|
||||
Files never leave the browser. Parsing and subsetting run in a disposable worker
|
||||
with an 8-second operation limit. Preview rendering is contained in a scriptless
|
||||
sandboxed frame. WOFF2 is detected but not parsed in v0.1.0.
|
||||
|
||||
Limits: 16 MiB input, 64 MiB declared expanded SFNT size, 128 tables, 65,535
|
||||
glyphs, 250,000 Unicode mappings, 20,000 preview characters and 1,024 subset
|
||||
glyphs. Suspicious WOFF ratios and invalid table bounds are rejected before the
|
||||
font library sees the data.
|
||||
|
||||
Run `npm ci`, then `npm run check`, `npm run test:browser`, and
|
||||
`npm run package:release -- --force`. Copyright © 2026 Albrecht Degering.
|
||||
@@ -0,0 +1,6 @@
|
||||
# Security
|
||||
|
||||
Do not send font files to third parties when reporting issues. Describe the
|
||||
failure and provide a minimal redistributable sample if possible. Report
|
||||
sensitive findings privately to the repository owner. Font parsing must remain
|
||||
worker-isolated, bounded and free of network resolution.
|
||||
@@ -0,0 +1,9 @@
|
||||
# Source identity
|
||||
|
||||
- Repository: https://git.add-ideas.de/lotobo/font-tools
|
||||
- Application ID: `de.add-ideas.font-tools`
|
||||
- Version: `0.1.0`
|
||||
- License: `GPL-3.0-or-later`
|
||||
|
||||
The release ZIP is deterministically assembled from the production build and
|
||||
the source/licensing documentation recorded in this repository.
|
||||
@@ -0,0 +1,5 @@
|
||||
# Third-party notices
|
||||
|
||||
Font Tools uses React, the add·ideas Toolbox packages, and opentype.js. The
|
||||
generated runtime-license inventory in `LICENSES/npm-runtime-licenses.txt`
|
||||
records package versions and license metadata. No third-party font is bundled.
|
||||
@@ -0,0 +1,6 @@
|
||||
# Accessibility
|
||||
|
||||
The workbench is keyboard operable, preserves visible focus, labels every input,
|
||||
announces load/subset results, exposes coverage as text and tables, and provides
|
||||
system-font comparison samples. Colour never carries the only indication of a
|
||||
missing glyph or blocked operation.
|
||||
@@ -0,0 +1,12 @@
|
||||
# Architecture
|
||||
|
||||
`core/sfnt.ts` validates SFNT/WOFF headers and table boundaries before parsing.
|
||||
`font.worker.ts` owns the opentype.js instance and the source bytes; the UI only
|
||||
receives bounded serializable inspection records. Each load gets a new worker,
|
||||
and an unresponsive operation is terminated after eight seconds. Subsetting is
|
||||
a separate worker command that rebuilds a static outline font from requested
|
||||
Unicode glyphs only after OS/2 restrictions are checked.
|
||||
|
||||
React keeps the last successful inspection after errors. Font rendering occurs
|
||||
in a scriptless sandboxed iframe. Relative assets and a same-origin service
|
||||
worker support nested offline deployment.
|
||||
@@ -0,0 +1,11 @@
|
||||
# Privacy and security
|
||||
|
||||
Font bytes, preview text and generated output stay in memory. There is no
|
||||
telemetry, URL import, remote font lookup or automatic upload. Explicit local
|
||||
downloads are the only output. Parsing uses strict size/table/expansion/glyph
|
||||
caps, a disposable worker and a deadline. User metadata is rendered as text;
|
||||
preview HTML is escaped and confined to a scriptless sandbox.
|
||||
|
||||
The OS/2 `fsType` field is technical metadata, not legal advice. Font Tools
|
||||
blocks subsetting when it declares restricted embedding, no-subsetting or
|
||||
bitmap-only embedding, but users must still comply with the actual licence.
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#352742"/><path d="M14 50h10l3-10h14l3 10h10L39 12H29L14 50Zm16-19 4-12 4 12h-8Z" fill="#f5d0fe"/><path d="M10 55h44" stroke="#fff" stroke-width="3" stroke-linecap="round"/></svg>
|
||||
|
After Width: | Height: | Size: 283 B |
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "Font Tools",
|
||||
"short_name": "Fonts",
|
||||
"description": "Inspect and prepare fonts locally.",
|
||||
"start_url": "./",
|
||||
"scope": "./",
|
||||
"display": "standalone",
|
||||
"background_color": "#352742",
|
||||
"theme_color": "#352742",
|
||||
"icons": [
|
||||
{
|
||||
"src": "./favicon.svg",
|
||||
"sizes": "any",
|
||||
"type": "image/svg+xml",
|
||||
"purpose": "any maskable"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
const CACHE = "font-tools-v0.1.0",
|
||||
APP = [
|
||||
"./",
|
||||
"./index.html",
|
||||
"./manifest.webmanifest",
|
||||
"./favicon.svg",
|
||||
"./toolbox-app.json",
|
||||
];
|
||||
|
||||
async function precacheAppShell() {
|
||||
const cache = await caches.open(CACHE);
|
||||
await cache.addAll(APP);
|
||||
const index = await cache.match("./index.html");
|
||||
if (index) {
|
||||
const markup = await index.text(),
|
||||
scope = new URL(self.registration.scope),
|
||||
assets = [...markup.matchAll(/\b(?:src|href)=["']([^"'#]+)["']/g)]
|
||||
.map((match) => new URL(match[1], self.location.href))
|
||||
.filter(
|
||||
(url) =>
|
||||
url.origin === scope.origin &&
|
||||
url.pathname.startsWith(scope.pathname),
|
||||
);
|
||||
await cache.addAll(assets);
|
||||
}
|
||||
}
|
||||
|
||||
self.addEventListener("install", (event) =>
|
||||
event.waitUntil(precacheAppShell().then(() => self.skipWaiting())),
|
||||
);
|
||||
self.addEventListener("activate", (event) =>
|
||||
event.waitUntil(
|
||||
caches
|
||||
.keys()
|
||||
.then((keys) =>
|
||||
Promise.all(
|
||||
keys.filter((key) => key !== CACHE).map((key) => caches.delete(key)),
|
||||
),
|
||||
)
|
||||
.then(() => self.clients.claim()),
|
||||
),
|
||||
);
|
||||
self.addEventListener("fetch", (event) => {
|
||||
if (
|
||||
event.request.method !== "GET" ||
|
||||
new URL(event.request.url).origin !== self.location.origin
|
||||
)
|
||||
return;
|
||||
event.respondWith(
|
||||
(async () => {
|
||||
const cached = await caches.match(event.request);
|
||||
if (cached) return cached;
|
||||
try {
|
||||
const response = await fetch(event.request);
|
||||
if (response.ok) {
|
||||
const cache = await caches.open(CACHE);
|
||||
await cache.put(event.request, response.clone());
|
||||
}
|
||||
return response;
|
||||
} catch (error) {
|
||||
if (event.request.mode === "navigate") {
|
||||
const fallback = await caches.match("./index.html");
|
||||
if (fallback) return fallback;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
})(),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"$schema": "https://git.add-ideas.de/lotobo/toolbox-sdk/raw/branch/main/schemas/toolbox-app.v1.schema.json",
|
||||
"schemaVersion": 1,
|
||||
"id": "de.add-ideas.font-tools",
|
||||
"name": "Font Tools",
|
||||
"version": "0.1.0",
|
||||
"description": "Inspect and prepare fonts locally.",
|
||||
"entry": "./",
|
||||
"icon": "./favicon.svg",
|
||||
"categories": ["design", "developer"],
|
||||
"tags": ["font", "ttf", "otf", "woff", "glyph", "typography", "subset"],
|
||||
"integration": {
|
||||
"contextVersion": 1,
|
||||
"launchModes": ["navigate", "new-tab"],
|
||||
"embedding": "unsupported"
|
||||
},
|
||||
"requirements": {
|
||||
"secureContext": false,
|
||||
"workers": true,
|
||||
"indexedDb": false,
|
||||
"crossOriginIsolated": false,
|
||||
"topLevelContext": false
|
||||
},
|
||||
"privacy": {
|
||||
"processing": "local",
|
||||
"fileUploads": true,
|
||||
"telemetry": false,
|
||||
"label": "Font files and preview text remain in this browser."
|
||||
},
|
||||
"source": {
|
||||
"repository": "https://git.add-ideas.de/lotobo/font-tools",
|
||||
"license": "GPL-3.0-or-later"
|
||||
},
|
||||
"actions": [
|
||||
{
|
||||
"id": "source",
|
||||
"label": "Source",
|
||||
"url": "https://git.add-ideas.de/lotobo/font-tools"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { format } from "prettier";
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const sourcePath = path.join(root, "src/toolbox/manifest.source.json");
|
||||
const outputPath = path.join(root, "public/toolbox-app.json");
|
||||
const source = JSON.parse(await readFile(sourcePath, "utf8"));
|
||||
const pkg = JSON.parse(await readFile(path.join(root, "package.json"), "utf8"));
|
||||
const versionSource = await readFile(path.join(root, "src/version.ts"), "utf8");
|
||||
const appVersion = /^export const APP_VERSION = "([^"]+)";$/mu.exec(
|
||||
versionSource,
|
||||
)?.[1];
|
||||
const repository = "https://git.add-ideas.de/lotobo/" + pkg.name;
|
||||
if (source.version !== pkg.version || appVersion !== pkg.version)
|
||||
throw new Error("Version identity drift");
|
||||
if (
|
||||
source.id !== "de.add-ideas." + pkg.name ||
|
||||
source.source?.repository !== repository ||
|
||||
source.source?.license !== "GPL-3.0-or-later"
|
||||
)
|
||||
throw new Error("Manifest source identity is invalid");
|
||||
const serialized = await format(JSON.stringify(source), {
|
||||
filepath: outputPath,
|
||||
});
|
||||
if (process.argv.includes("--check")) {
|
||||
if ((await readFile(outputPath, "utf8").catch(() => "")) !== serialized)
|
||||
throw new Error("public/toolbox-app.json is stale");
|
||||
console.log("Toolbox manifest is synchronized");
|
||||
} else {
|
||||
await writeFile(outputPath, serialized);
|
||||
console.log("Generated public/toolbox-app.json");
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
#!/usr/bin/env node
|
||||
import { createHash } from "node:crypto";
|
||||
import { execFile } from "node:child_process";
|
||||
import {
|
||||
access,
|
||||
chmod,
|
||||
copyFile,
|
||||
cp,
|
||||
lstat,
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
readFile,
|
||||
readdir,
|
||||
rename,
|
||||
rm,
|
||||
utimes,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { fileURLToPath } from "node:url";
|
||||
const execute = promisify(execFile);
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const pkg = JSON.parse(await readFile(path.join(root, "package.json"), "utf8"));
|
||||
const argument = (name, fallback) => {
|
||||
const index = process.argv.indexOf(name);
|
||||
return index >= 0 ? process.argv[index + 1] : fallback;
|
||||
};
|
||||
const output = path.resolve(
|
||||
root,
|
||||
argument("--output", "release/" + pkg.name + "-" + pkg.version + ".zip"),
|
||||
);
|
||||
const checksumOutput = output + ".sha256";
|
||||
const force = process.argv.includes("--force");
|
||||
if (
|
||||
path.extname(output).toLowerCase() !== ".zip" ||
|
||||
output === root ||
|
||||
output === path.parse(output).root
|
||||
)
|
||||
throw new Error("Unsafe release target");
|
||||
const exists = (file) =>
|
||||
access(file).then(
|
||||
() => true,
|
||||
() => false,
|
||||
);
|
||||
if (!force && ((await exists(output)) || (await exists(checksumOutput))))
|
||||
throw new Error("Release output exists");
|
||||
const input = path.join(root, "dist");
|
||||
for (const name of [
|
||||
"index.html",
|
||||
"manifest.webmanifest",
|
||||
"sw.js",
|
||||
"toolbox-app.json",
|
||||
"favicon.svg",
|
||||
"README.md",
|
||||
"CHANGELOG.md",
|
||||
"CONTRIBUTING.md",
|
||||
"LICENSE",
|
||||
"SECURITY.md",
|
||||
"SOURCE.md",
|
||||
"THIRD_PARTY_NOTICES.md",
|
||||
"LICENSES/README.md",
|
||||
"LICENSES/npm-runtime-licenses.txt",
|
||||
"docs/ACCESSIBILITY.md",
|
||||
"docs/ARCHITECTURE.md",
|
||||
"docs/PRIVACY-SECURITY.md",
|
||||
]) {
|
||||
const details = await lstat(path.join(input, name)).catch(() => null);
|
||||
if (!details?.isFile() || details.isSymbolicLink())
|
||||
throw new Error("Missing release file: " + name);
|
||||
}
|
||||
const manifest = JSON.parse(
|
||||
await readFile(path.join(input, "toolbox-app.json"), "utf8"),
|
||||
);
|
||||
const repository = "https://git.add-ideas.de/lotobo/" + pkg.name;
|
||||
if (
|
||||
manifest.id !== "de.add-ideas." + pkg.name ||
|
||||
manifest.version !== pkg.version ||
|
||||
manifest.entry !== "./" ||
|
||||
manifest.icon !== "./favicon.svg" ||
|
||||
manifest.source?.repository !== repository
|
||||
)
|
||||
throw new Error("Packaged manifest identity is invalid");
|
||||
if (
|
||||
/\b(?:src|href)=["']\//iu.test(
|
||||
await readFile(path.join(input, "index.html"), "utf8"),
|
||||
)
|
||||
)
|
||||
throw new Error("Root-absolute asset reference");
|
||||
async function collect(directory, prefix = "") {
|
||||
const files = [];
|
||||
for (const entry of (await readdir(directory, { withFileTypes: true })).sort(
|
||||
(a, b) => (a.name === b.name ? 0 : a.name < b.name ? -1 : 1),
|
||||
)) {
|
||||
const absolute = path.join(directory, entry.name);
|
||||
const relative = prefix ? prefix + "/" + entry.name : entry.name;
|
||||
if (entry.isSymbolicLink())
|
||||
throw new Error("Symlink in release: " + relative);
|
||||
if (entry.isDirectory()) files.push(...(await collect(absolute, relative)));
|
||||
else if (entry.isFile()) files.push({ absolute, relative });
|
||||
else throw new Error("Unsupported release entry: " + relative);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
const sourceFiles = await collect(input);
|
||||
for (const file of sourceFiles)
|
||||
if (
|
||||
file.relative.endsWith(".map") ||
|
||||
/(?:^|\/)(?:\.env(?:\.|$)|id_rsa|id_ed25519|.*\.pem$|.*\.key$)/iu.test(
|
||||
file.relative,
|
||||
) ||
|
||||
file.relative.split("/").includes("..")
|
||||
)
|
||||
throw new Error("Forbidden release entry: " + file.relative);
|
||||
await mkdir(path.dirname(output), { recursive: true });
|
||||
const stagingRoot = await mkdtemp(
|
||||
path.join(os.tmpdir(), pkg.name + "-release-"),
|
||||
);
|
||||
const publicationRoot = await mkdtemp(
|
||||
path.join(path.dirname(output), "." + pkg.name + "-publish-"),
|
||||
);
|
||||
const stagedTree = path.join(stagingRoot, "tree");
|
||||
const stagedArchive = path.join(stagingRoot, path.basename(output));
|
||||
try {
|
||||
await cp(input, stagedTree, { recursive: true });
|
||||
const timestamp = new Date("1980-01-01T00:00:00.000Z");
|
||||
for (const file of await collect(stagedTree)) {
|
||||
await chmod(file.absolute, 0o644);
|
||||
await utimes(file.absolute, timestamp, timestamp);
|
||||
}
|
||||
await execute(
|
||||
"zip",
|
||||
[
|
||||
"-X",
|
||||
"-q",
|
||||
"-9",
|
||||
stagedArchive,
|
||||
...sourceFiles.map((file) => file.relative),
|
||||
],
|
||||
{
|
||||
cwd: stagedTree,
|
||||
env: { ...process.env, TZ: "UTC" },
|
||||
maxBuffer: 1024 * 1024,
|
||||
},
|
||||
);
|
||||
const archive = await readFile(stagedArchive);
|
||||
const digest = createHash("sha256").update(archive).digest("hex");
|
||||
const stagedChecksum = stagedArchive + ".sha256";
|
||||
await writeFile(stagedChecksum, digest + " " + path.basename(output) + "\n");
|
||||
const publicationArchive = path.join(publicationRoot, path.basename(output));
|
||||
const publicationChecksum = publicationArchive + ".sha256";
|
||||
await copyFile(stagedArchive, publicationArchive);
|
||||
await copyFile(stagedChecksum, publicationChecksum);
|
||||
if (force) {
|
||||
await rm(output, { force: true });
|
||||
await rm(checksumOutput, { force: true });
|
||||
}
|
||||
await rename(publicationArchive, output);
|
||||
await rename(publicationChecksum, checksumOutput);
|
||||
console.log("Created " + path.relative(root, output) + "\nSHA-256 " + digest);
|
||||
} finally {
|
||||
await rm(stagingRoot, { recursive: true, force: true });
|
||||
await rm(publicationRoot, { recursive: true, force: true });
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { cp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const destination = path.join(root, "public");
|
||||
for (const name of [
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
"CHANGELOG.md",
|
||||
"CONTRIBUTING.md",
|
||||
"SECURITY.md",
|
||||
"SOURCE.md",
|
||||
"THIRD_PARTY_NOTICES.md",
|
||||
]) {
|
||||
await readFile(path.join(root, name));
|
||||
await cp(path.join(root, name), path.join(destination, name));
|
||||
}
|
||||
for (const directory of ["LICENSES", "docs"]) {
|
||||
const output = path.join(destination, directory);
|
||||
await rm(output, { recursive: true, force: true });
|
||||
await cp(path.join(root, directory), output, { recursive: true });
|
||||
}
|
||||
const lock = JSON.parse(
|
||||
await readFile(path.join(root, "package-lock.json"), "utf8"),
|
||||
);
|
||||
const sections = [];
|
||||
for (const [location, locked] of Object.entries(lock.packages ?? {}).sort(
|
||||
([a], [b]) => (a === b ? 0 : a < b ? -1 : 1),
|
||||
)) {
|
||||
if (!location.includes("node_modules/") || locked.dev === true) continue;
|
||||
const packageDirectory = path.join(root, location);
|
||||
const details = JSON.parse(
|
||||
await readFile(path.join(packageDirectory, "package.json"), "utf8"),
|
||||
);
|
||||
const candidates = (await readdir(packageDirectory))
|
||||
.filter((name) => /^(?:licen[cs]e|copying|notice)(?:\.|$)/iu.test(name))
|
||||
.sort();
|
||||
const texts = [];
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
texts.push(
|
||||
"--- " +
|
||||
candidate +
|
||||
" ---\n" +
|
||||
(await readFile(path.join(packageDirectory, candidate), "utf8")),
|
||||
);
|
||||
} catch {
|
||||
/* directory */
|
||||
}
|
||||
}
|
||||
sections.push(
|
||||
"=".repeat(78) +
|
||||
"\n" +
|
||||
details.name +
|
||||
"@" +
|
||||
details.version +
|
||||
"\nDeclared licence: " +
|
||||
(details.license ?? locked.license ?? "See upstream") +
|
||||
"\n" +
|
||||
"=".repeat(78) +
|
||||
"\n" +
|
||||
(texts.join("\n\n") || "See upstream package metadata."),
|
||||
);
|
||||
}
|
||||
await mkdir(path.join(destination, "LICENSES"), { recursive: true });
|
||||
await writeFile(
|
||||
path.join(destination, "LICENSES/npm-runtime-licenses.txt"),
|
||||
sections.join("\n\n").trimEnd() + "\n",
|
||||
);
|
||||
console.log("Prepared release documentation");
|
||||
@@ -0,0 +1,55 @@
|
||||
import { createServer } from "node:http";
|
||||
import { readFile, stat } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
const root = path.resolve(
|
||||
path.dirname(fileURLToPath(import.meta.url)),
|
||||
"..",
|
||||
"dist",
|
||||
),
|
||||
prefix = "/font/",
|
||||
types = new Map([
|
||||
[".css", "text/css; charset=utf-8"],
|
||||
[".html", "text/html; charset=utf-8"],
|
||||
[".js", "text/javascript; charset=utf-8"],
|
||||
[".json", "application/json; charset=utf-8"],
|
||||
[".webmanifest", "application/manifest+json; charset=utf-8"],
|
||||
[".svg", "image/svg+xml"],
|
||||
[".md", "text/markdown; charset=utf-8"],
|
||||
[".txt", "text/plain; charset=utf-8"],
|
||||
[".woff", "font/woff"],
|
||||
[".woff2", "font/woff2"],
|
||||
[".ttf", "font/ttf"],
|
||||
[".otf", "font/otf"],
|
||||
]),
|
||||
headers = {
|
||||
"Content-Security-Policy":
|
||||
"default-src 'self';base-uri 'self';object-src 'none';frame-ancestors 'none';form-action 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' blob: data:;frame-src 'self' blob:;connect-src 'self';worker-src 'self' blob:;manifest-src 'self'",
|
||||
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
};
|
||||
createServer(async (q, s) => {
|
||||
try {
|
||||
const u = new URL(q.url ?? "/", "http://127.0.0.1"),
|
||||
d = decodeURIComponent(u.pathname),
|
||||
r = d.startsWith(prefix) ? d.slice(prefix.length) : d.replace(/^\/+/, ""),
|
||||
n = path.posix.normalize(r || "index.html");
|
||||
if (n === ".." || n.startsWith("../") || path.isAbsolute(n))
|
||||
return void s.writeHead(400).end();
|
||||
let f = path.join(root, n);
|
||||
if ((await stat(f).catch(() => null))?.isDirectory())
|
||||
f = path.join(f, "index.html");
|
||||
const c = await readFile(f);
|
||||
s.writeHead(200, {
|
||||
"Content-Type": types.get(path.extname(f)) ?? "application/octet-stream",
|
||||
"Cache-Control": n.startsWith("assets/")
|
||||
? "public,max-age=31536000,immutable"
|
||||
: "no-cache",
|
||||
...headers,
|
||||
});
|
||||
s.end(c);
|
||||
} catch {
|
||||
s.writeHead(404).end("Not found");
|
||||
}
|
||||
}).listen(4202, "127.0.0.1", () => console.log("ready"));
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
import { useState } from "react";
|
||||
import { AppShell } from "@add-ideas/toolbox-shell-react";
|
||||
import "@add-ideas/toolbox-shell-react/styles.css";
|
||||
import "./styles.css";
|
||||
import { ErrorBoundary } from "./components/ErrorBoundary";
|
||||
import { HelpDialog } from "./components/HelpDialog";
|
||||
import { Workbench } from "./components/Workbench";
|
||||
import { manifest } from "./toolbox/manifest";
|
||||
|
||||
export function App() {
|
||||
const [help, setHelp] = useState(false);
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<AppShell
|
||||
app={manifest}
|
||||
manifestUrl="./toolbox-app.json"
|
||||
helpAction={{ onClick: () => setHelp(true) }}
|
||||
>
|
||||
<Workbench />
|
||||
</AppShell>
|
||||
<HelpDialog open={help} onClose={() => setHelp(false)} />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Component, type ErrorInfo, type ReactNode } from "react";
|
||||
|
||||
export class ErrorBoundary extends Component<
|
||||
{ children: ReactNode },
|
||||
{ error?: Error }
|
||||
> {
|
||||
state: { error?: Error } = {};
|
||||
static getDerivedStateFromError(error: Error) {
|
||||
return { error };
|
||||
}
|
||||
componentDidCatch(error: Error, info: ErrorInfo) {
|
||||
console.error("Application failure", error, info);
|
||||
}
|
||||
render() {
|
||||
if (this.state.error)
|
||||
return (
|
||||
<main className="fatal">
|
||||
<h1>Font Tools could not continue</h1>
|
||||
<p>{this.state.error.message}</p>
|
||||
<button type="button" onClick={() => location.reload()}>
|
||||
Reload
|
||||
</button>
|
||||
</main>
|
||||
);
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useMemo } from "react";
|
||||
import { previewDocument } from "../core/preview";
|
||||
|
||||
export function FontPreview({
|
||||
fontUrl,
|
||||
text,
|
||||
fontSize,
|
||||
lineHeight,
|
||||
axes,
|
||||
}: {
|
||||
fontUrl: string;
|
||||
text: string;
|
||||
fontSize: number;
|
||||
lineHeight: number;
|
||||
axes: Record<string, number>;
|
||||
}) {
|
||||
const source = useMemo(
|
||||
() => previewDocument(fontUrl, text, fontSize, lineHeight, axes),
|
||||
[fontUrl, text, fontSize, lineHeight, axes],
|
||||
);
|
||||
return (
|
||||
<iframe
|
||||
className="font-preview-frame"
|
||||
title="Isolated font and fallback comparison"
|
||||
sandbox="allow-same-origin"
|
||||
referrerPolicy="no-referrer"
|
||||
srcDoc={source}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
export function HelpDialog({
|
||||
open,
|
||||
onClose,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const ref = useRef<HTMLDialogElement>(null);
|
||||
useEffect(() => {
|
||||
const dialog = ref.current;
|
||||
if (!dialog) return;
|
||||
if (open && !dialog.open) dialog.showModal();
|
||||
if (!open && dialog.open) dialog.close();
|
||||
}, [open]);
|
||||
return (
|
||||
<dialog
|
||||
ref={ref}
|
||||
className="help-dialog"
|
||||
onClose={onClose}
|
||||
onCancel={onClose}
|
||||
aria-labelledby="help-title"
|
||||
>
|
||||
<div className="dialog-heading">
|
||||
<div>
|
||||
<p className="eyebrow">Local-first help</p>
|
||||
<h2 id="help-title">About Font Tools</h2>
|
||||
</div>
|
||||
<button onClick={onClose} aria-label="Close help">
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
<p>
|
||||
Open one local TTF, OTF or WOFF file. The table directory is checked
|
||||
before opentype.js parses it in a disposable worker. WOFF2 and font
|
||||
collections are identified but deliberately unsupported in v0.1.
|
||||
</p>
|
||||
<p>
|
||||
Preview text is rendered in a scriptless sandbox. Coverage results are
|
||||
based on the font's Unicode cmap and do not promise that every
|
||||
shaping sequence or colour glyph will render in every browser.
|
||||
</p>
|
||||
<p>
|
||||
OS/2 embedding flags are shown as technical evidence, not legal advice.
|
||||
Static subsetting is blocked for restricted, no-subsetting, bitmap-only
|
||||
and variable fonts, and always requires a rights confirmation.
|
||||
</p>
|
||||
</dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,767 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { triggerBlobDownload } from "@add-ideas/toolbox-helpers";
|
||||
import { generateFontFace, suggestedFamily } from "../core/css";
|
||||
import { FontWorkerClient } from "../core/fontClient";
|
||||
import type {
|
||||
CoverageInspection,
|
||||
FontInspection,
|
||||
SubsetResult,
|
||||
} from "../core/model";
|
||||
import { FONT_LIMITS } from "../core/sfnt";
|
||||
import { FontPreview } from "./FontPreview";
|
||||
|
||||
const SAMPLE =
|
||||
"Hamburgefontsiv 0123456789\nÀ bientôt · Καλημέρα · Привет · مرحبًا · 日本語 · 🙂";
|
||||
|
||||
export function Workbench() {
|
||||
const client = useRef<FontWorkerClient | null>(null),
|
||||
generation = useRef(0),
|
||||
previewUrl = useRef<string | null>(null),
|
||||
[inspection, setInspection] = useState<FontInspection | null>(null),
|
||||
[coverage, setCoverage] = useState<CoverageInspection | null>(null),
|
||||
[previewText, setPreviewText] = useState(SAMPLE),
|
||||
[fontSize, setFontSize] = useState(42),
|
||||
[lineHeight, setLineHeight] = useState(1.25),
|
||||
[axes, setAxes] = useState<Record<string, number>>({}),
|
||||
[url, setUrl] = useState<string | null>(null),
|
||||
[operation, setOperation] = useState<"load" | "coverage" | "subset" | null>(
|
||||
null,
|
||||
),
|
||||
[status, setStatus] = useState(
|
||||
"Choose a local TTF, OTF or WOFF font to begin.",
|
||||
),
|
||||
[tableFilter, setTableFilter] = useState(""),
|
||||
[cssFamily, setCssFamily] = useState("Local font"),
|
||||
[cssPath, setCssPath] = useState("./fonts/local-font.woff"),
|
||||
[fontDisplay, setFontDisplay] = useState<
|
||||
"auto" | "block" | "swap" | "fallback" | "optional"
|
||||
>("swap"),
|
||||
[unicodeRange, setUnicodeRange] = useState(false),
|
||||
[subsetText, setSubsetText] = useState(SAMPLE),
|
||||
[rightsConfirmed, setRightsConfirmed] = useState(false),
|
||||
[subsetReport, setSubsetReport] = useState<SubsetResult | null>(null);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
client.current?.terminate();
|
||||
if (previewUrl.current) URL.revokeObjectURL(previewUrl.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const cssResult = useMemo(() => {
|
||||
if (!inspection) return null;
|
||||
try {
|
||||
return generateFontFace({
|
||||
family: cssFamily,
|
||||
sourcePath: cssPath,
|
||||
display: fontDisplay,
|
||||
inspection,
|
||||
includeUnicodeRange: unicodeRange,
|
||||
});
|
||||
} catch (error) {
|
||||
return { css: "", warnings: [message(error)] };
|
||||
}
|
||||
}, [cssFamily, cssPath, fontDisplay, inspection, unicodeRange]);
|
||||
|
||||
async function openFont(file: File) {
|
||||
const token = ++generation.current,
|
||||
candidate = new FontWorkerClient();
|
||||
setOperation("load");
|
||||
setStatus(`Inspecting ${file.name} in an isolated worker…`);
|
||||
try {
|
||||
const next = await candidate.load(file),
|
||||
nextCoverage = await candidate.coverage(previewText);
|
||||
if (token !== generation.current) return candidate.terminate();
|
||||
client.current?.terminate();
|
||||
client.current = candidate;
|
||||
if (previewUrl.current) URL.revokeObjectURL(previewUrl.current);
|
||||
const nextUrl = URL.createObjectURL(file);
|
||||
previewUrl.current = nextUrl;
|
||||
setUrl(nextUrl);
|
||||
setInspection(next);
|
||||
setCoverage(nextCoverage);
|
||||
setAxes(
|
||||
Object.fromEntries(next.axes.map((axis) => [axis.tag, axis.default])),
|
||||
);
|
||||
setCssFamily(suggestedFamily(next));
|
||||
setCssPath(`./fonts/${safeAssetName(file.name)}`);
|
||||
setSubsetReport(null);
|
||||
setRightsConfirmed(false);
|
||||
setStatus(
|
||||
`Inspected ${next.glyphCount.toLocaleString()} glyphs, ${next.unicodeCount.toLocaleString()} Unicode values and ${next.tables.length} tables locally.`,
|
||||
);
|
||||
} catch (error) {
|
||||
candidate.terminate();
|
||||
if (token === generation.current)
|
||||
setStatus(`${message(error)} The last valid font remains visible.`);
|
||||
} finally {
|
||||
if (token === generation.current) setOperation(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function analyzeCoverage() {
|
||||
if (!client.current) return;
|
||||
setOperation("coverage");
|
||||
setStatus("Checking unique preview characters against the font cmap…");
|
||||
try {
|
||||
const next = await client.current.coverage(previewText);
|
||||
setCoverage(next);
|
||||
setStatus(
|
||||
`${next.covered} unique characters map to glyphs; ${next.missing} use .notdef/fallback${next.truncated ? "; the per-character list is capped" : ""}.`,
|
||||
);
|
||||
} catch (error) {
|
||||
setStatus(`${message(error)} The last coverage result remains visible.`);
|
||||
} finally {
|
||||
setOperation(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function buildSubset() {
|
||||
if (!client.current || !inspection) return;
|
||||
setOperation("subset");
|
||||
setStatus("Rebuilding and validating a bounded static subset locally…");
|
||||
try {
|
||||
const result = await client.current.subset(
|
||||
subsetText,
|
||||
cssFamily,
|
||||
rightsConfirmed,
|
||||
);
|
||||
setSubsetReport(result);
|
||||
triggerBlobDownload(
|
||||
new Blob([result.buffer], { type: "font/otf" }),
|
||||
result.fileName,
|
||||
);
|
||||
setStatus(
|
||||
`Created ${result.subsetGlyphs} glyphs from ${result.sourceGlyphs.toLocaleString()} source glyphs and started the local download.`,
|
||||
);
|
||||
} catch (error) {
|
||||
setStatus(`${message(error)} No subset was downloaded.`);
|
||||
} finally {
|
||||
setOperation(null);
|
||||
}
|
||||
}
|
||||
|
||||
const filteredTables = inspection?.tables.filter((table) => {
|
||||
const query = tableFilter.trim().toLowerCase();
|
||||
return (
|
||||
!query ||
|
||||
`${table.tag} ${table.description}`.toLowerCase().includes(query)
|
||||
);
|
||||
});
|
||||
const subsetBlocked = inspection
|
||||
? subsetBlockReason(inspection)
|
||||
: "Load a font first.";
|
||||
|
||||
return (
|
||||
<main className="workbench">
|
||||
<section className="hero panel">
|
||||
<div>
|
||||
<p className="eyebrow">Bounded local font laboratory</p>
|
||||
<h1>Know what is inside a font.</h1>
|
||||
<p>
|
||||
Inspect tables and rights signals, test real text and fallbacks,
|
||||
then generate deployment CSS or an honest static subset—without
|
||||
uploading the font.
|
||||
</p>
|
||||
</div>
|
||||
<label className={`file-button ${operation === "load" ? "busy" : ""}`}>
|
||||
{operation === "load" ? "Inspecting…" : "Open font"}
|
||||
<input
|
||||
type="file"
|
||||
accept=".ttf,.otf,.woff,.woff2,font/ttf,font/otf,font/woff,font/woff2"
|
||||
disabled={operation === "load"}
|
||||
onChange={(event) => {
|
||||
const file = event.currentTarget.files?.[0];
|
||||
if (file) void openFont(file);
|
||||
event.currentTarget.value = "";
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
</section>
|
||||
|
||||
<p className="status" role="status" aria-live="polite">
|
||||
{status}
|
||||
</p>
|
||||
|
||||
{!inspection || !url ? (
|
||||
<section className="empty panel">
|
||||
<div className="drop-icon" aria-hidden="true">
|
||||
Aa
|
||||
</div>
|
||||
<h2>Everything stays on this device</h2>
|
||||
<p>
|
||||
TTF, OTF and WOFF up to 16 MiB are accepted. WOFF2 is identified and
|
||||
rejected clearly because opentype.js does not decode it.
|
||||
</p>
|
||||
<dl className="limit-grid">
|
||||
<div>
|
||||
<dt>Parser</dt>
|
||||
<dd>Disposable worker · 8 s</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Expanded data</dt>
|
||||
<dd>64 MiB maximum</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Output</dt>
|
||||
<dd>Explicit downloads only</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</section>
|
||||
) : (
|
||||
<>
|
||||
<section className="summary-grid" aria-label="Font summary">
|
||||
<Summary
|
||||
label="Identity"
|
||||
value={
|
||||
inspection.names.fullName ||
|
||||
inspection.names.family ||
|
||||
inspection.fileName
|
||||
}
|
||||
detail={inspection.names.version || "Version not named"}
|
||||
/>
|
||||
<Summary
|
||||
label="Format"
|
||||
value={inspection.flavor}
|
||||
detail={`${formatBytes(inspection.fileSize)} source · ${formatBytes(inspection.expandedSize)} expanded`}
|
||||
/>
|
||||
<Summary
|
||||
label="Coverage"
|
||||
value={`${inspection.unicodeCount.toLocaleString()} Unicode values`}
|
||||
detail={`${inspection.glyphCount.toLocaleString()} glyphs`}
|
||||
/>
|
||||
<Summary
|
||||
label="Embedding signal"
|
||||
value={inspection.embedding.label}
|
||||
detail={`${inspection.embedding.rawHex} · ${inspection.embedding.subsetAllowed ? "subset not blocked" : "subset blocked"}`}
|
||||
tone={inspection.embedding.subsetAllowed ? "ok" : "warn"}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="panel preview-panel">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<p className="eyebrow">Preview & fallback comparison</p>
|
||||
<h2>Your text, four ways</h2>
|
||||
</div>
|
||||
<span className="isolation">Scriptless sandbox</span>
|
||||
</div>
|
||||
<label>
|
||||
Preview text
|
||||
<textarea
|
||||
value={previewText}
|
||||
maxLength={FONT_LIMITS.previewCharacters}
|
||||
onChange={(event) => setPreviewText(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<div className="preview-controls">
|
||||
<label>
|
||||
Size{" "}
|
||||
<input
|
||||
type="range"
|
||||
min="12"
|
||||
max="160"
|
||||
value={fontSize}
|
||||
onChange={(event) => setFontSize(event.target.valueAsNumber)}
|
||||
/>
|
||||
<span>{fontSize}px</span>
|
||||
</label>
|
||||
<label>
|
||||
Line height{" "}
|
||||
<input
|
||||
type="range"
|
||||
min="0.8"
|
||||
max="2.5"
|
||||
step="0.05"
|
||||
value={lineHeight}
|
||||
onChange={(event) =>
|
||||
setLineHeight(event.target.valueAsNumber)
|
||||
}
|
||||
/>
|
||||
<span>{lineHeight.toFixed(2)}</span>
|
||||
</label>
|
||||
</div>
|
||||
{inspection.axes.length > 0 && (
|
||||
<fieldset className="axes">
|
||||
<legend>Variable axes</legend>
|
||||
{inspection.axes.map((axis) => (
|
||||
<label key={axis.tag}>
|
||||
<span>
|
||||
<strong>{axis.name}</strong> <code>{axis.tag}</code>
|
||||
</span>
|
||||
<input
|
||||
type="range"
|
||||
min={axis.min}
|
||||
max={axis.max}
|
||||
step={(axis.max - axis.min) / 200 || 1}
|
||||
value={axes[axis.tag] ?? axis.default}
|
||||
onChange={(event) =>
|
||||
setAxes((current) => ({
|
||||
...current,
|
||||
[axis.tag]: event.target.valueAsNumber,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<span>
|
||||
{Number((axes[axis.tag] ?? axis.default).toFixed(3))}
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setAxes(
|
||||
Object.fromEntries(
|
||||
inspection.axes.map((axis) => [axis.tag, axis.default]),
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
Reset axes
|
||||
</button>
|
||||
</fieldset>
|
||||
)}
|
||||
<FontPreview
|
||||
fontUrl={url}
|
||||
text={previewText}
|
||||
fontSize={fontSize}
|
||||
lineHeight={lineHeight}
|
||||
axes={axes}
|
||||
/>
|
||||
{[...previewText].length > 5_000 && (
|
||||
<p className="note">
|
||||
The visual preview shows the first 5,000 characters; cmap
|
||||
analysis accepts all 20,000.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<div className="two-column">
|
||||
<section className="panel">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<p className="eyebrow">Names & metrics</p>
|
||||
<h2>Identity records</h2>
|
||||
</div>
|
||||
</div>
|
||||
<dl className="metadata-list">
|
||||
{nameEntries(inspection).map(([label, value]) => (
|
||||
<div key={label}>
|
||||
<dt>{label}</dt>
|
||||
<dd>{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
<div>
|
||||
<dt>Units per em</dt>
|
||||
<dd>{inspection.unitsPerEm.toLocaleString()}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Ascender / descender</dt>
|
||||
<dd>
|
||||
{inspection.ascender.toLocaleString()} /{" "}
|
||||
{inspection.descender.toLocaleString()}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</section>
|
||||
<section
|
||||
className={`panel rights ${inspection.embedding.subsetAllowed ? "allowed" : "blocked"}`}
|
||||
>
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<p className="eyebrow">OS/2 fsType</p>
|
||||
<h2>Embedding & licence signals</h2>
|
||||
</div>
|
||||
<code>{inspection.embedding.rawHex}</code>
|
||||
</div>
|
||||
<p className="rights-label">{inspection.embedding.label}</p>
|
||||
<ul>
|
||||
{inspection.embedding.signals.map((signal) => (
|
||||
<li key={signal}>{signal}</li>
|
||||
))}
|
||||
</ul>
|
||||
{inspection.names.license && (
|
||||
<div className="license-text">
|
||||
<strong>Embedded licence text</strong>
|
||||
<p>{inspection.names.license}</p>
|
||||
</div>
|
||||
)}
|
||||
{inspection.names.licenseUrl && (
|
||||
<p>
|
||||
<strong>Recorded licence URL:</strong>{" "}
|
||||
<span className="break">{inspection.names.licenseUrl}</span>
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section className="panel coverage-panel">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<p className="eyebrow">Unicode cmap</p>
|
||||
<h2>Coverage</h2>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => void analyzeCoverage()}
|
||||
disabled={operation !== null}
|
||||
>
|
||||
{operation === "coverage"
|
||||
? "Checking…"
|
||||
: "Analyze preview text"}
|
||||
</button>
|
||||
</div>
|
||||
<div className="block-grid">
|
||||
{inspection.coverageBlocks.map((block) => (
|
||||
<div className="coverage-block" key={block.id}>
|
||||
<div>
|
||||
<strong>{block.label}</strong>
|
||||
<span>
|
||||
{block.covered.toLocaleString()} /{" "}
|
||||
{block.total.toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
<meter min="0" max={block.total} value={block.covered}>
|
||||
{Math.round((block.covered / block.total) * 100)}%
|
||||
</meter>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{coverage && (
|
||||
<>
|
||||
<p className="coverage-summary">
|
||||
<strong>{coverage.covered}</strong> mapped ·{" "}
|
||||
<strong>{coverage.missing}</strong> missing among unique
|
||||
preview characters
|
||||
</p>
|
||||
<div
|
||||
className="glyph-strip"
|
||||
aria-label="Preview character coverage"
|
||||
>
|
||||
{coverage.characters.slice(0, 256).map((entry) => (
|
||||
<span
|
||||
className={entry.covered ? "covered" : "missing"}
|
||||
key={`${entry.codePoint}-${entry.character}`}
|
||||
title={`U+${hex(entry.codePoint)} · ${entry.glyphName} · ${entry.covered ? "mapped" : "missing"}`}
|
||||
>
|
||||
<span className="glyph-char">
|
||||
{visibleCharacter(entry.character)}
|
||||
</span>
|
||||
<small>U+{hex(entry.codePoint)}</small>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
{(coverage.characters.length > 256 || coverage.truncated) && (
|
||||
<p className="note">
|
||||
Showing the first 256 unique characters; analysis records at
|
||||
most 2,048.
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<details>
|
||||
<summary>
|
||||
Unicode range inventory ({inspection.coverageRanges.length}
|
||||
{inspection.coverageRangesTruncated ? "+" : ""})
|
||||
</summary>
|
||||
<div className="range-list">
|
||||
{inspection.coverageRanges.map((range) => (
|
||||
<code key={`${range.start}-${range.end}`}>
|
||||
U+{hex(range.start)}
|
||||
{range.end === range.start ? "" : `–U+${hex(range.end)}`}
|
||||
</code>
|
||||
))}
|
||||
</div>
|
||||
{inspection.coverageRangesTruncated && (
|
||||
<p>
|
||||
The range list is capped at 512 disjoint ranges; total Unicode
|
||||
count remains exact.
|
||||
</p>
|
||||
)}
|
||||
</details>
|
||||
</section>
|
||||
|
||||
<section className="panel tables-panel">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<p className="eyebrow">Validated directory</p>
|
||||
<h2>{inspection.tables.length} font tables</h2>
|
||||
</div>
|
||||
<label className="compact">
|
||||
Filter tables
|
||||
<input
|
||||
value={tableFilter}
|
||||
onChange={(event) => setTableFilter(event.target.value)}
|
||||
placeholder="cmap, variation…"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">Tag</th>
|
||||
<th scope="col">Purpose</th>
|
||||
<th scope="col">Stored</th>
|
||||
<th scope="col">Expanded</th>
|
||||
<th scope="col">Offset</th>
|
||||
<th scope="col">Checksum</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filteredTables?.map((table) => (
|
||||
<tr key={`${table.tag}-${table.offset}`}>
|
||||
<th scope="row">
|
||||
<code>{JSON.stringify(table.tag)}</code>
|
||||
</th>
|
||||
<td>{table.description}</td>
|
||||
<td>
|
||||
{formatBytes(table.storedLength)}
|
||||
{table.compressed ? " compressed" : ""}
|
||||
</td>
|
||||
<td>{formatBytes(table.length)}</td>
|
||||
<td>{table.offset.toLocaleString()}</td>
|
||||
<td>
|
||||
<code>{table.checksum}</code>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{inspection.warnings.length > 0 && (
|
||||
<div className="diagnostics">
|
||||
<h3>Inspection notes</h3>
|
||||
<ul>
|
||||
{inspection.warnings.map((warning) => (
|
||||
<li key={warning}>{warning}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<div className="two-column output-grid">
|
||||
<section className="panel">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<p className="eyebrow">Inert output</p>
|
||||
<h2>Safe @font-face CSS</h2>
|
||||
</div>
|
||||
</div>
|
||||
<label>
|
||||
Font family
|
||||
<input
|
||||
value={cssFamily}
|
||||
maxLength={200}
|
||||
onChange={(event) => setCssFamily(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Local asset path
|
||||
<input
|
||||
value={cssPath}
|
||||
maxLength={1024}
|
||||
onChange={(event) => setCssPath(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<div className="inline-controls">
|
||||
<label>
|
||||
font-display
|
||||
<select
|
||||
value={fontDisplay}
|
||||
onChange={(event) =>
|
||||
setFontDisplay(event.target.value as typeof fontDisplay)
|
||||
}
|
||||
>
|
||||
<option>swap</option>
|
||||
<option>block</option>
|
||||
<option>fallback</option>
|
||||
<option>optional</option>
|
||||
<option>auto</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={unicodeRange}
|
||||
onChange={(event) => setUnicodeRange(event.target.checked)}
|
||||
/>{" "}
|
||||
Include complete unicode-range when compact
|
||||
</label>
|
||||
</div>
|
||||
<textarea
|
||||
className="code-output"
|
||||
readOnly
|
||||
aria-label="Generated CSS"
|
||||
value={cssResult?.css ?? ""}
|
||||
/>
|
||||
{cssResult?.warnings.map((warning) => (
|
||||
<p className="note" key={warning}>
|
||||
{warning}
|
||||
</p>
|
||||
))}
|
||||
<button
|
||||
disabled={!cssResult?.css}
|
||||
onClick={() =>
|
||||
cssResult &&
|
||||
triggerBlobDownload(
|
||||
new Blob([`${cssResult.css}\n`], { type: "text/css" }),
|
||||
"font-face.css",
|
||||
)
|
||||
}
|
||||
>
|
||||
Download CSS
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<section className="panel subset-panel">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<p className="eyebrow">Bounded derivative</p>
|
||||
<h2>Simple static subset</h2>
|
||||
</div>
|
||||
</div>
|
||||
<p>
|
||||
This output intentionally does not preserve layout, variation,
|
||||
hinting, colour or signature tables. It is suitable only after
|
||||
target-software review.
|
||||
</p>
|
||||
{subsetBlocked && (
|
||||
<p className="block-reason">
|
||||
<strong>Unavailable:</strong> {subsetBlocked}
|
||||
</p>
|
||||
)}
|
||||
<label>
|
||||
Characters to retain
|
||||
<textarea
|
||||
value={subsetText}
|
||||
maxLength={FONT_LIMITS.previewCharacters}
|
||||
onChange={(event) => setSubsetText(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="check rights-check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={rightsConfirmed}
|
||||
onChange={(event) => setRightsConfirmed(event.target.checked)}
|
||||
/>{" "}
|
||||
I have reviewed the actual font licence and have rights to
|
||||
create and use this derivative.
|
||||
</label>
|
||||
<button
|
||||
className="primary"
|
||||
disabled={
|
||||
Boolean(subsetBlocked) ||
|
||||
!rightsConfirmed ||
|
||||
operation !== null
|
||||
}
|
||||
onClick={() => void buildSubset()}
|
||||
>
|
||||
{operation === "subset"
|
||||
? "Building…"
|
||||
: "Build & download .otf subset"}
|
||||
</button>
|
||||
{subsetReport && (
|
||||
<div className="loss-report">
|
||||
<h3>Last subset loss report</h3>
|
||||
<p>
|
||||
{subsetReport.subsetGlyphs} of{" "}
|
||||
{subsetReport.sourceGlyphs.toLocaleString()} glyphs ·{" "}
|
||||
{subsetReport.requestedCodePoints} requested code points
|
||||
</p>
|
||||
<ul>
|
||||
{subsetReport.losses.map((loss) => (
|
||||
<li key={loss}>{loss}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function Summary({
|
||||
label,
|
||||
value,
|
||||
detail,
|
||||
tone,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
detail: string;
|
||||
tone?: "ok" | "warn";
|
||||
}) {
|
||||
return (
|
||||
<article className={`summary-card panel ${tone ?? ""}`}>
|
||||
<p className="eyebrow">{label}</p>
|
||||
<strong>{value}</strong>
|
||||
<span>{detail}</span>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
function nameEntries(inspection: FontInspection): [string, string][] {
|
||||
const labels: Record<string, string> = {
|
||||
family: "Family",
|
||||
subfamily: "Subfamily",
|
||||
fullName: "Full name",
|
||||
postScriptName: "PostScript name",
|
||||
version: "Version",
|
||||
manufacturer: "Manufacturer",
|
||||
designer: "Designer",
|
||||
description: "Description",
|
||||
copyright: "Copyright",
|
||||
trademark: "Trademark",
|
||||
};
|
||||
return Object.entries(labels).flatMap(([key, label]) =>
|
||||
inspection.names[key]
|
||||
? [[label, inspection.names[key]!] as [string, string]]
|
||||
: [],
|
||||
);
|
||||
}
|
||||
|
||||
function subsetBlockReason(inspection: FontInspection) {
|
||||
if (!inspection.embedding.subsetAllowed)
|
||||
return `OS/2 fsType ${inspection.embedding.rawHex} declares a restriction that blocks this outline subset.`;
|
||||
if (inspection.axes.length)
|
||||
return "Variable fonts are inspected and previewed, but v0.1 does not flatten their variation model.";
|
||||
if (!inspection.tables.some((table) => ["glyf", "CFF "].includes(table.tag)))
|
||||
return "No supported static glyf or CFF outline table is present.";
|
||||
return "";
|
||||
}
|
||||
|
||||
function safeAssetName(name: string) {
|
||||
return (
|
||||
name.replace(/[^\p{Letter}\p{Number}._-]+/gu, "-").slice(0, 120) ||
|
||||
"local-font.otf"
|
||||
);
|
||||
}
|
||||
|
||||
function formatBytes(value: number) {
|
||||
if (value < 1024) return `${value} B`;
|
||||
if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KiB`;
|
||||
return `${(value / 1024 / 1024).toFixed(2)} MiB`;
|
||||
}
|
||||
|
||||
function visibleCharacter(character: string) {
|
||||
return character === " "
|
||||
? "␠"
|
||||
: character === "\n"
|
||||
? "↵"
|
||||
: character === "\t"
|
||||
? "⇥"
|
||||
: character;
|
||||
}
|
||||
|
||||
function hex(value: number) {
|
||||
return value.toString(16).toUpperCase().padStart(4, "0");
|
||||
}
|
||||
|
||||
function message(error: unknown) {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
import type { FontInspection, VariableAxis } from "./model";
|
||||
import { extensionFormat } from "./sfnt";
|
||||
|
||||
export interface CssOptions {
|
||||
family: string;
|
||||
sourcePath: string;
|
||||
display: "auto" | "block" | "swap" | "fallback" | "optional";
|
||||
inspection: FontInspection;
|
||||
includeUnicodeRange: boolean;
|
||||
}
|
||||
|
||||
export interface CssResult {
|
||||
css: string;
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
export function generateFontFace(options: CssOptions): CssResult {
|
||||
const family = options.family.trim();
|
||||
if (!family) throw new Error("Font family is required.");
|
||||
if (family.length > 200)
|
||||
throw new Error("Font family exceeds 200 characters.");
|
||||
const sourcePath = validateLocalPath(options.sourcePath),
|
||||
axes = new Map(options.inspection.axes.map((axis) => [axis.tag, axis])),
|
||||
lines = [
|
||||
"@font-face {",
|
||||
` font-family: ${cssString(family)};`,
|
||||
` src: url(${cssString(sourcePath)}) format(${cssString(
|
||||
extensionFormat(
|
||||
options.inspection.fileName,
|
||||
options.inspection.container,
|
||||
),
|
||||
)});`,
|
||||
` font-display: ${options.display};`,
|
||||
` font-weight: ${axisRange(axes.get("wght"), "400")};`,
|
||||
` font-stretch: ${axisRange(axes.get("wdth"), "100", "%")};`,
|
||||
` font-style: ${styleValue(options.inspection, axes)};`,
|
||||
],
|
||||
warnings: string[] = [];
|
||||
if (options.includeUnicodeRange) {
|
||||
if (options.inspection.coverageRangesTruncated) {
|
||||
warnings.push(
|
||||
"unicode-range was omitted because the displayed range inventory is truncated.",
|
||||
);
|
||||
} else if (options.inspection.coverageRanges.length > 128) {
|
||||
warnings.push(
|
||||
"unicode-range was omitted because more than 128 disjoint ranges would make the rule misleadingly large.",
|
||||
);
|
||||
} else if (options.inspection.coverageRanges.length) {
|
||||
const values = options.inspection.coverageRanges.map((range) =>
|
||||
range.start === range.end
|
||||
? `U+${hex(range.start)}`
|
||||
: `U+${hex(range.start)}-${hex(range.end)}`,
|
||||
);
|
||||
lines.push(` unicode-range: ${values.join(", ")};`);
|
||||
}
|
||||
}
|
||||
lines.push("}");
|
||||
if (options.inspection.embedding.level === "restricted")
|
||||
warnings.push(
|
||||
"The font declares restricted embedding. Generating inert text does not grant web-font rights.",
|
||||
);
|
||||
else
|
||||
warnings.push(
|
||||
"Confirm the actual font licence before deploying this @font-face rule.",
|
||||
);
|
||||
return { css: lines.join("\n"), warnings };
|
||||
}
|
||||
|
||||
export function validateLocalPath(value: string) {
|
||||
const path = value.trim();
|
||||
if (!path) throw new Error("A local font asset path is required.");
|
||||
if (path.length > 1_024)
|
||||
throw new Error("Font asset path exceeds 1,024 characters.");
|
||||
if (/^[a-z][a-z\d+.-]*:/iu.test(path) || path.startsWith("//"))
|
||||
throw new Error(
|
||||
"Only relative or root-relative local asset paths are accepted.",
|
||||
);
|
||||
if (/\p{Cc}/u.test(path))
|
||||
throw new Error("Font asset path contains control characters.");
|
||||
return path;
|
||||
}
|
||||
|
||||
function cssString(value: string) {
|
||||
return `"${value
|
||||
.replaceAll("\\", "\\\\")
|
||||
.replaceAll('"', '\\"')
|
||||
.replace(/[\n\r\f]/gu, (character) =>
|
||||
character === "\n" ? "\\a " : character === "\r" ? "\\d " : "\\c ",
|
||||
)}"`;
|
||||
}
|
||||
|
||||
function axisRange(
|
||||
axis: VariableAxis | undefined,
|
||||
fallback: string,
|
||||
suffix = "",
|
||||
) {
|
||||
if (!axis) return fallback + suffix;
|
||||
const minimum = `${trimNumber(axis.min)}${suffix}`,
|
||||
maximum = `${trimNumber(axis.max)}${suffix}`;
|
||||
return minimum === maximum ? minimum : `${minimum} ${maximum}`;
|
||||
}
|
||||
|
||||
function styleValue(
|
||||
inspection: FontInspection,
|
||||
axes: Map<string, VariableAxis>,
|
||||
) {
|
||||
const slant = axes.get("slnt");
|
||||
if (slant)
|
||||
return `oblique ${trimNumber(Math.min(slant.min, slant.max))}deg ${trimNumber(
|
||||
Math.max(slant.min, slant.max),
|
||||
)}deg`;
|
||||
const subfamily = inspection.names.subfamily?.toLowerCase() ?? "";
|
||||
return subfamily.includes("italic") ? "italic" : "normal";
|
||||
}
|
||||
|
||||
function trimNumber(value: number) {
|
||||
return Number(value.toFixed(4)).toString();
|
||||
}
|
||||
|
||||
function hex(value: number) {
|
||||
return value.toString(16).toUpperCase().padStart(4, "0");
|
||||
}
|
||||
|
||||
export function suggestedFamily(inspection: FontInspection) {
|
||||
return (
|
||||
inspection.names.family ||
|
||||
inspection.names.fullName ||
|
||||
inspection.fileName.replace(/\.[^.]+$/u, "") ||
|
||||
"Local font"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,449 @@
|
||||
/// <reference lib="webworker" />
|
||||
import * as opentype from "opentype.js";
|
||||
import type {
|
||||
CoverageBlock,
|
||||
CoverageInspection,
|
||||
CoverageRange,
|
||||
FontInspection,
|
||||
SubsetResult,
|
||||
VariableAxis,
|
||||
WorkerRequest,
|
||||
WorkerResponse,
|
||||
} from "./model";
|
||||
import { decodeEmbedding, FONT_LIMITS, inspectDirectory } from "./sfnt";
|
||||
|
||||
const worker = self as DedicatedWorkerGlobalScope;
|
||||
let font: opentype.Font | null = null,
|
||||
inspection: FontInspection | null = null;
|
||||
|
||||
worker.addEventListener("message", (event: MessageEvent<WorkerRequest>) => {
|
||||
const request = event.data;
|
||||
try {
|
||||
if (request.command === "load") {
|
||||
const result = load(request.buffer, request.fileName, request.fileSize);
|
||||
respond(request.id, result);
|
||||
} else if (request.command === "coverage") {
|
||||
respond(request.id, inspectTextCoverage(request.text));
|
||||
} else {
|
||||
const result = subset(
|
||||
request.text,
|
||||
request.familyName,
|
||||
request.rightsConfirmed,
|
||||
);
|
||||
respond(request.id, result, [result.buffer]);
|
||||
}
|
||||
} catch (error) {
|
||||
const response: WorkerResponse = {
|
||||
id: request.id,
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
worker.postMessage(response);
|
||||
}
|
||||
});
|
||||
|
||||
function respond(id: number, result: unknown, transfer: Transferable[] = []) {
|
||||
const response: WorkerResponse = { id, ok: true, result };
|
||||
worker.postMessage(response, transfer);
|
||||
}
|
||||
|
||||
function load(
|
||||
buffer: ArrayBuffer,
|
||||
fileName: string,
|
||||
fileSize: number,
|
||||
): FontInspection {
|
||||
const directory = inspectDirectory(buffer);
|
||||
if (fileSize !== buffer.byteLength)
|
||||
throw new Error("Transferred font size does not match the selected file.");
|
||||
const parsed = opentype.parse(buffer);
|
||||
if (parsed.glyphs.length > FONT_LIMITS.glyphs)
|
||||
throw new Error(
|
||||
`Font exceeds the ${FONT_LIMITS.glyphs.toLocaleString()}-glyph limit.`,
|
||||
);
|
||||
const unicode = collectUnicode(parsed),
|
||||
ranges = compressRanges([...unicode].sort((a, b) => a - b)),
|
||||
tables = parsed.tables as unknown as Record<string, unknown>,
|
||||
os2 = object(tables.os2),
|
||||
rawFsType = finiteInteger(os2.fsType),
|
||||
axes = readAxes(tables.fvar),
|
||||
names = readNames(parsed.names as unknown as Record<string, unknown>),
|
||||
warnings = [...directory.warnings];
|
||||
if (!directory.tables.some((table) => table.tag === "cmap"))
|
||||
warnings.push("No cmap table is present; Unicode coverage may be empty.");
|
||||
if (!directory.tables.some((table) => table.tag === "name"))
|
||||
warnings.push("No name table is present; identity fields may be empty.");
|
||||
if (directory.tables.some((table) => table.tag === "DSIG"))
|
||||
warnings.push(
|
||||
"A DSIG table is present; this inventory does not validate signatures.",
|
||||
);
|
||||
if (
|
||||
directory.tables.some((table) =>
|
||||
["COLR", "CPAL", "SVG ", "sbix", "CBDT", "CBLC"].includes(table.tag),
|
||||
)
|
||||
)
|
||||
warnings.push(
|
||||
"Colour glyph tables are present; browser preview support varies.",
|
||||
);
|
||||
if (
|
||||
!directory.tables.some((table) =>
|
||||
["glyf", "CFF ", "CFF2"].includes(table.tag),
|
||||
)
|
||||
)
|
||||
warnings.push(
|
||||
"No supported outline table was identified; static subsetting is unavailable.",
|
||||
);
|
||||
const next: FontInspection = {
|
||||
fileName,
|
||||
fileSize,
|
||||
container: directory.container,
|
||||
flavor: directory.flavor,
|
||||
names,
|
||||
unitsPerEm: parsed.unitsPerEm,
|
||||
ascender: parsed.ascender,
|
||||
descender: parsed.descender,
|
||||
glyphCount: parsed.glyphs.length,
|
||||
unicodeCount: unicode.size,
|
||||
coverageRanges: ranges.ranges,
|
||||
coverageRangesTruncated: ranges.truncated,
|
||||
coverageBlocks: coverageBlocks(unicode),
|
||||
axes,
|
||||
embedding: decodeEmbedding(rawFsType),
|
||||
tables: directory.tables,
|
||||
expandedSize: directory.expandedSize,
|
||||
warnings,
|
||||
};
|
||||
font = parsed;
|
||||
inspection = next;
|
||||
return next;
|
||||
}
|
||||
|
||||
function collectUnicode(parsed: opentype.Font) {
|
||||
const values = new Set<number>();
|
||||
let mappings = 0;
|
||||
for (let index = 0; index < parsed.glyphs.length; index += 1) {
|
||||
const glyph = parsed.glyphs.get(index),
|
||||
codes = glyph.unicodes?.length
|
||||
? glyph.unicodes
|
||||
: glyph.unicode === undefined
|
||||
? []
|
||||
: [glyph.unicode];
|
||||
for (const code of codes) {
|
||||
mappings += 1;
|
||||
if (mappings > FONT_LIMITS.unicodeMappings)
|
||||
throw new Error(
|
||||
`Font exceeds the ${FONT_LIMITS.unicodeMappings.toLocaleString()} Unicode-mapping limit.`,
|
||||
);
|
||||
if (Number.isInteger(code) && code >= 0 && code <= 0x10ffff)
|
||||
values.add(code);
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
function compressRanges(sorted: number[]) {
|
||||
const ranges: CoverageRange[] = [];
|
||||
let start: number | undefined,
|
||||
end: number | undefined,
|
||||
truncated = false;
|
||||
for (const value of sorted) {
|
||||
if (start === undefined) start = end = value;
|
||||
else if (value === end! + 1) end = value;
|
||||
else {
|
||||
if (ranges.length === 512) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
ranges.push({ start, end: end! });
|
||||
start = end = value;
|
||||
}
|
||||
}
|
||||
if (!truncated && start !== undefined) ranges.push({ start, end: end! });
|
||||
return { ranges, truncated };
|
||||
}
|
||||
|
||||
const BLOCKS = [
|
||||
["basic-latin", "Basic Latin", 0x0020, 0x007e],
|
||||
["latin-1", "Latin-1 Supplement", 0x00a0, 0x00ff],
|
||||
["latin-ext", "Latin Extended A/B", 0x0100, 0x024f],
|
||||
["greek", "Greek and Coptic", 0x0370, 0x03ff],
|
||||
["cyrillic", "Cyrillic", 0x0400, 0x04ff],
|
||||
["hebrew", "Hebrew", 0x0590, 0x05ff],
|
||||
["arabic", "Arabic", 0x0600, 0x06ff],
|
||||
["devanagari", "Devanagari", 0x0900, 0x097f],
|
||||
["thai", "Thai", 0x0e00, 0x0e7f],
|
||||
["hiragana", "Hiragana", 0x3040, 0x309f],
|
||||
["katakana", "Katakana", 0x30a0, 0x30ff],
|
||||
["cjk", "CJK Unified Ideographs", 0x4e00, 0x9fff],
|
||||
["hangul", "Hangul Syllables", 0xac00, 0xd7af],
|
||||
["symbols", "Miscellaneous Symbols", 0x2600, 0x26ff],
|
||||
["emoji", "Emoji pictographs", 0x1f300, 0x1faff],
|
||||
] as const;
|
||||
|
||||
function coverageBlocks(values: Set<number>): CoverageBlock[] {
|
||||
return BLOCKS.map(([id, label, start, end]) => {
|
||||
let covered = 0;
|
||||
for (let value = start; value <= end; value += 1)
|
||||
if (values.has(value)) covered += 1;
|
||||
return { id, label, covered, total: end - start + 1 };
|
||||
});
|
||||
}
|
||||
|
||||
function readAxes(value: unknown): VariableAxis[] {
|
||||
const fvar = object(value),
|
||||
axes = Array.isArray(fvar.axes) ? fvar.axes : [];
|
||||
if (axes.length > 32)
|
||||
throw new Error("Font exceeds the 32-variable-axis limit.");
|
||||
return axes.flatMap((raw, index) => {
|
||||
const axis = object(raw),
|
||||
tag =
|
||||
typeof axis.tag === "string" ? axis.tag.slice(0, 4) : `axis${index}`,
|
||||
min = finite(axis.minValue),
|
||||
defaultValue = finite(axis.defaultValue),
|
||||
max = finite(axis.maxValue);
|
||||
if (
|
||||
min === null ||
|
||||
defaultValue === null ||
|
||||
max === null ||
|
||||
min > defaultValue ||
|
||||
defaultValue > max
|
||||
)
|
||||
return [];
|
||||
return [
|
||||
{
|
||||
tag,
|
||||
name: localized(axis.name) || tag,
|
||||
min,
|
||||
default: defaultValue,
|
||||
max,
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
function readNames(names: Record<string, unknown>) {
|
||||
const fields: [string, string][] = [
|
||||
["family", "fontFamily"],
|
||||
["subfamily", "fontSubfamily"],
|
||||
["fullName", "fullName"],
|
||||
["postScriptName", "postScriptName"],
|
||||
["version", "version"],
|
||||
["manufacturer", "manufacturer"],
|
||||
["designer", "designer"],
|
||||
["description", "description"],
|
||||
["copyright", "copyright"],
|
||||
["trademark", "trademark"],
|
||||
["license", "license"],
|
||||
["licenseUrl", "licenseURL"],
|
||||
];
|
||||
return Object.fromEntries(
|
||||
fields.flatMap(([output, input]) => {
|
||||
const value = namedValue(names, input);
|
||||
return value ? [[output, value.slice(0, 4_000)]] : [];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function namedValue(names: Record<string, unknown>, field: string) {
|
||||
const direct = localized(names[field]).trim();
|
||||
if (direct) return direct;
|
||||
for (const platform of ["unicode", "windows", "macintosh"]) {
|
||||
const value = localized(object(names[platform])[field]).trim();
|
||||
if (value) return value;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function localized(value: unknown): string {
|
||||
if (typeof value === "string") return value;
|
||||
if (!value || typeof value !== "object") return "";
|
||||
const record = value as Record<string, unknown>,
|
||||
english = record.en;
|
||||
if (typeof english === "string") return english;
|
||||
return (
|
||||
Object.values(record).find(
|
||||
(entry): entry is string => typeof entry === "string",
|
||||
) ?? ""
|
||||
);
|
||||
}
|
||||
|
||||
function inspectTextCoverage(text: string): CoverageInspection {
|
||||
const current = requireFont();
|
||||
if ([...text].length > FONT_LIMITS.previewCharacters)
|
||||
throw new Error("Preview text exceeds 20,000 Unicode characters.");
|
||||
const unique = [...new Set([...text])],
|
||||
truncated = unique.length > 2_048,
|
||||
characters = unique.slice(0, 2_048).map((character) => {
|
||||
const codePoint = character.codePointAt(0)!,
|
||||
glyphIndex = current.charToGlyphIndex(character),
|
||||
glyph = current.glyphs.get(glyphIndex);
|
||||
return {
|
||||
character,
|
||||
codePoint,
|
||||
glyphIndex,
|
||||
glyphName:
|
||||
glyph.name || (glyphIndex === 0 ? ".notdef" : `glyph ${glyphIndex}`),
|
||||
covered: glyphIndex !== 0,
|
||||
};
|
||||
});
|
||||
return {
|
||||
characters,
|
||||
covered: characters.filter((entry) => entry.covered).length,
|
||||
missing: characters.filter((entry) => !entry.covered).length,
|
||||
truncated,
|
||||
};
|
||||
}
|
||||
|
||||
function subset(
|
||||
text: string,
|
||||
familyName: string,
|
||||
rightsConfirmed: boolean,
|
||||
): SubsetResult {
|
||||
const current = requireFont(),
|
||||
report = requireInspection();
|
||||
if (!rightsConfirmed)
|
||||
throw new Error(
|
||||
"Confirm that you have rights to create and use a derivative subset.",
|
||||
);
|
||||
if (!report.embedding.subsetAllowed)
|
||||
throw new Error(
|
||||
`Subsetting is blocked by OS/2 fsType ${report.embedding.rawHex}.`,
|
||||
);
|
||||
if (report.axes.length)
|
||||
throw new Error(
|
||||
"Variable fonts are not flattened or subset in v0.1; use a licensed static instance.",
|
||||
);
|
||||
if (!report.tables.some((table) => ["glyf", "CFF "].includes(table.tag)))
|
||||
throw new Error(
|
||||
"The font has no supported static outline table to subset.",
|
||||
);
|
||||
const characters = [...text];
|
||||
if (!characters.length)
|
||||
throw new Error("Enter at least one character to subset.");
|
||||
if (characters.length > FONT_LIMITS.previewCharacters)
|
||||
throw new Error("Subset text exceeds 20,000 Unicode characters.");
|
||||
const requested = new Set(
|
||||
characters.map((character) => character.codePointAt(0)!),
|
||||
),
|
||||
indexes = new Set<number>([0]);
|
||||
for (const character of characters) {
|
||||
const index = current.charToGlyphIndex(character);
|
||||
if (index !== 0) indexes.add(index);
|
||||
if (indexes.size > FONT_LIMITS.subsetGlyphs)
|
||||
throw new Error(
|
||||
`Subset exceeds the ${FONT_LIMITS.subsetGlyphs.toLocaleString()}-glyph limit.`,
|
||||
);
|
||||
}
|
||||
if (indexes.size === 1)
|
||||
throw new Error("None of the requested characters map to a font glyph.");
|
||||
const glyphs = [...indexes]
|
||||
.sort((a, b) => a - b)
|
||||
.map((index) => cloneGlyph(current.glyphs.get(index), requested));
|
||||
const cleanFamily = familyName.trim().slice(0, 200);
|
||||
if (!cleanFamily) throw new Error("Subset family name is required.");
|
||||
const subsetFont = new opentype.Font({
|
||||
familyName: cleanFamily,
|
||||
styleName: report.names.subfamily || "Regular",
|
||||
unitsPerEm: current.unitsPerEm,
|
||||
ascender: current.ascender,
|
||||
descender: current.descender,
|
||||
glyphs,
|
||||
license: report.names.license,
|
||||
licenseURL: report.names.licenseUrl,
|
||||
copyright: report.names.copyright,
|
||||
trademark: report.names.trademark,
|
||||
manufacturer: report.names.manufacturer,
|
||||
designer: report.names.designer,
|
||||
version: report.names.version,
|
||||
});
|
||||
// opentype.js rebuilds OS/2 from this object. Preserve the machine-readable
|
||||
// embedding/subsetting declaration so a derivative never becomes less
|
||||
// restrictive merely because it passed through this tool.
|
||||
if (report.embedding.raw !== null)
|
||||
(subsetFont.tables.os2 as unknown as Record<string, unknown>).fsType =
|
||||
report.embedding.raw;
|
||||
const buffer = subsetFont.toArrayBuffer();
|
||||
inspectDirectory(buffer);
|
||||
const reparsed = opentype.parse(buffer),
|
||||
outputFsType = finiteInteger(
|
||||
object(object(reparsed.tables as unknown as Record<string, unknown>).os2)
|
||||
.fsType,
|
||||
);
|
||||
if (report.embedding.raw !== null && outputFsType !== report.embedding.raw)
|
||||
throw new Error(
|
||||
"The subset writer did not preserve the source embedding restrictions.",
|
||||
);
|
||||
const losses = [
|
||||
"Rebuilt as a static OpenType outline font; the source container is not preserved.",
|
||||
"Only directly mapped requested Unicode glyphs and .notdef are retained.",
|
||||
"OpenType shaping/positioning, ligatures, kerning, hinting and variation tables are not retained.",
|
||||
"Colour, bitmap, SVG, signature and most source metadata tables are not retained.",
|
||||
"Family/style, readable licence fields, fsType restrictions and basic horizontal metrics are retained; verify rendering in the target software.",
|
||||
"The output is a technical derivative. The source licence still governs use and redistribution.",
|
||||
];
|
||||
return {
|
||||
buffer,
|
||||
fileName: `${safeFileName(cleanFamily)}-subset.otf`,
|
||||
sourceGlyphs: report.glyphCount,
|
||||
subsetGlyphs: glyphs.length,
|
||||
requestedCodePoints: requested.size,
|
||||
losses,
|
||||
};
|
||||
}
|
||||
|
||||
function cloneGlyph(glyph: opentype.Glyph, requested: Set<number>) {
|
||||
const unicodes = (glyph.unicodes ?? []).filter((code) => requested.has(code));
|
||||
if (
|
||||
!unicodes.length &&
|
||||
glyph.unicode !== undefined &&
|
||||
requested.has(glyph.unicode)
|
||||
)
|
||||
unicodes.push(glyph.unicode);
|
||||
return new opentype.Glyph({
|
||||
name: glyph.name ?? undefined,
|
||||
unicode: unicodes[0],
|
||||
unicodes,
|
||||
advanceWidth: glyph.advanceWidth,
|
||||
leftSideBearing: glyph.leftSideBearing,
|
||||
path: glyph.path,
|
||||
});
|
||||
}
|
||||
|
||||
function safeFileName(value: string) {
|
||||
return (
|
||||
value
|
||||
.normalize("NFKD")
|
||||
.replace(/[^\p{Letter}\p{Number}._-]+/gu, "-")
|
||||
.replace(/^-+|-+$/gu, "")
|
||||
.slice(0, 80) || "font"
|
||||
);
|
||||
}
|
||||
|
||||
function requireFont() {
|
||||
if (!font) throw new Error("Load a font first.");
|
||||
return font;
|
||||
}
|
||||
|
||||
function requireInspection() {
|
||||
if (!inspection) throw new Error("Load a font first.");
|
||||
return inspection;
|
||||
}
|
||||
|
||||
function object(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object"
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
|
||||
function finite(value: unknown) {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
||||
}
|
||||
|
||||
function finiteInteger(value: unknown) {
|
||||
const number = finite(value);
|
||||
return number !== null &&
|
||||
Number.isInteger(number) &&
|
||||
number >= 0 &&
|
||||
number <= 0xffff
|
||||
? number
|
||||
: null;
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import type {
|
||||
CoverageInspection,
|
||||
FontInspection,
|
||||
SubsetResult,
|
||||
WorkerRequest,
|
||||
WorkerResponse,
|
||||
} from "./model";
|
||||
import { FONT_LIMITS } from "./sfnt";
|
||||
import FontParserWorker from "./font.worker?worker&inline";
|
||||
|
||||
interface Pending {
|
||||
resolve(value: unknown): void;
|
||||
reject(error: Error): void;
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
type WithoutId<T> = T extends unknown ? Omit<T, "id"> : never;
|
||||
type WorkerCommand = WithoutId<WorkerRequest>;
|
||||
|
||||
export class FontWorkerClient {
|
||||
private readonly worker: Worker;
|
||||
private readonly pending = new Map<number, Pending>();
|
||||
private sequence = 0;
|
||||
private stopped = false;
|
||||
|
||||
constructor() {
|
||||
this.worker = new FontParserWorker({ name: "font-tools-parser" });
|
||||
this.worker.addEventListener(
|
||||
"message",
|
||||
(event: MessageEvent<WorkerResponse>) => {
|
||||
const response = event.data,
|
||||
pending = this.pending.get(response.id);
|
||||
if (!pending) return;
|
||||
clearTimeout(pending.timer);
|
||||
this.pending.delete(response.id);
|
||||
if (response.ok) pending.resolve(response.result);
|
||||
else pending.reject(new Error(response.error));
|
||||
},
|
||||
);
|
||||
this.worker.addEventListener("error", () => {
|
||||
this.failAll(new Error("The isolated font parser stopped unexpectedly."));
|
||||
});
|
||||
this.worker.addEventListener("messageerror", () => {
|
||||
this.failAll(
|
||||
new Error("The isolated font parser returned an unreadable result."),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async load(file: File): Promise<FontInspection> {
|
||||
if (file.size > FONT_LIMITS.fileBytes)
|
||||
throw new Error("Font exceeds the 16 MiB input limit.");
|
||||
const buffer = await file.arrayBuffer();
|
||||
return this.request<FontInspection>(
|
||||
{ command: "load", fileName: file.name, fileSize: file.size, buffer },
|
||||
[buffer],
|
||||
);
|
||||
}
|
||||
|
||||
coverage(text: string) {
|
||||
return this.request<CoverageInspection>({ command: "coverage", text });
|
||||
}
|
||||
|
||||
subset(text: string, familyName: string, rightsConfirmed: boolean) {
|
||||
return this.request<SubsetResult>({
|
||||
command: "subset",
|
||||
text,
|
||||
familyName,
|
||||
rightsConfirmed,
|
||||
});
|
||||
}
|
||||
|
||||
terminate() {
|
||||
if (this.stopped) return;
|
||||
this.stopped = true;
|
||||
this.worker.terminate();
|
||||
this.failAll(new Error("Font operation cancelled."));
|
||||
}
|
||||
|
||||
private request<T>(
|
||||
payload: WorkerCommand,
|
||||
transfer: Transferable[] = [],
|
||||
): Promise<T> {
|
||||
if (this.stopped)
|
||||
return Promise.reject(new Error("Font parser is no longer active."));
|
||||
const id = ++this.sequence,
|
||||
request = { ...payload, id } as WorkerRequest;
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.pending.delete(id);
|
||||
this.terminate();
|
||||
reject(new Error("Font operation exceeded its 8-second safety limit."));
|
||||
}, FONT_LIMITS.operationMilliseconds);
|
||||
this.pending.set(id, {
|
||||
resolve: (value) => resolve(value as T),
|
||||
reject,
|
||||
timer,
|
||||
});
|
||||
this.worker.postMessage(request, transfer);
|
||||
});
|
||||
}
|
||||
|
||||
private failAll(error: Error) {
|
||||
for (const pending of this.pending.values()) {
|
||||
clearTimeout(pending.timer);
|
||||
pending.reject(error);
|
||||
}
|
||||
this.pending.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
export type FontContainer = "truetype" | "opentype-cff" | "woff";
|
||||
|
||||
export interface TableRecord {
|
||||
tag: string;
|
||||
description: string;
|
||||
offset: number;
|
||||
length: number;
|
||||
storedLength: number;
|
||||
checksum: string;
|
||||
compressed: boolean;
|
||||
}
|
||||
|
||||
export interface DirectoryInspection {
|
||||
container: FontContainer;
|
||||
flavor: string;
|
||||
declaredSize: number;
|
||||
expandedSize: number;
|
||||
tables: TableRecord[];
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
export interface VariableAxis {
|
||||
tag: string;
|
||||
name: string;
|
||||
min: number;
|
||||
default: number;
|
||||
max: number;
|
||||
}
|
||||
|
||||
export interface CoverageRange {
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
export interface CoverageBlock {
|
||||
id: string;
|
||||
label: string;
|
||||
covered: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface EmbeddingInfo {
|
||||
raw: number | null;
|
||||
rawHex: string;
|
||||
level:
|
||||
"installable" | "restricted" | "preview-print" | "editable" | "unknown";
|
||||
label: string;
|
||||
noSubsetting: boolean;
|
||||
bitmapOnly: boolean;
|
||||
subsetAllowed: boolean;
|
||||
signals: string[];
|
||||
}
|
||||
|
||||
export interface FontInspection {
|
||||
fileName: string;
|
||||
fileSize: number;
|
||||
container: FontContainer;
|
||||
flavor: string;
|
||||
names: Record<string, string>;
|
||||
unitsPerEm: number;
|
||||
ascender: number;
|
||||
descender: number;
|
||||
glyphCount: number;
|
||||
unicodeCount: number;
|
||||
coverageRanges: CoverageRange[];
|
||||
coverageRangesTruncated: boolean;
|
||||
coverageBlocks: CoverageBlock[];
|
||||
axes: VariableAxis[];
|
||||
embedding: EmbeddingInfo;
|
||||
tables: TableRecord[];
|
||||
expandedSize: number;
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
export interface GlyphCoverage {
|
||||
character: string;
|
||||
codePoint: number;
|
||||
glyphIndex: number;
|
||||
glyphName: string;
|
||||
covered: boolean;
|
||||
}
|
||||
|
||||
export interface CoverageInspection {
|
||||
characters: GlyphCoverage[];
|
||||
covered: number;
|
||||
missing: number;
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
export interface SubsetResult {
|
||||
buffer: ArrayBuffer;
|
||||
fileName: string;
|
||||
sourceGlyphs: number;
|
||||
subsetGlyphs: number;
|
||||
requestedCodePoints: number;
|
||||
losses: string[];
|
||||
}
|
||||
|
||||
export type WorkerRequest =
|
||||
| {
|
||||
id: number;
|
||||
command: "load";
|
||||
fileName: string;
|
||||
fileSize: number;
|
||||
buffer: ArrayBuffer;
|
||||
}
|
||||
| { id: number; command: "coverage"; text: string }
|
||||
| {
|
||||
id: number;
|
||||
command: "subset";
|
||||
text: string;
|
||||
familyName: string;
|
||||
rightsConfirmed: boolean;
|
||||
};
|
||||
|
||||
export type WorkerResponse =
|
||||
| { id: number; ok: true; result: unknown }
|
||||
| { id: number; ok: false; error: string };
|
||||
@@ -0,0 +1,39 @@
|
||||
export function previewDocument(
|
||||
fontUrl: string,
|
||||
text: string,
|
||||
fontSize: number,
|
||||
lineHeight: number,
|
||||
axes: Record<string, number>,
|
||||
) {
|
||||
const safeText = escapeHtml([...text].slice(0, 5_000).join("")),
|
||||
variation = Object.entries(axes)
|
||||
.filter(
|
||||
([tag, value]) =>
|
||||
/^[\x20-\x7e]{1,4}$/u.test(tag) && Number.isFinite(value),
|
||||
)
|
||||
.map(
|
||||
([tag, value]) =>
|
||||
`"${escapeHtml(tag)}" ${Number(value.toFixed(4))}`,
|
||||
)
|
||||
.join(", "),
|
||||
size = Math.min(160, Math.max(12, fontSize)),
|
||||
leading = Math.min(2.5, Math.max(0.8, lineHeight)),
|
||||
url = fontUrl.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
|
||||
return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; font-src blob: data:"><style>
|
||||
@font-face{font-family:FontToolsPreview;src:url("${url}");font-display:block}
|
||||
:root{color-scheme:light dark}body{margin:0;padding:1rem;background:transparent;color:CanvasText;font:14px system-ui,sans-serif}
|
||||
.row{border-bottom:1px solid color-mix(in srgb,CanvasText 18%,transparent);padding:.7rem 0}.row:last-child{border:0}
|
||||
.label{display:block;font:600 11px/1.2 system-ui,sans-serif;letter-spacing:.08em;text-transform:uppercase;opacity:.7;margin-bottom:.35rem}
|
||||
.sample{overflow-wrap:anywhere;font-size:${size}px;line-height:${leading};font-variation-settings:${variation || "normal"}}
|
||||
.loaded{font-family:FontToolsPreview,system-ui,sans-serif}.system{font-family:system-ui,sans-serif}.serif{font-family:serif}.mono{font-family:monospace}
|
||||
</style></head><body><div class="row"><span class="label">Loaded font, then system fallback</span><div class="sample loaded">${safeText}</div></div><div class="row"><span class="label">System sans-serif</span><div class="sample system">${safeText}</div></div><div class="row"><span class="label">System serif</span><div class="sample serif">${safeText}</div></div><div class="row"><span class="label">System monospace</span><div class="sample mono">${safeText}</div></div></body></html>`;
|
||||
}
|
||||
|
||||
function escapeHtml(value: string) {
|
||||
return value
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """)
|
||||
.replaceAll("'", "'");
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
import type {
|
||||
DirectoryInspection,
|
||||
EmbeddingInfo,
|
||||
FontContainer,
|
||||
TableRecord,
|
||||
} from "./model";
|
||||
|
||||
export const FONT_LIMITS = {
|
||||
fileBytes: 16 * 1024 * 1024,
|
||||
expandedBytes: 64 * 1024 * 1024,
|
||||
tableBytes: 32 * 1024 * 1024,
|
||||
tables: 128,
|
||||
glyphs: 65_535,
|
||||
unicodeMappings: 250_000,
|
||||
previewCharacters: 20_000,
|
||||
subsetGlyphs: 1_024,
|
||||
operationMilliseconds: 8_000,
|
||||
} as const;
|
||||
|
||||
const TABLE_DESCRIPTIONS: Record<string, string> = {
|
||||
"CFF ": "Compact Font Format outlines",
|
||||
CFF2: "Compact Font Format 2 outlines",
|
||||
COLR: "Layered colour glyphs",
|
||||
CPAL: "Colour palettes",
|
||||
DSIG: "Digital signature record",
|
||||
GDEF: "Glyph definition data",
|
||||
GPOS: "Glyph positioning",
|
||||
GSUB: "Glyph substitution",
|
||||
HVAR: "Horizontal metric variations",
|
||||
JSTF: "Justification data",
|
||||
MATH: "Mathematical layout",
|
||||
OS2: "OS/2 metrics and embedding flags",
|
||||
"OS/2": "OS/2 metrics and embedding flags",
|
||||
SVG: "SVG glyph documents",
|
||||
SVG_: "SVG glyph documents",
|
||||
avar: "Axis variations",
|
||||
cmap: "Unicode character mapping",
|
||||
cvt: "TrueType control values",
|
||||
"cvt ": "TrueType control values",
|
||||
fpgm: "TrueType font program",
|
||||
fvar: "Variable-font axes",
|
||||
glyf: "TrueType outlines",
|
||||
gasp: "Rasterisation behaviour",
|
||||
gvar: "Glyph variations",
|
||||
head: "Font header",
|
||||
hhea: "Horizontal header",
|
||||
hmtx: "Horizontal metrics",
|
||||
kern: "Legacy kerning",
|
||||
loca: "Glyph locations",
|
||||
maxp: "Maximum profile",
|
||||
meta: "Metadata",
|
||||
name: "Naming records",
|
||||
post: "PostScript data",
|
||||
prep: "TrueType control program",
|
||||
sbix: "Bitmap colour glyphs",
|
||||
stat: "Style attributes",
|
||||
vhea: "Vertical header",
|
||||
vmtx: "Vertical metrics",
|
||||
};
|
||||
|
||||
export function inspectDirectory(buffer: ArrayBuffer): DirectoryInspection {
|
||||
if (buffer.byteLength > FONT_LIMITS.fileBytes)
|
||||
throw new Error("Font exceeds the 16 MiB input limit.");
|
||||
if (buffer.byteLength < 4) throw new Error("File is too short to be a font.");
|
||||
const view = new DataView(buffer),
|
||||
signature = tagAt(view, 0);
|
||||
if (signature === "wOF2")
|
||||
throw new Error(
|
||||
"WOFF2 is recognized but not supported by the local v0.1 parser. Convert it to WOFF, OTF or TTF first.",
|
||||
);
|
||||
if (signature === "ttcf")
|
||||
throw new Error(
|
||||
"TrueType Collections (TTC/OTC) are not supported in v0.1.",
|
||||
);
|
||||
if (signature === "wOFF") return inspectWoff(view);
|
||||
if (
|
||||
signature === "OTTO" ||
|
||||
signature === "true" ||
|
||||
signature === "typ1" ||
|
||||
view.getUint32(0, false) === 0x0001_0000
|
||||
)
|
||||
return inspectSfnt(view, signature);
|
||||
throw new Error(
|
||||
`Unsupported font signature ${displayTag(signature)}; expected TTF, OTF or WOFF.`,
|
||||
);
|
||||
}
|
||||
|
||||
function inspectSfnt(view: DataView, signature: string): DirectoryInspection {
|
||||
requireBytes(view, 0, 12, "SFNT header");
|
||||
const count = view.getUint16(4, false);
|
||||
validateTableCount(count);
|
||||
requireBytes(view, 12, count * 16, "SFNT table directory");
|
||||
const tables: TableRecord[] = [];
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const base = 12 + index * 16,
|
||||
tag = tagAt(view, base),
|
||||
checksum = view.getUint32(base + 4, false),
|
||||
offset = view.getUint32(base + 8, false),
|
||||
length = view.getUint32(base + 12, false);
|
||||
validateTable(view, tag, offset, length, length);
|
||||
tables.push(record(tag, offset, length, length, checksum));
|
||||
}
|
||||
const warnings = directoryWarnings(tables);
|
||||
return {
|
||||
container: signature === "OTTO" ? "opentype-cff" : "truetype",
|
||||
flavor: signature === "OTTO" ? "OpenType/CFF" : "TrueType outlines",
|
||||
declaredSize: view.byteLength,
|
||||
expandedSize: view.byteLength,
|
||||
tables,
|
||||
warnings,
|
||||
};
|
||||
}
|
||||
|
||||
function inspectWoff(view: DataView): DirectoryInspection {
|
||||
requireBytes(view, 0, 44, "WOFF header");
|
||||
const flavorTag = tagAt(view, 4),
|
||||
declaredSize = view.getUint32(8, false),
|
||||
count = view.getUint16(12, false),
|
||||
expandedSize = view.getUint32(16, false);
|
||||
validateTableCount(count);
|
||||
if (declaredSize > view.byteLength)
|
||||
throw new Error("WOFF header declares bytes beyond the file boundary.");
|
||||
if (expandedSize > FONT_LIMITS.expandedBytes)
|
||||
throw new Error("WOFF expanded size exceeds the 64 MiB safety limit.");
|
||||
requireBytes(view, 44, count * 20, "WOFF table directory");
|
||||
validateOptionalBlock(
|
||||
view,
|
||||
view.getUint32(24, false),
|
||||
view.getUint32(28, false),
|
||||
"WOFF metadata",
|
||||
);
|
||||
validateOptionalBlock(
|
||||
view,
|
||||
view.getUint32(36, false),
|
||||
view.getUint32(40, false),
|
||||
"WOFF private data",
|
||||
);
|
||||
const tables: TableRecord[] = [];
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const base = 44 + index * 20,
|
||||
tag = tagAt(view, base),
|
||||
offset = view.getUint32(base + 4, false),
|
||||
storedLength = view.getUint32(base + 8, false),
|
||||
length = view.getUint32(base + 12, false),
|
||||
checksum = view.getUint32(base + 16, false);
|
||||
if (storedLength > length)
|
||||
throw new Error(
|
||||
`WOFF table ${displayTag(tag)} is larger than its original length.`,
|
||||
);
|
||||
if (storedLength > 0 && length / storedLength > 200)
|
||||
throw new Error(
|
||||
`WOFF table ${displayTag(tag)} exceeds the 200:1 expansion-ratio limit.`,
|
||||
);
|
||||
validateTable(view, tag, offset, length, storedLength);
|
||||
tables.push(record(tag, offset, length, storedLength, checksum));
|
||||
}
|
||||
const warnings = directoryWarnings(tables);
|
||||
if (declaredSize !== view.byteLength)
|
||||
warnings.push(
|
||||
`WOFF header length (${declaredSize.toLocaleString()}) differs from the file length (${view.byteLength.toLocaleString()}).`,
|
||||
);
|
||||
return {
|
||||
container: "woff",
|
||||
flavor:
|
||||
flavorTag === "OTTO"
|
||||
? "WOFF with CFF outlines"
|
||||
: "WOFF with TrueType outlines",
|
||||
declaredSize,
|
||||
expandedSize,
|
||||
tables,
|
||||
warnings,
|
||||
};
|
||||
}
|
||||
|
||||
function validateTableCount(count: number) {
|
||||
if (count < 1) throw new Error("The font declares no tables.");
|
||||
if (count > FONT_LIMITS.tables)
|
||||
throw new Error(`The font exceeds the ${FONT_LIMITS.tables}-table limit.`);
|
||||
}
|
||||
|
||||
function validateTable(
|
||||
view: DataView,
|
||||
tag: string,
|
||||
offset: number,
|
||||
length: number,
|
||||
storedLength: number,
|
||||
) {
|
||||
if (!/^[\x20-\x7e]{4}$/u.test(tag))
|
||||
throw new Error("A table has a non-ASCII tag.");
|
||||
if (length > FONT_LIMITS.tableBytes)
|
||||
throw new Error(
|
||||
`Table ${displayTag(tag)} exceeds the 32 MiB expanded-table limit.`,
|
||||
);
|
||||
if (length > 0 && storedLength === 0)
|
||||
throw new Error(`Table ${displayTag(tag)} has an empty stored payload.`);
|
||||
requireBytes(view, offset, storedLength, `table ${displayTag(tag)}`);
|
||||
}
|
||||
|
||||
function validateOptionalBlock(
|
||||
view: DataView,
|
||||
offset: number,
|
||||
length: number,
|
||||
label: string,
|
||||
) {
|
||||
if (offset === 0 && length === 0) return;
|
||||
if (offset === 0 || length === 0)
|
||||
throw new Error(`${label} has an incomplete boundary.`);
|
||||
requireBytes(view, offset, length, label);
|
||||
}
|
||||
|
||||
function requireBytes(
|
||||
view: DataView,
|
||||
offset: number,
|
||||
length: number,
|
||||
label: string,
|
||||
) {
|
||||
if (
|
||||
!Number.isSafeInteger(offset) ||
|
||||
!Number.isSafeInteger(length) ||
|
||||
offset < 0 ||
|
||||
length < 0 ||
|
||||
offset > view.byteLength ||
|
||||
length > view.byteLength - offset
|
||||
)
|
||||
throw new Error(`${label} extends beyond the file boundary.`);
|
||||
}
|
||||
|
||||
function directoryWarnings(tables: TableRecord[]) {
|
||||
const warnings: string[] = [],
|
||||
seen = new Set<string>();
|
||||
for (const table of tables) {
|
||||
if (seen.has(table.tag))
|
||||
warnings.push(`Duplicate ${displayTag(table.tag)} table.`);
|
||||
seen.add(table.tag);
|
||||
if (table.offset % 4 !== 0)
|
||||
warnings.push(`${displayTag(table.tag)} table is not four-byte aligned.`);
|
||||
}
|
||||
const byOffset = [...tables].sort((a, b) => a.offset - b.offset);
|
||||
for (let index = 1; index < byOffset.length; index += 1) {
|
||||
const previous = byOffset[index - 1]!,
|
||||
current = byOffset[index]!;
|
||||
if (previous.offset + previous.storedLength > current.offset)
|
||||
warnings.push(
|
||||
`${displayTag(previous.tag)} and ${displayTag(current.tag)} table payloads overlap.`,
|
||||
);
|
||||
}
|
||||
return warnings;
|
||||
}
|
||||
|
||||
function record(
|
||||
tag: string,
|
||||
offset: number,
|
||||
length: number,
|
||||
storedLength: number,
|
||||
checksum: number,
|
||||
): TableRecord {
|
||||
return {
|
||||
tag,
|
||||
description: TABLE_DESCRIPTIONS[tag] ?? "OpenType table",
|
||||
offset,
|
||||
length,
|
||||
storedLength,
|
||||
checksum: `0x${checksum.toString(16).padStart(8, "0")}`,
|
||||
compressed: storedLength < length,
|
||||
};
|
||||
}
|
||||
|
||||
function tagAt(view: DataView, offset: number) {
|
||||
requireBytes(view, offset, 4, "font signature");
|
||||
return String.fromCharCode(
|
||||
view.getUint8(offset),
|
||||
view.getUint8(offset + 1),
|
||||
view.getUint8(offset + 2),
|
||||
view.getUint8(offset + 3),
|
||||
);
|
||||
}
|
||||
|
||||
function displayTag(tag: string) {
|
||||
return JSON.stringify(tag);
|
||||
}
|
||||
|
||||
export function decodeEmbedding(raw: number | null): EmbeddingInfo {
|
||||
if (raw === null)
|
||||
return {
|
||||
raw,
|
||||
rawHex: "not present",
|
||||
level: "unknown",
|
||||
label: "No OS/2 embedding signal",
|
||||
noSubsetting: false,
|
||||
bitmapOnly: false,
|
||||
subsetAllowed: true,
|
||||
signals: [
|
||||
"The font has no readable OS/2 fsType field; verify its licence manually.",
|
||||
],
|
||||
};
|
||||
const restricted = Boolean(raw & 0x0002),
|
||||
previewPrint = Boolean(raw & 0x0004),
|
||||
editable = Boolean(raw & 0x0008),
|
||||
noSubsetting = Boolean(raw & 0x0100),
|
||||
bitmapOnly = Boolean(raw & 0x0200),
|
||||
level: EmbeddingInfo["level"] = restricted
|
||||
? "restricted"
|
||||
: editable
|
||||
? "editable"
|
||||
: previewPrint
|
||||
? "preview-print"
|
||||
: "installable",
|
||||
label =
|
||||
level === "restricted"
|
||||
? "Restricted licence embedding"
|
||||
: level === "editable"
|
||||
? "Editable embedding"
|
||||
: level === "preview-print"
|
||||
? "Preview & print embedding"
|
||||
: "Installable embedding";
|
||||
const signals = [
|
||||
`${label} is declared by OS/2 fsType.`,
|
||||
noSubsetting
|
||||
? "The no-subsetting bit is set."
|
||||
: "The no-subsetting bit is clear.",
|
||||
bitmapOnly
|
||||
? "Only bitmap embedding is declared; outline export is blocked."
|
||||
: "The bitmap-only bit is clear.",
|
||||
"fsType is a technical signal, not a substitute for the font licence.",
|
||||
];
|
||||
return {
|
||||
raw,
|
||||
rawHex: `0x${raw.toString(16).padStart(4, "0")}`,
|
||||
level,
|
||||
label,
|
||||
noSubsetting,
|
||||
bitmapOnly,
|
||||
subsetAllowed: !restricted && !noSubsetting && !bitmapOnly,
|
||||
signals,
|
||||
};
|
||||
}
|
||||
|
||||
export function extensionFormat(fileName: string, container?: FontContainer) {
|
||||
const extension = fileName.split(".").at(-1)?.toLowerCase();
|
||||
if (extension === "woff" || container === "woff") return "woff";
|
||||
if (extension === "ttf" || container === "truetype") return "truetype";
|
||||
if (extension === "otf" || container === "opentype-cff") return "opentype";
|
||||
return "opentype";
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { App } from "./App";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
|
||||
if ("serviceWorker" in navigator && import.meta.env.PROD) {
|
||||
window.addEventListener("load", () => {
|
||||
const url = new URL("./sw.js", document.baseURI);
|
||||
void navigator.serviceWorker
|
||||
.register(url, { scope: new URL("./", document.baseURI).pathname })
|
||||
.catch(() => undefined);
|
||||
});
|
||||
}
|
||||
+661
@@ -0,0 +1,661 @@
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
font-family:
|
||||
Inter,
|
||||
ui-sans-serif,
|
||||
system-ui,
|
||||
-apple-system,
|
||||
sans-serif;
|
||||
--surface: color-mix(in srgb, Canvas 94%, #d8b4fe 6%);
|
||||
--surface-strong: color-mix(in srgb, Canvas 86%, #c084fc 14%);
|
||||
--line: color-mix(in srgb, CanvasText 18%, transparent);
|
||||
--line-strong: color-mix(in srgb, CanvasText 34%, transparent);
|
||||
--muted: color-mix(in srgb, CanvasText 66%, transparent);
|
||||
--accent: #7e22a8;
|
||||
--accent-ink: #ffffff;
|
||||
--success: #167448;
|
||||
--warning: #b45309;
|
||||
background: Canvas;
|
||||
color: CanvasText;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-width: 320px;
|
||||
}
|
||||
|
||||
button,
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
button,
|
||||
input,
|
||||
select,
|
||||
textarea,
|
||||
.file-button {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 0.68rem;
|
||||
background: Canvas;
|
||||
color: CanvasText;
|
||||
padding: 0.62rem 0.75rem;
|
||||
}
|
||||
|
||||
button,
|
||||
.file-button {
|
||||
min-height: 2.55rem;
|
||||
cursor: pointer;
|
||||
background: var(--surface);
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
button:hover,
|
||||
.file-button:hover {
|
||||
border-color: var(--accent);
|
||||
background: var(--surface-strong);
|
||||
}
|
||||
|
||||
button:disabled,
|
||||
input:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
button:focus-visible,
|
||||
input:focus-visible,
|
||||
select:focus-visible,
|
||||
textarea:focus-visible,
|
||||
summary:focus-visible {
|
||||
outline: 3px solid color-mix(in srgb, var(--accent) 48%, transparent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.toolbox-shell__main {
|
||||
width: min(100%, 90rem);
|
||||
}
|
||||
|
||||
.workbench {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
padding: clamp(0.75rem, 2vw, 1.5rem);
|
||||
}
|
||||
|
||||
.panel {
|
||||
min-width: 0;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 1rem;
|
||||
background: var(--surface);
|
||||
padding: clamp(0.85rem, 2vw, 1.2rem);
|
||||
box-shadow: 0 0.5rem 1.8rem color-mix(in srgb, CanvasText 5%, transparent);
|
||||
}
|
||||
|
||||
.hero,
|
||||
.section-heading,
|
||||
.dialog-heading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.hero {
|
||||
background:
|
||||
radial-gradient(
|
||||
circle at 90% 10%,
|
||||
color-mix(in srgb, #e879f9 24%, transparent),
|
||||
transparent 38%
|
||||
),
|
||||
linear-gradient(135deg, var(--surface), var(--surface-strong));
|
||||
}
|
||||
|
||||
.hero h1 {
|
||||
margin: 0.15rem 0;
|
||||
font-size: clamp(1.75rem, 4vw, 2.8rem);
|
||||
letter-spacing: -0.035em;
|
||||
}
|
||||
|
||||
.hero p:not(.eyebrow) {
|
||||
max-width: 70ch;
|
||||
margin: 0.35rem 0 0;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
margin: 0;
|
||||
color: var(--accent);
|
||||
font-size: 0.7rem;
|
||||
font-weight: 850;
|
||||
letter-spacing: 0.13em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.file-button {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
flex: 0 0 auto;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--accent);
|
||||
color: var(--accent-ink);
|
||||
border-color: var(--accent);
|
||||
padding-inline: 1.1rem;
|
||||
}
|
||||
|
||||
.file-button input {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
clip: rect(0 0 0 0);
|
||||
}
|
||||
|
||||
.status {
|
||||
min-height: 1.5em;
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.empty {
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
gap: 0.5rem;
|
||||
padding-block: clamp(2.5rem, 8vw, 6rem);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.empty h2,
|
||||
.empty p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.empty p {
|
||||
max-width: 62ch;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.drop-icon {
|
||||
display: grid;
|
||||
width: 5rem;
|
||||
height: 5rem;
|
||||
place-items: center;
|
||||
border: 1px solid var(--line-strong);
|
||||
border-radius: 1.25rem;
|
||||
background: Canvas;
|
||||
color: var(--accent);
|
||||
font:
|
||||
800 1.8rem/1 Georgia,
|
||||
serif;
|
||||
transform: rotate(-3deg);
|
||||
}
|
||||
|
||||
.limit-grid,
|
||||
.summary-grid,
|
||||
.two-column,
|
||||
.block-grid {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.limit-grid {
|
||||
width: min(100%, 48rem);
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
margin: 1rem 0 0;
|
||||
}
|
||||
|
||||
.limit-grid div {
|
||||
border-top: 1px solid var(--line);
|
||||
padding-top: 0.7rem;
|
||||
}
|
||||
|
||||
.limit-grid dt {
|
||||
color: var(--muted);
|
||||
font-size: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.limit-grid dd {
|
||||
margin: 0.25rem 0 0;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.summary-grid {
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.summary-card {
|
||||
display: grid;
|
||||
align-content: start;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
|
||||
.summary-card strong {
|
||||
font-size: clamp(1rem, 2vw, 1.18rem);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.summary-card span {
|
||||
color: var(--muted);
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.summary-card.ok {
|
||||
border-top: 3px solid var(--success);
|
||||
}
|
||||
|
||||
.summary-card.warn {
|
||||
border-top: 3px solid var(--warning);
|
||||
}
|
||||
|
||||
.section-heading {
|
||||
margin-bottom: 0.8rem;
|
||||
}
|
||||
|
||||
.section-heading h2 {
|
||||
margin: 0.15rem 0 0;
|
||||
}
|
||||
|
||||
.isolation {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 99rem;
|
||||
padding: 0.35rem 0.65rem;
|
||||
color: var(--muted);
|
||||
font-size: 0.75rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
label {
|
||||
display: grid;
|
||||
gap: 0.35rem;
|
||||
color: var(--muted);
|
||||
font-size: 0.84rem;
|
||||
}
|
||||
|
||||
textarea {
|
||||
min-height: 6rem;
|
||||
resize: vertical;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.preview-controls,
|
||||
.inline-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
flex-wrap: wrap;
|
||||
margin-block: 0.8rem;
|
||||
}
|
||||
|
||||
.preview-controls label {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(8rem, 16rem) 4rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
input[type="range"] {
|
||||
padding: 0;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
|
||||
.axes {
|
||||
display: grid;
|
||||
gap: 0.65rem;
|
||||
margin: 0.8rem 0;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 0.75rem;
|
||||
padding: 0.8rem;
|
||||
}
|
||||
|
||||
.axes legend {
|
||||
color: var(--muted);
|
||||
font-weight: 750;
|
||||
}
|
||||
|
||||
.axes label {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(9rem, 1fr) minmax(10rem, 3fr) 5rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.font-preview-frame {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: clamp(25rem, 48vh, 36rem);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 0.8rem;
|
||||
background: Canvas;
|
||||
}
|
||||
|
||||
.two-column {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.metadata-list {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.metadata-list div {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(8rem, 0.7fr) minmax(0, 1.5fr);
|
||||
gap: 0.75rem;
|
||||
border-top: 1px solid var(--line);
|
||||
padding: 0.55rem 0;
|
||||
}
|
||||
|
||||
.metadata-list div:first-child {
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.metadata-list dt {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.metadata-list dd {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.rights {
|
||||
border-left: 4px solid var(--success);
|
||||
}
|
||||
|
||||
.rights.blocked {
|
||||
border-left-color: var(--warning);
|
||||
}
|
||||
|
||||
.rights-label {
|
||||
font-size: 1.15rem;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.rights li,
|
||||
.loss-report li,
|
||||
.diagnostics li {
|
||||
margin-block: 0.35rem;
|
||||
}
|
||||
|
||||
.license-text {
|
||||
max-height: 12rem;
|
||||
overflow: auto;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 0.7rem;
|
||||
background: Canvas;
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
.license-text p {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.break {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.block-grid {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.coverage-block {
|
||||
display: grid;
|
||||
gap: 0.4rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 0.7rem;
|
||||
background: Canvas;
|
||||
padding: 0.65rem;
|
||||
}
|
||||
|
||||
.coverage-block div {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
.coverage-block span {
|
||||
color: var(--muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
meter {
|
||||
width: 100%;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
|
||||
.coverage-summary {
|
||||
margin: 1rem 0 0.5rem;
|
||||
}
|
||||
|
||||
.glyph-strip {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(4.5rem, 1fr));
|
||||
gap: 0.4rem;
|
||||
max-height: 25rem;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.glyph-strip > span {
|
||||
display: grid;
|
||||
min-height: 4.5rem;
|
||||
place-items: center;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 0.55rem;
|
||||
background: Canvas;
|
||||
padding: 0.3rem;
|
||||
}
|
||||
|
||||
.glyph-strip .missing {
|
||||
border-color: color-mix(in srgb, var(--warning) 65%, var(--line));
|
||||
background: color-mix(in srgb, var(--warning) 8%, Canvas);
|
||||
}
|
||||
|
||||
.glyph-char {
|
||||
font-size: 1.35rem;
|
||||
}
|
||||
|
||||
.glyph-strip small {
|
||||
color: var(--muted);
|
||||
font:
|
||||
0.65rem ui-monospace,
|
||||
monospace;
|
||||
}
|
||||
|
||||
details {
|
||||
margin-top: 1rem;
|
||||
border-top: 1px solid var(--line);
|
||||
padding-top: 0.8rem;
|
||||
}
|
||||
|
||||
summary {
|
||||
cursor: pointer;
|
||||
font-weight: 750;
|
||||
}
|
||||
|
||||
.range-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem;
|
||||
max-height: 16rem;
|
||||
overflow: auto;
|
||||
margin-top: 0.65rem;
|
||||
}
|
||||
|
||||
.range-list code {
|
||||
border-radius: 0.35rem;
|
||||
background: Canvas;
|
||||
padding: 0.25rem 0.4rem;
|
||||
}
|
||||
|
||||
.compact {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(9rem, 18rem);
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.table-scroll {
|
||||
max-height: 35rem;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.84rem;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
max-width: 25rem;
|
||||
border-bottom: 1px solid var(--line);
|
||||
padding: 0.58rem;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
thead th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: var(--surface-strong);
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.diagnostics,
|
||||
.loss-report {
|
||||
margin-top: 0.8rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 0.7rem;
|
||||
padding: 0.8rem;
|
||||
}
|
||||
|
||||
.diagnostics h3,
|
||||
.loss-report h3 {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.output-grid > section {
|
||||
display: grid;
|
||||
align-content: start;
|
||||
gap: 0.7rem;
|
||||
}
|
||||
|
||||
.check {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.55rem;
|
||||
}
|
||||
|
||||
.check input {
|
||||
width: 1.1rem;
|
||||
height: 1.1rem;
|
||||
flex: 0 0 auto;
|
||||
margin-top: 0.1rem;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
|
||||
.code-output {
|
||||
min-height: 14rem;
|
||||
font:
|
||||
0.78rem/1.5 ui-monospace,
|
||||
SFMono-Regular,
|
||||
Consolas,
|
||||
monospace;
|
||||
}
|
||||
|
||||
.primary {
|
||||
background: var(--accent);
|
||||
color: var(--accent-ink);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.block-reason {
|
||||
border-left: 3px solid var(--warning);
|
||||
border-radius: 0.35rem;
|
||||
background: color-mix(in srgb, var(--warning) 9%, Canvas);
|
||||
padding: 0.65rem;
|
||||
}
|
||||
|
||||
.note {
|
||||
margin: 0.5rem 0;
|
||||
color: var(--muted);
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.help-dialog {
|
||||
width: min(44rem, calc(100% - 2rem));
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 1rem;
|
||||
background: Canvas;
|
||||
color: CanvasText;
|
||||
padding: 1.2rem;
|
||||
}
|
||||
|
||||
.help-dialog::backdrop {
|
||||
background: #13091cbb;
|
||||
backdrop-filter: blur(3px);
|
||||
}
|
||||
|
||||
.dialog-heading button {
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.fatal {
|
||||
width: min(100% - 2rem, 50rem);
|
||||
margin: 3rem auto;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 1rem;
|
||||
padding: 1.5rem;
|
||||
}
|
||||
|
||||
@media (max-width: 1000px) {
|
||||
.summary-grid,
|
||||
.block-grid {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.hero,
|
||||
.section-heading {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.summary-grid,
|
||||
.two-column,
|
||||
.block-grid,
|
||||
.limit-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.preview-controls,
|
||||
.inline-controls {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.preview-controls label,
|
||||
.axes label,
|
||||
.compact,
|
||||
.metadata-list div {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.isolation {
|
||||
align-self: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
scroll-behavior: auto !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { afterEach } from "vitest";
|
||||
import { cleanup } from "@testing-library/react";
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
localStorage.clear();
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"$schema": "https://git.add-ideas.de/lotobo/toolbox-sdk/raw/branch/main/schemas/toolbox-app.v1.schema.json",
|
||||
"schemaVersion": 1,
|
||||
"id": "de.add-ideas.font-tools",
|
||||
"name": "Font Tools",
|
||||
"version": "0.1.0",
|
||||
"description": "Inspect and prepare fonts locally.",
|
||||
"entry": "./",
|
||||
"icon": "./favicon.svg",
|
||||
"categories": ["design", "developer"],
|
||||
"tags": ["font", "ttf", "otf", "woff", "glyph", "typography", "subset"],
|
||||
"integration": {
|
||||
"contextVersion": 1,
|
||||
"launchModes": ["navigate", "new-tab"],
|
||||
"embedding": "unsupported"
|
||||
},
|
||||
"requirements": {
|
||||
"secureContext": false,
|
||||
"workers": true,
|
||||
"indexedDb": false,
|
||||
"crossOriginIsolated": false,
|
||||
"topLevelContext": false
|
||||
},
|
||||
"privacy": {
|
||||
"processing": "local",
|
||||
"fileUploads": true,
|
||||
"telemetry": false,
|
||||
"label": "Font files and preview text remain in this browser."
|
||||
},
|
||||
"source": {
|
||||
"repository": "https://git.add-ideas.de/lotobo/font-tools",
|
||||
"license": "GPL-3.0-or-later"
|
||||
},
|
||||
"actions": [
|
||||
{
|
||||
"id": "source",
|
||||
"label": "Source",
|
||||
"url": "https://git.add-ideas.de/lotobo/font-tools"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { defineToolboxApp, parseToolboxApp } from "@add-ideas/toolbox-contract";
|
||||
import source from "./manifest.source.json";
|
||||
|
||||
export const manifest = defineToolboxApp(parseToolboxApp(source));
|
||||
@@ -0,0 +1 @@
|
||||
export const APP_VERSION = "0.1.0";
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,207 @@
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import opentype from "opentype.js";
|
||||
|
||||
const ORIGIN = "http://127.0.0.1:4202";
|
||||
const { Font, Glyph, Path } = opentype;
|
||||
|
||||
test("inspects, compares, covers and subsets a local font", async ({
|
||||
page,
|
||||
}) => {
|
||||
const external = await blockExternal(page);
|
||||
await page.setViewportSize({ width: 1800, height: 1000 });
|
||||
await page.goto("/font/");
|
||||
await expect(page.getByRole("heading", { name: "Font Tools" })).toBeVisible();
|
||||
await page.locator('input[type="file"]').setInputFiles({
|
||||
name: "fixture.otf",
|
||||
mimeType: "font/otf",
|
||||
buffer: fixtureFont(0x0004),
|
||||
});
|
||||
await expect(page.locator('p[role="status"]')).toContainText("Inspected");
|
||||
await expect(
|
||||
page.getByText("Fixture Sans", { exact: true }).first(),
|
||||
).toBeVisible();
|
||||
await expect(page.locator("iframe.font-preview-frame")).toHaveAttribute(
|
||||
"sandbox",
|
||||
"allow-same-origin",
|
||||
);
|
||||
const preview = page.getByLabel("Preview text");
|
||||
await preview.fill("ABZ");
|
||||
await page.getByRole("button", { name: "Analyze preview text" }).click();
|
||||
await expect(page.locator('p[role="status"]')).toContainText(
|
||||
"2 unique characters map to glyphs; 1",
|
||||
);
|
||||
await expect(page.getByLabel("Generated CSS")).toContainText(
|
||||
'font-family: "Fixture Sans"',
|
||||
);
|
||||
await page.getByLabel("Characters to retain").fill("AB");
|
||||
await page.getByLabel(/I have reviewed the actual font licence/u).check();
|
||||
const download = page.waitForEvent("download");
|
||||
await page
|
||||
.getByRole("button", { name: "Build & download .otf subset" })
|
||||
.click();
|
||||
const completedDownload = await download;
|
||||
expect(completedDownload.suggestedFilename()).toBe("Fixture-Sans-subset.otf");
|
||||
const downloadedPath = await completedDownload.path();
|
||||
expect(downloadedPath).not.toBeNull();
|
||||
const downloadedBytes = await readFile(downloadedPath!);
|
||||
const downloadedBuffer = downloadedBytes.buffer.slice(
|
||||
downloadedBytes.byteOffset,
|
||||
downloadedBytes.byteOffset + downloadedBytes.byteLength,
|
||||
),
|
||||
subset = opentype.parse(downloadedBuffer);
|
||||
expect(subset.glyphs.length).toBe(3);
|
||||
expect(subset.tables.os2?.fsType).toBe(0x0004);
|
||||
await expect(
|
||||
page.getByRole("heading", { name: "Last subset loss report" }),
|
||||
).toBeVisible();
|
||||
expect(external).toEqual([]);
|
||||
expect(
|
||||
await page
|
||||
.locator(".toolbox-shell__main")
|
||||
.evaluate((element) => getComputedStyle(element).width),
|
||||
).toBe("1440px");
|
||||
});
|
||||
|
||||
test("enforces the no-subsetting fsType bit", async ({ page }) => {
|
||||
await page.goto("/font/");
|
||||
await page.locator('input[type="file"]').setInputFiles({
|
||||
name: "restricted.otf",
|
||||
mimeType: "font/otf",
|
||||
buffer: fixtureFont(0x0100),
|
||||
});
|
||||
await expect(page.locator('p[role="status"]')).toContainText("Inspected");
|
||||
await expect(
|
||||
page.getByText("0x0100", { exact: false }).first(),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Build & download .otf subset" }),
|
||||
).toBeDisabled();
|
||||
await expect(
|
||||
page.getByText(/declares a restriction that blocks/u),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test("shell, CSP, manifest and nested offline PWA", async ({
|
||||
page,
|
||||
context,
|
||||
request,
|
||||
}) => {
|
||||
await page.goto("/font/");
|
||||
await page.getByRole("button", { name: "Help" }).click();
|
||||
await expect(page.getByRole("dialog")).toContainText("disposable worker");
|
||||
await page.keyboard.press("Escape");
|
||||
await page.getByRole("button", { name: "Personalize" }).click();
|
||||
await page.getByRole("button", { name: "Dark" }).click();
|
||||
await expect(page.locator(".toolbox-shell").first()).toHaveAttribute(
|
||||
"data-toolbox-theme",
|
||||
"dark",
|
||||
);
|
||||
expect(
|
||||
await page.evaluate(async () =>
|
||||
Boolean(await navigator.serviceWorker.ready),
|
||||
),
|
||||
).toBe(true);
|
||||
await context.setOffline(true);
|
||||
await page.reload();
|
||||
await expect(page.getByRole("heading", { name: "Font Tools" })).toBeVisible();
|
||||
await context.setOffline(false);
|
||||
const response = await request.get("/font/");
|
||||
expect(response.headers()["content-security-policy"]).toContain(
|
||||
"connect-src 'self'",
|
||||
);
|
||||
expect(response.headers()["content-security-policy"]).toContain(
|
||||
"font-src 'self' blob: data:",
|
||||
);
|
||||
const manifest = await request.get("/font/toolbox-app.json");
|
||||
await expect(manifest.json()).resolves.toMatchObject({
|
||||
id: "de.add-ideas.font-tools",
|
||||
version: "0.1.0",
|
||||
requirements: { workers: true },
|
||||
});
|
||||
});
|
||||
|
||||
async function blockExternal(page: Page) {
|
||||
const requests: string[] = [];
|
||||
await page.route("**/*", async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.protocol !== "blob:" && url.origin !== ORIGIN) {
|
||||
requests.push(url.href);
|
||||
await route.abort();
|
||||
} else await route.continue();
|
||||
});
|
||||
return requests;
|
||||
}
|
||||
|
||||
function fixtureFont(fsType: number) {
|
||||
const notdef = new Glyph({
|
||||
name: ".notdef",
|
||||
advanceWidth: 600,
|
||||
path: rectanglePath(40, 0, 520, 700),
|
||||
}),
|
||||
space = new Glyph({
|
||||
name: "space",
|
||||
unicode: 32,
|
||||
advanceWidth: 300,
|
||||
path: new Path(),
|
||||
}),
|
||||
a = new Glyph({
|
||||
name: "A",
|
||||
unicode: 65,
|
||||
advanceWidth: 650,
|
||||
path: trianglePath(),
|
||||
}),
|
||||
b = new Glyph({
|
||||
name: "B",
|
||||
unicode: 66,
|
||||
advanceWidth: 650,
|
||||
path: rectanglePath(60, 0, 530, 700),
|
||||
}),
|
||||
font = new Font({
|
||||
familyName: "Fixture Sans",
|
||||
styleName: "Regular",
|
||||
unitsPerEm: 1_000,
|
||||
ascender: 800,
|
||||
descender: -200,
|
||||
glyphs: [notdef, space, a, b],
|
||||
license: "Fixture font for automated local tests only.",
|
||||
version: "Version 1.000",
|
||||
}),
|
||||
bytes = new Uint8Array(font.toArrayBuffer());
|
||||
patchFsType(bytes, fsType);
|
||||
return Buffer.from(bytes);
|
||||
}
|
||||
|
||||
function patchFsType(bytes: Uint8Array, fsType: number) {
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength),
|
||||
count = view.getUint16(4, false);
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const base = 12 + index * 16,
|
||||
tag = String.fromCharCode(...bytes.slice(base, base + 4));
|
||||
if (tag === "OS/2") {
|
||||
const offset = view.getUint32(base + 8, false);
|
||||
view.setUint16(offset + 8, fsType, false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new Error("Generated fixture has no OS/2 table.");
|
||||
}
|
||||
|
||||
function trianglePath() {
|
||||
const path = new Path();
|
||||
path.moveTo(40, 0);
|
||||
path.lineTo(325, 700);
|
||||
path.lineTo(610, 0);
|
||||
path.close();
|
||||
return path;
|
||||
}
|
||||
|
||||
function rectanglePath(x: number, y: number, width: number, height: number) {
|
||||
const path = new Path();
|
||||
path.moveTo(x, y);
|
||||
path.lineTo(x + width, y);
|
||||
path.lineTo(x + width, y + height);
|
||||
path.lineTo(x, y + height);
|
||||
path.close();
|
||||
return path;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { Workbench } from "../../src/components/Workbench";
|
||||
|
||||
vi.mock("../../src/core/fontClient", () => ({
|
||||
FontWorkerClient: class FontWorkerClient {},
|
||||
}));
|
||||
|
||||
describe("Font Workbench", () => {
|
||||
it("presents an actionable local-only empty state", () => {
|
||||
render(<Workbench />);
|
||||
expect(
|
||||
screen.getByRole("heading", { name: "Know what is inside a font." }),
|
||||
).toBeVisible();
|
||||
expect(screen.getByLabelText("Open font")).toHaveAttribute(
|
||||
"accept",
|
||||
expect.stringContaining(".woff2"),
|
||||
);
|
||||
expect(screen.getByText(/Disposable worker/u)).toBeVisible();
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Choose a local");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { generateFontFace, validateLocalPath } from "../../src/core/css";
|
||||
import type { FontInspection } from "../../src/core/model";
|
||||
|
||||
const inspection: FontInspection = {
|
||||
fileName: "Variable.woff",
|
||||
fileSize: 1_000,
|
||||
container: "woff",
|
||||
flavor: "WOFF",
|
||||
names: { family: "Fixture", subfamily: "Regular" },
|
||||
unitsPerEm: 1_000,
|
||||
ascender: 800,
|
||||
descender: -200,
|
||||
glyphCount: 3,
|
||||
unicodeCount: 3,
|
||||
coverageRanges: [{ start: 0x41, end: 0x43 }],
|
||||
coverageRangesTruncated: false,
|
||||
coverageBlocks: [],
|
||||
axes: [{ tag: "wght", name: "Weight", min: 200, default: 400, max: 900 }],
|
||||
embedding: {
|
||||
raw: 0,
|
||||
rawHex: "0x0000",
|
||||
level: "installable",
|
||||
label: "Installable embedding",
|
||||
noSubsetting: false,
|
||||
bitmapOnly: false,
|
||||
subsetAllowed: true,
|
||||
signals: [],
|
||||
},
|
||||
tables: [],
|
||||
expandedSize: 2_000,
|
||||
warnings: [],
|
||||
};
|
||||
|
||||
describe("safe CSS generation", () => {
|
||||
it("quotes metadata, emits axes and a complete compact range", () => {
|
||||
const result = generateFontFace({
|
||||
family: 'Fixture "Local"',
|
||||
sourcePath: "./fonts/fixture.woff",
|
||||
display: "swap",
|
||||
inspection,
|
||||
includeUnicodeRange: true,
|
||||
});
|
||||
expect(result.css).toContain('font-family: "Fixture \\"Local\\""');
|
||||
expect(result.css).toContain("font-weight: 200 900");
|
||||
expect(result.css).toContain("unicode-range: U+0041-0043");
|
||||
});
|
||||
|
||||
it("rejects remote and control-bearing paths", () => {
|
||||
expect(() => validateLocalPath("https://example.test/font.woff")).toThrow(
|
||||
/local asset paths/u,
|
||||
);
|
||||
expect(() => validateLocalPath("./font\n.woff")).toThrow(/control/u);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { previewDocument } from "../../src/core/preview";
|
||||
|
||||
describe("sandbox preview document", () => {
|
||||
it("escapes text and allows no script capability", () => {
|
||||
const html = previewDocument(
|
||||
"blob:http://localhost/fixture",
|
||||
'<script>alert("x")</script>',
|
||||
42,
|
||||
1.2,
|
||||
{ wght: 550 },
|
||||
);
|
||||
expect(html).toContain("<script>");
|
||||
expect(html).not.toContain('<script>alert("x")</script>');
|
||||
expect(html).toContain("default-src 'none'");
|
||||
expect(html).toContain(""wght" 550");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { decodeEmbedding, inspectDirectory } from "../../src/core/sfnt";
|
||||
|
||||
describe("SFNT directory validation", () => {
|
||||
it("inventories bounded TrueType tables", () => {
|
||||
const report = inspectDirectory(sfnt(["head", "cmap", "OS/2"]));
|
||||
expect(report.container).toBe("truetype");
|
||||
expect(report.tables.map((table) => table.tag)).toEqual([
|
||||
"head",
|
||||
"cmap",
|
||||
"OS/2",
|
||||
]);
|
||||
expect(report.tables[2]?.description).toContain("embedding");
|
||||
});
|
||||
|
||||
it("rejects unsupported and out-of-bounds containers before library parsing", () => {
|
||||
expect(() => inspectDirectory(signature("wOF2"))).toThrow(/WOFF2/u);
|
||||
const invalid = sfnt(["head"]),
|
||||
view = new DataView(invalid);
|
||||
view.setUint32(12 + 8, invalid.byteLength - 2, false);
|
||||
view.setUint32(12 + 12, 12, false);
|
||||
expect(() => inspectDirectory(invalid)).toThrow(/file boundary/u);
|
||||
});
|
||||
});
|
||||
|
||||
describe("embedding flags", () => {
|
||||
it("decodes and enforces subsetting restrictions", () => {
|
||||
expect(decodeEmbedding(0).subsetAllowed).toBe(true);
|
||||
expect(decodeEmbedding(0x0002).level).toBe("restricted");
|
||||
expect(decodeEmbedding(0x0100)).toMatchObject({
|
||||
noSubsetting: true,
|
||||
subsetAllowed: false,
|
||||
});
|
||||
expect(decodeEmbedding(0x0208)).toMatchObject({
|
||||
level: "editable",
|
||||
bitmapOnly: true,
|
||||
subsetAllowed: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function signature(value: string) {
|
||||
const bytes = new Uint8Array(4);
|
||||
[...value].forEach(
|
||||
(character, index) => (bytes[index] = character.charCodeAt(0)),
|
||||
);
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
function sfnt(tags: string[]) {
|
||||
const directoryBytes = 12 + tags.length * 16,
|
||||
tableBytes = 12,
|
||||
buffer = new ArrayBuffer(directoryBytes + tags.length * tableBytes),
|
||||
view = new DataView(buffer);
|
||||
view.setUint32(0, 0x0001_0000, false);
|
||||
view.setUint16(4, tags.length, false);
|
||||
tags.forEach((tag, index) => {
|
||||
const base = 12 + index * 16;
|
||||
[...tag].forEach((character, offset) =>
|
||||
view.setUint8(base + offset, character.charCodeAt(0)),
|
||||
);
|
||||
view.setUint32(base + 4, index + 1, false);
|
||||
view.setUint32(base + 8, directoryBytes + index * tableBytes, false);
|
||||
view.setUint32(base + 12, tableBytes, false);
|
||||
});
|
||||
return buffer;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"types": ["vite/client", "node"],
|
||||
"allowArbitraryExtensions": true,
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "Bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"useDefineForClassFields": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true
|
||||
},
|
||||
"include": ["src", "tests"]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.app.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.node.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "Bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true
|
||||
},
|
||||
"include": [
|
||||
"vite.config.ts",
|
||||
"playwright.config.ts",
|
||||
"eslint.config.mjs",
|
||||
"scripts/**/*.mjs"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/// <reference types="vitest/config" />
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
|
||||
export default defineConfig({
|
||||
base: "./",
|
||||
plugins: [react()],
|
||||
test: {
|
||||
environment: "jsdom",
|
||||
setupFiles: "./src/test/setup.ts",
|
||||
css: true,
|
||||
pool: "threads",
|
||||
maxWorkers: 1,
|
||||
restoreMocks: true,
|
||||
exclude: ["tests/browser/**", "node_modules/**", "dist/**"],
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user