Release Data Tools 0.1.0

This commit is contained in:
2026-09-01 02:47:11 +02:00
commit 7ecfecdb2c
66 changed files with 11596 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
node_modules/
dist/
release/*.zip
release/*.zip.sha256
coverage/
playwright-report/
test-results/
*.tsbuildinfo
.DS_Store
+1
View File
@@ -0,0 +1 @@
@add-ideas:registry=https://git.add-ideas.de/api/packages/lotobo/npm/
+11
View File
@@ -0,0 +1,11 @@
# Changelog
## 0.1.0 - 2026-09-01
- Added exact-number JSON, YAML 1.2, TOML, hardened XML, CSV, TSV and NDJSON parsing.
- Added automatic/explicit format selection, diagnostics and bounded source, tree, table and flattened views.
- Added RFC 6901 JSON Pointer and a non-evaluating safe path subset.
- Added formatting and all-format conversion with explicit loss/coercion reports and spreadsheet-safe delimited export.
- Added disposable-worker parsing that retains the last valid view while new input is analysed.
- Added pre-allocation delimited-data limits, bounded query text, broad XInclude namespace rejection and a parser deadline.
- Added Toolbox integration, responsive accessible UI, offline shell and deterministic release packaging.
+3
View File
@@ -0,0 +1,3 @@
# Contributing
Run `npm ci`, `npm run check`, and `npm run test:browser` before proposing a change. Keep processing local, preserve explicit limits, and include fixtures for every parser boundary.
+674
View File
@@ -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>.
+3
View File
@@ -0,0 +1,3 @@
# Licences
The application is GPL-3.0-or-later. Generated release artifacts include an exact runtime dependency licence inventory in `npm-runtime-licenses.txt`.
+50
View File
@@ -0,0 +1,50 @@
# Data Tools
Inspect, format, query, flatten and convert structured data locally in the browser. Data Tools is a standalone application in the [add·ideas Toolbox](https://git.add-ideas.de/lotobo/toolbox-portal); input text and files never leave the current browser.
## Version 0.1.0
- Detect or explicitly select JSON, YAML 1.2, TOML, XML, CSV, TSV and NDJSON.
- Keep JSON integer and decimal lexemes exact, including values beyond IEEE-754 range.
- Inspect a bounded typed tree, a tabular projection and flattened scalar leaves.
- Query with RFC 6901 JSON Pointer or a deliberately small, non-evaluating path subset.
- Format and convert between every supported output with a visible loss/coercion report.
- Export CSV/TSV with opt-in spreadsheet formula neutralisation, enabled by default.
- Open UTF-8 files or edit text directly; parsing runs in a disposable module worker and the previous valid result remains visible while a replacement is analysed.
### Format semantics
| Format | v0.1 behaviour |
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| JSON | Duplicate keys and prototype-affecting keys are rejected. Number lexemes are stored and emitted exactly. |
| YAML | YAML 1.2 core schema, unique string keys, BigInt integers, maximum 50 alias expansions. Custom tags and merge keys are rejected. |
| TOML | Integers are BigInt-backed and dates/times retain their TOML kind. Floats use the browser's binary representation and are diagnosed. |
| XML | `DOCTYPE`, entity declarations and XInclude are rejected before inert parsing. Elements, namespaces, attributes, text, CDATA, comments and processing instructions use an explicit ordered record model. |
| CSV / TSV | Fields remain strings. Quoting and line endings are parsed without dynamic typing. The first row can be used as table headings. |
| NDJSON | Every non-empty line is parsed as lossless JSON. Blank lines and the exact failing line are reported. |
The safe path subset supports `$`, `.key`, `['key']`, `[index]` and `[*]`. It intentionally has no recursive descent, filters, expressions, functions or script evaluation.
### Resource limits
The current production limits are 16 MiB of UTF-8 input, 8 million JavaScript characters, 100,000 model nodes, depth 128, 50,000 delimited rows, 2,000 columns, 250,000 cells, 1 million characters per field, 4,096 query characters, 1,000 query matches and 16 million generated characters. Disposable parses have a 30-second deadline. UI previews are smaller than the model and state when they are truncated.
See [Architecture](docs/ARCHITECTURE.md), [Privacy and security](docs/PRIVACY-SECURITY.md) and [Accessibility](docs/ACCESSIBILITY.md) for the design and threat model.
## Development
Requires Node.js 22 and npm 11.
```sh
npm ci
npm run check
npm run test:browser
```
## Release
`npm run release:artifact` creates a deterministic `release/data-tools-0.1.0.zip` and checksum sidecar.
## Licence
GPL-3.0-or-later. Runtime dependencies retain their own licences; see [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
+3
View File
@@ -0,0 +1,3 @@
# Security
Please report vulnerabilities privately to the repository owner. Do not attach sensitive source files to public issues. Imported inputs are untrusted; parsers must remain bounded and must not execute active content or fetch external resources.
+7
View File
@@ -0,0 +1,7 @@
# Corresponding source
The corresponding source for Data Tools 0.1.0 is available at:
https://git.add-ideas.de/lotobo/data-tools/src/tag/v0.1.0
Build with Node.js 22, npm 11, `npm ci`, and `npm run release:artifact`.
+13
View File
@@ -0,0 +1,13 @@
# Third-party notices
Data Tools is GPL-3.0-or-later. Runtime dependencies retain their own licences:
- add·ideas Toolbox contract and React shell 0.2.3 — Apache-2.0
- React and React DOM 19.2.8 — MIT
- lossless-json 4.3.1 — MIT
- yaml 2.9.0 — ISC
- smol-toml 1.8.0 — BSD-3-Clause
- @xmldom/xmldom 0.9.12 — MIT
- Papa Parse 5.7.0 — MIT
Release preparation reproduces the licence texts and exact installed versions in `LICENSES/npm-runtime-licenses.txt`. Development-only packages are not shipped in the application bundle.
+7
View File
@@ -0,0 +1,7 @@
# Accessibility
The workbench uses semantic landmarks, ordered headings, labelled native controls and a real ARIA tab list. Left/Right, Home and End move between views. File selection, format selection, analysis, formatting, querying, copy and download are keyboard operable.
Parser and action state use polite live regions. Errors include text labels and codes rather than relying on colour. Tree rows expose `treeitem` levels, tables have captions and keyboard-scrollable regions, and truncated previews state what was omitted. Visible focus, reduced-motion preferences, responsive layouts and Toolbox system/light/dark themes are supported.
Large source and output areas remain native textareas so browser selection, zoom, high-contrast settings and assistive-technology editing conventions continue to work.
+23
View File
@@ -0,0 +1,23 @@
# Architecture
Data Tools is a relocatable static React application. There is no application server and no runtime API.
## Pipeline
1. The UI checks the local file size before decoding and passes text, the selected format and the optional filename to a fresh module worker.
2. The worker applies byte/character and structural preflight limits, including a streaming dimension pass before delimited parsing, then parses with format-specific defensive options and converts the result into a serialisable typed node model.
3. The model is measured again for node count and depth before it is returned. A newer request terminates the older worker, and a 30-second deadline terminates a stalled parse. The UI retains the last successful model until a new one is ready.
4. Tree, table, flattened and query projections operate on the model with their own preview/result caps.
5. Serialisers create a new string and a structured list of notices, coercions and losses. Output is capped before it reaches copy or download actions.
The node model has explicit null, boolean, string, number, date, array and ordered-object variants. Number nodes retain a source representation (`exact`, `bigint` or `binary`) and an exact display lexeme. Objects use ordered entry arrays rather than assigning untrusted keys to ordinary JavaScript objects.
XML deliberately does not pretend to be a JSON object. It is represented as explicit element records containing qualified name, namespace URI, attributes and ordered child records. Converting XML to another syntax therefore exposes this model and reports the convention.
## Parsers
Runtime versions are pinned exactly: `lossless-json` 4.3.1, `yaml` 2.9.0, `smol-toml` 1.8.0, `@xmldom/xmldom` 0.9.12 and `papaparse` 5.7.0. No imported value is rendered as HTML or executed.
Version 0.1 keeps its bounded data-model functions as pure app modules rather
than introducing a runtime helper dependency. They are intentionally shaped
for later replacement by the shared limits and download APIs.
+21
View File
@@ -0,0 +1,21 @@
# Privacy and security
## Data flow
Input files are read with the browser File API and decoded as UTF-8. Text is copied to a same-origin worker for parsing and returned as a structured-cloneable model. There is no upload endpoint, account, telemetry, analytics, persistence or content fetch. The service worker only caches the application shell.
## Untrusted input controls
- Input, model, structural depth, delimited cells, query text/results, previews
and output have fixed limits. Delimited dimensions are scanned before the
third-party parser allocates a table, and disposable parses have a 30-second
deadline.
- JSON duplicate keys and the keys `__proto__`, `constructor` and `prototype` are rejected.
- YAML uses the 1.2 core schema with unique string keys, no custom tags or merge keys, and a bounded alias count.
- XML rejects `DOCTYPE`, entity declarations and XInclude before parsing. The parser is not used to load external resources, and imported markup is never inserted into the DOM.
- CSV/TSV dynamic typing is disabled. Spreadsheet-safe export prefixes cells beginning with `=`, `+`, `-`, `@`, tab or carriage return; disabling it produces a warning in the conversion report.
- The safe query language has no evaluator, functions, filters, recursive descent or scripts.
Conversion is not sanitisation. XML-to-object conventions, typed-scalar coercions, nested CSV cell encoding, TOML null handling and unsafe numeric conversions are reported alongside the generated result. Users should inspect that report before relying on converted output.
The browser still receives normal application assets from its configured origin. A deployment should retain the supplied restrictive CSP, same-origin worker policy, `nosniff`, no-referrer policy and immutable caching for fingerprinted assets.
+37
View File
@@ -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
View File
@@ -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="description"
content="Inspect, query and convert structured data locally in the browser."
/>
<link rel="icon" type="image/svg+xml" href="./favicon.svg" />
<link rel="manifest" href="./manifest.webmanifest" />
<meta name="theme-color" content="#29255f" />
<title>Data Tools</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./src/main.tsx"></script>
</body>
</html>
+4036
View File
File diff suppressed because it is too large Load Diff
+76
View File
@@ -0,0 +1,76 @@
{
"name": "data-tools",
"version": "0.1.0",
"description": "Inspect, query and convert structured data locally in the browser.",
"license": "GPL-3.0-or-later",
"author": "Albrecht Degering",
"repository": {
"type": "git",
"url": "git+https://git.add-ideas.de/lotobo/data-tools.git"
},
"homepage": "https://git.add-ideas.de/lotobo/data-tools",
"bugs": {
"url": "https://git.add-ideas.de/lotobo/data-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-shell-react": "0.2.3",
"@xmldom/xmldom": "0.9.12",
"lossless-json": "4.3.1",
"papaparse": "5.7.0",
"react": "19.2.8",
"react-dom": "19.2.8",
"smol-toml": "1.8.0",
"yaml": "2.9.0"
},
"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/papaparse": "5.5.2",
"@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"
}
+21
View File
@@ -0,0 +1,21 @@
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "./tests/browser",
fullyParallel: false,
workers: 1,
timeout: 120_000,
expect: { timeout: 10_000 },
reporter: [["list"]],
use: { baseURL: "http://127.0.0.1:4173", trace: "retain-on-failure" },
webServer: {
command: "npm run build && node scripts/serve-test.mjs",
url: "http://127.0.0.1:4173",
reuseExistingServer: !process.env.CI,
timeout: 180_000,
},
projects: [
{ name: "chromium", use: { ...devices["Desktop Chrome"] } },
{ name: "firefox", use: { ...devices["Desktop Firefox"] } },
],
});
+11
View File
@@ -0,0 +1,11 @@
# Changelog
## 0.1.0 - 2026-09-01
- Added exact-number JSON, YAML 1.2, TOML, hardened XML, CSV, TSV and NDJSON parsing.
- Added automatic/explicit format selection, diagnostics and bounded source, tree, table and flattened views.
- Added RFC 6901 JSON Pointer and a non-evaluating safe path subset.
- Added formatting and all-format conversion with explicit loss/coercion reports and spreadsheet-safe delimited export.
- Added disposable-worker parsing that retains the last valid view while new input is analysed.
- Added pre-allocation delimited-data limits, bounded query text, broad XInclude namespace rejection and a parser deadline.
- Added Toolbox integration, responsive accessible UI, offline shell and deterministic release packaging.
+3
View File
@@ -0,0 +1,3 @@
# Contributing
Run `npm ci`, `npm run check`, and `npm run test:browser` before proposing a change. Keep processing local, preserve explicit limits, and include fixtures for every parser boundary.
+674
View File
@@ -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>.
+3
View File
@@ -0,0 +1,3 @@
# Licences
The application is GPL-3.0-or-later. Generated release artifacts include an exact runtime dependency licence inventory in `npm-runtime-licenses.txt`.
+589
View File
@@ -0,0 +1,589 @@
==============================================================================
@add-ideas/toolbox-contract@0.2.3
Declared licence: Apache-2.0
==============================================================================
--- LICENSE ---
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
Copyright 2026 ADD Ideas
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================
@add-ideas/toolbox-shell-react@0.2.3
Declared licence: Apache-2.0
==============================================================================
--- LICENSE ---
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
Copyright 2026 ADD Ideas
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================
@xmldom/xmldom@0.9.12
Declared licence: MIT
==============================================================================
--- LICENSE ---
Copyright 2019 - present Christopher J. Brody and other contributors, as listed in: https://github.com/xmldom/xmldom/graphs/contributors
Copyright 2012 - 2017 @jindw <jindw@xidea.org> and other contributors, as listed in: https://github.com/jindw/xmldom/graphs/contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
==============================================================================
lossless-json@4.3.1
Declared licence: MIT
==============================================================================
--- LICENSE.md ---
The MIT License (MIT)
Copyright (c) 2016-2026 Jos de Jong
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
==============================================================================
papaparse@5.7.0
Declared licence: MIT
==============================================================================
--- LICENSE ---
The MIT License (MIT)
Copyright (c) 2015 Matthew Holt
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
==============================================================================
react@19.2.8
Declared licence: MIT
==============================================================================
--- LICENSE ---
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
==============================================================================
react-dom@19.2.8
Declared licence: MIT
==============================================================================
--- LICENSE ---
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
==============================================================================
scheduler@0.27.0
Declared licence: MIT
==============================================================================
--- LICENSE ---
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
==============================================================================
smol-toml@1.8.0
Declared licence: BSD-3-Clause
==============================================================================
--- LICENSE ---
Copyright (c) Squirrel Chat et al., All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
==============================================================================
yaml@2.9.0
Declared licence: ISC
==============================================================================
--- LICENSE ---
Copyright Eemeli Aro <eemeli@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright notice
and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
+50
View File
@@ -0,0 +1,50 @@
# Data Tools
Inspect, format, query, flatten and convert structured data locally in the browser. Data Tools is a standalone application in the [add·ideas Toolbox](https://git.add-ideas.de/lotobo/toolbox-portal); input text and files never leave the current browser.
## Version 0.1.0
- Detect or explicitly select JSON, YAML 1.2, TOML, XML, CSV, TSV and NDJSON.
- Keep JSON integer and decimal lexemes exact, including values beyond IEEE-754 range.
- Inspect a bounded typed tree, a tabular projection and flattened scalar leaves.
- Query with RFC 6901 JSON Pointer or a deliberately small, non-evaluating path subset.
- Format and convert between every supported output with a visible loss/coercion report.
- Export CSV/TSV with opt-in spreadsheet formula neutralisation, enabled by default.
- Open UTF-8 files or edit text directly; parsing runs in a disposable module worker and the previous valid result remains visible while a replacement is analysed.
### Format semantics
| Format | v0.1 behaviour |
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| JSON | Duplicate keys and prototype-affecting keys are rejected. Number lexemes are stored and emitted exactly. |
| YAML | YAML 1.2 core schema, unique string keys, BigInt integers, maximum 50 alias expansions. Custom tags and merge keys are rejected. |
| TOML | Integers are BigInt-backed and dates/times retain their TOML kind. Floats use the browser's binary representation and are diagnosed. |
| XML | `DOCTYPE`, entity declarations and XInclude are rejected before inert parsing. Elements, namespaces, attributes, text, CDATA, comments and processing instructions use an explicit ordered record model. |
| CSV / TSV | Fields remain strings. Quoting and line endings are parsed without dynamic typing. The first row can be used as table headings. |
| NDJSON | Every non-empty line is parsed as lossless JSON. Blank lines and the exact failing line are reported. |
The safe path subset supports `$`, `.key`, `['key']`, `[index]` and `[*]`. It intentionally has no recursive descent, filters, expressions, functions or script evaluation.
### Resource limits
The current production limits are 16 MiB of UTF-8 input, 8 million JavaScript characters, 100,000 model nodes, depth 128, 50,000 delimited rows, 2,000 columns, 250,000 cells, 1 million characters per field, 4,096 query characters, 1,000 query matches and 16 million generated characters. Disposable parses have a 30-second deadline. UI previews are smaller than the model and state when they are truncated.
See [Architecture](docs/ARCHITECTURE.md), [Privacy and security](docs/PRIVACY-SECURITY.md) and [Accessibility](docs/ACCESSIBILITY.md) for the design and threat model.
## Development
Requires Node.js 22 and npm 11.
```sh
npm ci
npm run check
npm run test:browser
```
## Release
`npm run release:artifact` creates a deterministic `release/data-tools-0.1.0.zip` and checksum sidecar.
## Licence
GPL-3.0-or-later. Runtime dependencies retain their own licences; see [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
+3
View File
@@ -0,0 +1,3 @@
# Security
Please report vulnerabilities privately to the repository owner. Do not attach sensitive source files to public issues. Imported inputs are untrusted; parsers must remain bounded and must not execute active content or fetch external resources.
+7
View File
@@ -0,0 +1,7 @@
# Corresponding source
The corresponding source for Data Tools 0.1.0 is available at:
https://git.add-ideas.de/lotobo/data-tools/src/tag/v0.1.0
Build with Node.js 22, npm 11, `npm ci`, and `npm run release:artifact`.
+13
View File
@@ -0,0 +1,13 @@
# Third-party notices
Data Tools is GPL-3.0-or-later. Runtime dependencies retain their own licences:
- add·ideas Toolbox contract and React shell 0.2.3 — Apache-2.0
- React and React DOM 19.2.8 — MIT
- lossless-json 4.3.1 — MIT
- yaml 2.9.0 — ISC
- smol-toml 1.8.0 — BSD-3-Clause
- @xmldom/xmldom 0.9.12 — MIT
- Papa Parse 5.7.0 — MIT
Release preparation reproduces the licence texts and exact installed versions in `LICENSES/npm-runtime-licenses.txt`. Development-only packages are not shipped in the application bundle.
+7
View File
@@ -0,0 +1,7 @@
# Accessibility
The workbench uses semantic landmarks, ordered headings, labelled native controls and a real ARIA tab list. Left/Right, Home and End move between views. File selection, format selection, analysis, formatting, querying, copy and download are keyboard operable.
Parser and action state use polite live regions. Errors include text labels and codes rather than relying on colour. Tree rows expose `treeitem` levels, tables have captions and keyboard-scrollable regions, and truncated previews state what was omitted. Visible focus, reduced-motion preferences, responsive layouts and Toolbox system/light/dark themes are supported.
Large source and output areas remain native textareas so browser selection, zoom, high-contrast settings and assistive-technology editing conventions continue to work.
+23
View File
@@ -0,0 +1,23 @@
# Architecture
Data Tools is a relocatable static React application. There is no application server and no runtime API.
## Pipeline
1. The UI checks the local file size before decoding and passes text, the selected format and the optional filename to a fresh module worker.
2. The worker applies byte/character and structural preflight limits, including a streaming dimension pass before delimited parsing, then parses with format-specific defensive options and converts the result into a serialisable typed node model.
3. The model is measured again for node count and depth before it is returned. A newer request terminates the older worker, and a 30-second deadline terminates a stalled parse. The UI retains the last successful model until a new one is ready.
4. Tree, table, flattened and query projections operate on the model with their own preview/result caps.
5. Serialisers create a new string and a structured list of notices, coercions and losses. Output is capped before it reaches copy or download actions.
The node model has explicit null, boolean, string, number, date, array and ordered-object variants. Number nodes retain a source representation (`exact`, `bigint` or `binary`) and an exact display lexeme. Objects use ordered entry arrays rather than assigning untrusted keys to ordinary JavaScript objects.
XML deliberately does not pretend to be a JSON object. It is represented as explicit element records containing qualified name, namespace URI, attributes and ordered child records. Converting XML to another syntax therefore exposes this model and reports the convention.
## Parsers
Runtime versions are pinned exactly: `lossless-json` 4.3.1, `yaml` 2.9.0, `smol-toml` 1.8.0, `@xmldom/xmldom` 0.9.12 and `papaparse` 5.7.0. No imported value is rendered as HTML or executed.
Version 0.1 keeps its bounded data-model functions as pure app modules rather
than introducing a runtime helper dependency. They are intentionally shaped
for later replacement by the shared limits and download APIs.
+21
View File
@@ -0,0 +1,21 @@
# Privacy and security
## Data flow
Input files are read with the browser File API and decoded as UTF-8. Text is copied to a same-origin worker for parsing and returned as a structured-cloneable model. There is no upload endpoint, account, telemetry, analytics, persistence or content fetch. The service worker only caches the application shell.
## Untrusted input controls
- Input, model, structural depth, delimited cells, query text/results, previews
and output have fixed limits. Delimited dimensions are scanned before the
third-party parser allocates a table, and disposable parses have a 30-second
deadline.
- JSON duplicate keys and the keys `__proto__`, `constructor` and `prototype` are rejected.
- YAML uses the 1.2 core schema with unique string keys, no custom tags or merge keys, and a bounded alias count.
- XML rejects `DOCTYPE`, entity declarations and XInclude before parsing. The parser is not used to load external resources, and imported markup is never inserted into the DOM.
- CSV/TSV dynamic typing is disabled. Spreadsheet-safe export prefixes cells beginning with `=`, `+`, `-`, `@`, tab or carriage return; disabling it produces a warning in the conversion report.
- The safe query language has no evaluator, functions, filters, recursive descent or scripts.
Conversion is not sanitisation. XML-to-object conventions, typed-scalar coercions, nested CSV cell encoding, TOML null handling and unsafe numeric conversions are reported alongside the generated result. Users should inspect that report before relying on converted output.
The browser still receives normal application assets from its configured origin. A deployment should retain the supplied restrictive CSP, same-origin worker policy, `nosniff`, no-referrer policy and immutable caching for fingerprinted assets.
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Data Tools"><path fill="#5b4ec4" d="M11 4h30l12 12v44H11z"/><path fill="#fff" opacity=".28" d="M41 4v14h12"/><text x="32" y="43" fill="#fff" font-family="system-ui,sans-serif" font-size="18" font-weight="800" text-anchor="middle">DA</text></svg>

After

Width:  |  Height:  |  Size: 329 B

+18
View File
@@ -0,0 +1,18 @@
{
"name": "Data Tools",
"short_name": "Data",
"description": "Inspect, query and convert structured data locally in the browser.",
"start_url": "./",
"scope": "./",
"display": "standalone",
"background_color": "#f6f7fb",
"theme_color": "#29255f",
"icons": [
{
"src": "./favicon.svg",
"sizes": "any",
"type": "image/svg+xml",
"purpose": "any maskable"
}
]
}
+54
View File
@@ -0,0 +1,54 @@
const CACHE_PREFIX = "data-tools-shell-";
const CACHE_NAME = CACHE_PREFIX + "0.1.0";
const CORE = ["./", "./manifest.webmanifest", "./favicon.svg"];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then(async (cache) => {
await cache.addAll(CORE);
const html = await (await fetch("./")).text();
const assets = [...html.matchAll(/(?:src|href)="(\.\/assets\/[^"]+)"/g)]
.map((match) => match[1])
.filter(Boolean);
await cache.addAll(assets);
}),
);
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches
.keys()
.then((keys) =>
Promise.all(
keys
.filter((key) => key.startsWith(CACHE_PREFIX) && key !== CACHE_NAME)
.map((key) => caches.delete(key)),
),
)
.then(() => self.clients.claim()),
);
});
self.addEventListener("fetch", (event) => {
if (event.request.method !== "GET") return;
const url = new URL(event.request.url);
if (
url.origin !== self.location.origin ||
!url.pathname.startsWith(new URL(self.registration.scope).pathname)
)
return;
event.respondWith(
caches.match(event.request).then(
(cached) =>
cached ??
fetch(event.request).then((response) => {
if (response.ok) {
const copy = response.clone();
void caches
.open(CACHE_NAME)
.then((cache) => cache.put(event.request, copy));
}
return response;
}),
),
);
});
+41
View File
@@ -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.data-tools",
"name": "Data Tools",
"version": "0.1.0",
"description": "Inspect, query and convert structured data locally in the browser.",
"entry": "./",
"icon": "./favicon.svg",
"categories": ["data", "developer", "documents"],
"tags": ["json", "yaml", "toml", "xml", "csv", "tsv", "ndjson"],
"integration": {
"contextVersion": 1,
"launchModes": ["navigate", "new-tab"],
"embedding": "unsupported"
},
"requirements": {
"secureContext": false,
"workers": true,
"indexedDb": false,
"crossOriginIsolated": false,
"topLevelContext": false
},
"privacy": {
"processing": "local",
"fileUploads": false,
"telemetry": false,
"label": "Inputs stay in this browser; nothing is uploaded."
},
"source": {
"repository": "https://git.add-ideas.de/lotobo/data-tools",
"license": "GPL-3.0-or-later"
},
"actions": [
{
"id": "source",
"label": "Source",
"url": "https://git.add-ideas.de/lotobo/data-tools"
}
]
}
+33
View File
@@ -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");
}
+165
View File
@@ -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 });
}
+70
View File
@@ -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");
+69
View File
@@ -0,0 +1,69 @@
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",
);
const prefix = "/deep/nested/data/";
const 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"],
[".wasm", "application/wasm"],
[".png", "image/png"],
[".jpg", "image/jpeg"],
[".webp", "image/webp"],
]);
const headers = {
"Content-Security-Policy":
"default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; worker-src 'self' blob:; manifest-src 'self'",
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Resource-Policy": "same-origin",
"Permissions-Policy":
"camera=(), microphone=(), geolocation=(), usb=(), payment=()",
"Referrer-Policy": "no-referrer",
"X-Content-Type-Options": "nosniff",
};
const server = createServer(async (request, response) => {
try {
const url = new URL(request.url ?? "/", "http://127.0.0.1");
const relative = decodeURIComponent(url.pathname).startsWith(prefix)
? decodeURIComponent(url.pathname).slice(prefix.length)
: decodeURIComponent(url.pathname).replace(/^\/+/, "");
const normalized = path.posix.normalize(relative || "index.html");
if (
normalized === ".." ||
normalized.startsWith("../") ||
path.isAbsolute(normalized)
) {
response.writeHead(400).end("Bad request");
return;
}
let file = path.join(root, normalized);
if ((await stat(file).catch(() => null))?.isDirectory())
file = path.join(file, "index.html");
const content = await readFile(file);
const cacheControl = normalized.startsWith("assets/")
? "public, max-age=31536000, immutable"
: "no-cache";
response.writeHead(200, {
"Content-Type":
types.get(path.extname(file)) ?? "application/octet-stream",
"Cache-Control": cacheControl,
...headers,
});
response.end(content);
} catch {
response.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
response.end("Not found");
}
});
server.listen(4173, "127.0.0.1", () => console.log("Test server ready"));
+35
View File
@@ -0,0 +1,35 @@
import { lazy, Suspense, 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 { manifest } from "./toolbox/manifest";
const Workbench = lazy(async () => ({
default: (await import("./components/Workbench")).Workbench,
}));
export function App() {
const [helpOpen, setHelpOpen] = useState(false);
return (
<ErrorBoundary>
<AppShell
app={manifest}
manifestUrl="./toolbox-app.json"
helpAction={{ onClick: () => setHelpOpen(true) }}
>
<Suspense
fallback={
<p className="loading" role="status">
Preparing Data Tools
</p>
}
>
<Workbench />
</Suspense>
</AppShell>
<HelpDialog open={helpOpen} onClose={() => setHelpOpen(false)} />
</ErrorBoundary>
);
}
+27
View File
@@ -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>Data Tools could not continue</h1>
<p>{this.state.error.message}</p>
<button type="button" onClick={() => location.reload()}>
Reload
</button>
</main>
);
return this.props.children;
}
}
+50
View File
@@ -0,0 +1,50 @@
import { useEffect, useRef } from "react";
export function HelpDialog({
open,
onClose,
}: {
open: boolean;
onClose: () => void;
}) {
const dialog = useRef<HTMLDialogElement>(null);
useEffect(() => {
const node = dialog.current;
if (!node) return;
if (open && !node.open) node.showModal();
if (!open && node.open) node.close();
}, [open]);
return (
<dialog
ref={dialog}
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 Data Tools</h2>
</div>
<button type="button" onClick={onClose} aria-label="Close help">
×
</button>
</div>
<p>
Inspect, format, query, flatten and convert JSON, YAML 1.2, TOML, XML,
CSV, TSV and NDJSON locally.
</p>
<p>
All processing is performed in this browser. Imported data is treated as
untrusted, parsed in a disposable worker and bounded to 16 MiB, 100,000
nodes and depth 128.
</p>
<p>
Conversions include a report for coercion or information loss. XML
declarations with external semantics are rejected, and spreadsheet-safe
CSV/TSV output is enabled by default.
</p>
</dialog>
);
}
+848
View File
@@ -0,0 +1,848 @@
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type ChangeEvent,
type CSSProperties,
type DragEvent,
type KeyboardEvent,
} from "react";
import { convertDocument } from "../core/convert";
import { assertBoundedFile, DATA_LIMITS } from "../core/limits";
import { scalarText } from "../core/model";
import { flattenRows, runQuery, tableFromNode, treeRows } from "../core/query";
import { createParseTask, type ParseTask } from "../core/worker-client";
import {
DATA_FORMATS,
DataToolsError,
type ConversionResult,
type DataFormat,
type Diagnostic,
type FormatSelection,
type ParsedDocument,
type QueryMatch,
type TableModel,
} from "../core/types";
const DEFAULT_SAMPLE = `{
"project": "Data Tools",
"exactInteger": 9007199254740993123456789,
"features": ["detect", "inspect", "query", "convert"],
"localOnly": true
}`;
const views = [
{ id: "source", label: "Source", short: "Input & diagnostics" },
{ id: "tree", label: "Tree", short: "Paths & types" },
{ id: "table", label: "Table", short: "Rows & columns" },
{ id: "query", label: "Query", short: "Pointer & safe path" },
{ id: "convert", label: "Convert", short: "Output & disclosure" },
] as const;
type ViewId = (typeof views)[number]["id"];
type ParseStatus = "idle" | "pending" | "ready" | "error";
function initialView(): ViewId {
const hash = globalThis.location?.hash.replace(/^#/, "") as ViewId;
return views.some((view) => view.id === hash) ? hash : "source";
}
function formatSize(bytes: number): string {
if (bytes < 1_024) return `${bytes} B`;
if (bytes < 1_048_576) return `${(bytes / 1_024).toFixed(1)} KiB`;
return `${(bytes / 1_048_576).toFixed(1)} MiB`;
}
function extension(format: DataFormat): string {
return format === "yaml" ? "yaml" : format === "ndjson" ? "jsonl" : format;
}
function downloadText(text: string, format: DataFormat): void {
const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = `converted.${extension(format)}`;
anchor.rel = "noopener";
anchor.hidden = true;
document.body.append(anchor);
try {
anchor.click();
} finally {
anchor.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 0);
}
}
function Diagnostics({ diagnostics }: { diagnostics: Diagnostic[] }) {
if (diagnostics.length === 0)
return <p className="empty-state">No parser diagnostics.</p>;
return (
<ul className="diagnostic-list">
{diagnostics.map((diagnostic, index) => (
<li
key={`${diagnostic.code}-${index}`}
className={`diagnostic diagnostic--${diagnostic.severity}`}
>
<span className="diagnostic__severity">{diagnostic.severity}</span>
<div>
<strong>{diagnostic.code}</strong>
<p>{diagnostic.message}</p>
{diagnostic.location?.line ? (
<small>
Line {diagnostic.location.line}
{diagnostic.location.column
? `, column ${diagnostic.location.column}`
: ""}
</small>
) : null}
</div>
</li>
))}
</ul>
);
}
function DataTable({ table, caption }: { table: TableModel; caption: string }) {
if (table.columns.length === 0)
return <p className="empty-state">This value has no table columns.</p>;
return (
<div
className="table-scroll"
tabIndex={0}
role="region"
aria-label={caption}
>
<table>
<caption className="sr-only">{caption}</caption>
<thead>
<tr>
{table.columns.map((column, index) => (
<th key={`${column}-${index}`} scope="col">
{column || `Column ${index + 1}`}
</th>
))}
</tr>
</thead>
<tbody>
{table.rows.map((row, rowIndex) => (
<tr key={rowIndex}>
{table.columns.map((_, columnIndex) => (
<td key={columnIndex}>{row[columnIndex] ?? ""}</td>
))}
</tr>
))}
</tbody>
</table>
{table.truncatedRows || table.truncatedColumns ? (
<p className="preview-note">
Preview limit reached: {table.truncatedRows} more row(s),{" "}
{table.truncatedColumns} more column(s).
</p>
) : null}
</div>
);
}
function TreeView({ document }: { document: ParsedDocument }) {
const preview = useMemo(() => treeRows(document.root), [document]);
return (
<div className="tree" role="tree" aria-label="Parsed data tree">
{preview.rows.map((row, index) => (
<div
role="treeitem"
aria-level={row.depth + 1}
className="tree-row"
key={`${row.pointer}-${index}`}
style={{ "--tree-depth": row.depth } as CSSProperties}
>
<code className="tree-row__label">{row.label}</code>
<span className={`type-chip type-chip--${row.type}`}>{row.type}</span>
<span className="tree-row__summary">{row.summary}</span>
<code className="tree-row__path">{row.pointer || "(root)"}</code>
</div>
))}
{preview.truncated ? (
<p className="preview-note">
Tree preview stops after 2,000 nodes. Queries and conversions still
use the complete bounded model.
</p>
) : null}
</div>
);
}
function QueryResults({ matches }: { matches: QueryMatch[] }) {
if (matches.length === 0)
return <p className="empty-state">No values matched.</p>;
return (
<div className="query-results">
<p className="result-count">
{matches.length} match{matches.length === 1 ? "" : "es"}
</p>
<ol>
{matches.map((match, index) => (
<li key={`${match.pointer}-${index}`}>
<code>{match.pointer || "(root)"}</code>
<span className={`type-chip type-chip--${match.node.type}`}>
{match.node.type}
</span>
<span>{scalarText(match.node)}</span>
</li>
))}
</ol>
</div>
);
}
function ConversionDisclosure({ result }: { result: ConversionResult }) {
if (result.events.length === 0)
return (
<p className="disclosure disclosure--clean">
No known loss or coercion in this conversion.
</p>
);
return (
<div className="disclosure">
<h3>Conversion report</h3>
<ul>
{result.events.map((event, index) => (
<li
key={`${event.code}-${event.path}-${index}`}
className={`loss-event loss-event--${event.severity}`}
>
<strong>{event.severity}</strong>
<span>
{event.message}
{event.count && event.count > 1
? ` (${event.count} occurrences)`
: ""}
</span>
<code>{event.path || "(root)"}</code>
</li>
))}
</ul>
</div>
);
}
export function Workbench() {
const [source, setSource] = useState(DEFAULT_SAMPLE);
const [selection, setSelection] = useState<FormatSelection>("auto");
const [filename, setFilename] = useState<string>();
const [documentModel, setDocumentModel] = useState<ParsedDocument>();
const [failureDiagnostics, setFailureDiagnostics] = useState<Diagnostic[]>(
[],
);
const [status, setStatus] = useState<ParseStatus>("idle");
const [statusMessage, setStatusMessage] = useState(
"Ready to inspect locally.",
);
const [active, setActive] = useState<ViewId>(initialView);
const [firstRowHeader, setFirstRowHeader] = useState(false);
const [queryMode, setQueryMode] = useState<"pointer" | "path">("pointer");
const [query, setQuery] = useState("/features/0");
const [target, setTarget] = useState<DataFormat>("yaml");
const [spreadsheetSafe, setSpreadsheetSafe] = useState(true);
const [actionNotice, setActionNotice] = useState("");
const currentTask = useRef<ParseTask | undefined>(undefined);
const requestSequence = useRef(0);
const analyze = useCallback(
(value: string, format: FormatSelection, name?: string) => {
currentTask.current?.cancel();
const sequence = ++requestSequence.current;
const task = createParseTask({ source: value, format, filename: name });
currentTask.current = task;
setStatus("pending");
setStatusMessage("Analyzing in an isolated worker…");
void task.promise
.then((parsed) => {
if (sequence !== requestSequence.current) return;
setDocumentModel(parsed);
setFailureDiagnostics([]);
setStatus("ready");
setStatusMessage(
`Parsed as ${parsed.format.toUpperCase()}; ${parsed.stats.nodes.toLocaleString()} bounded nodes.`,
);
setTarget((current) =>
current === parsed.format
? parsed.format === "json"
? "yaml"
: "json"
: current,
);
})
.catch((error: unknown) => {
if (
sequence !== requestSequence.current ||
(error instanceof DOMException && error.name === "AbortError")
)
return;
setStatus("error");
setStatusMessage(
error instanceof Error
? error.message
: "The input could not be parsed.",
);
setFailureDiagnostics(
error instanceof DataToolsError
? error.diagnostics
: [
{
code: "parse.unknown",
message:
error instanceof Error
? error.message
: "Unknown parser failure.",
severity: "error",
},
],
);
});
},
[],
);
useEffect(() => {
const timer = window.setTimeout(
() => analyze(source, selection, filename),
420,
);
return () => window.clearTimeout(timer);
}, [analyze, filename, selection, source]);
useEffect(() => () => currentTask.current?.cancel(), []);
useEffect(() => {
const onHashChange = () => setActive(initialView());
globalThis.addEventListener("hashchange", onHashChange);
return () => globalThis.removeEventListener("hashchange", onHashChange);
}, []);
const diagnostics =
status === "error"
? failureDiagnostics
: (documentModel?.diagnostics ?? []);
const table = useMemo(
() =>
documentModel
? tableFromNode(documentModel.root, firstRowHeader)
: undefined,
[documentModel, firstRowHeader],
);
const flattened = useMemo(
() => (documentModel ? flattenRows(documentModel.root) : undefined),
[documentModel],
);
const queryResult = useMemo(() => {
if (!documentModel) return { matches: [] as QueryMatch[], error: "" };
try {
return {
matches: runQuery(documentModel.root, queryMode, query),
error: "",
};
} catch (error) {
return {
matches: [] as QueryMatch[],
error: error instanceof Error ? error.message : "Invalid query.",
};
}
}, [documentModel, query, queryMode]);
const conversion = useMemo(() => {
if (!documentModel) return { result: undefined, error: "" };
try {
return {
result: convertDocument(documentModel, target, {
spreadsheetSafe,
firstRowHeader,
}),
error: "",
};
} catch (error) {
return {
result: undefined,
error: error instanceof Error ? error.message : "Conversion failed.",
};
}
}, [documentModel, firstRowHeader, spreadsheetSafe, target]);
function selectView(id: ViewId): void {
setActive(id);
history.replaceState(
null,
"",
`${location.pathname}${location.search}#${id}`,
);
}
function tabKeyDown(event: KeyboardEvent<HTMLButtonElement>): void {
if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
event.preventDefault();
const current = views.findIndex((view) => view.id === active);
const index =
event.key === "Home"
? 0
: event.key === "End"
? views.length - 1
: (current + (event.key === "ArrowRight" ? 1 : -1) + views.length) %
views.length;
const next = views[index];
if (!next) return;
selectView(next.id);
requestAnimationFrame(() =>
document.getElementById(`view-tab-${next.id}`)?.focus(),
);
}
async function readFile(file: File): Promise<void> {
try {
assertBoundedFile(file);
const bytes = await file.arrayBuffer();
const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
setFilename(file.name);
setSelection("auto");
setSource(text);
setStatusMessage(`Loaded ${file.name} locally.`);
} catch (error) {
setStatus("error");
setStatusMessage(
error instanceof Error
? error.message
: "The file could not be read as UTF-8 text.",
);
setFailureDiagnostics([
{
code: "file.read",
message:
error instanceof Error
? error.message
: "The file could not be read.",
severity: "error",
},
]);
}
}
function fileChanged(event: ChangeEvent<HTMLInputElement>): void {
const file = event.target.files?.[0];
if (file) void readFile(file);
event.target.value = "";
}
function fileDropped(event: DragEvent<HTMLElement>): void {
event.preventDefault();
const file = event.dataTransfer.files[0];
if (file) void readFile(file);
}
async function copyOutput(): Promise<void> {
if (!conversion.result) return;
try {
await navigator.clipboard.writeText(conversion.result.text);
setActionNotice("Converted output copied.");
} catch {
setActionNotice(
"Clipboard access was denied; select the output and copy it manually.",
);
}
}
function formatSource(): void {
if (!documentModel) return;
try {
const formatted = convertDocument(documentModel, documentModel.format, {
spreadsheetSafe: false,
firstRowHeader,
});
setSource(formatted.text);
setActionNotice(
formatted.events.length
? `Formatted with ${formatted.events.length} disclosure item(s).`
: "Source formatted locally.",
);
} catch (error) {
setActionNotice(
error instanceof Error ? error.message : "Formatting failed.",
);
}
}
return (
<main className="workbench">
<header className="hero">
<div>
<p className="eyebrow">Private structured-data workbench</p>
<h1>Data Tools</h1>
<p>
Detect, inspect, query, flatten, format and convert data without
sending it anywhere.
</p>
</div>
<span
className="privacy-pill"
title="No uploads, telemetry or server processing"
>
Browser-local
</span>
</header>
<section
className="panel editor-panel"
aria-labelledby="input-heading"
onDragOver={(event) => event.preventDefault()}
onDrop={fileDropped}
>
<div className="panel-heading">
<div>
<p className="eyebrow">Untrusted input</p>
<h2 id="input-heading">Source</h2>
</div>
<div className="status-badge" data-status={status}>
<span aria-hidden="true" />
{status}
</div>
</div>
<div className="editor-toolbar">
<label className="field format-field">
<span>Input format</span>
<select
value={selection}
onChange={(event) =>
setSelection(event.target.value as FormatSelection)
}
data-testid="format-select"
>
<option value="auto">Detect automatically</option>
{DATA_FORMATS.map((format) => (
<option value={format} key={format}>
{format.toUpperCase()}
</option>
))}
</select>
</label>
<label className="file-button button">
Open file
<input
type="file"
accept=".json,.jsonl,.ndjson,.yaml,.yml,.toml,.xml,.csv,.tsv,.tab,text/*,application/json,application/xml"
onChange={fileChanged}
data-testid="data-file-input"
/>
</label>
<button
type="button"
className="primary-button"
onClick={() => analyze(source, selection, filename)}
>
Analyze now
</button>
<button
type="button"
onClick={formatSource}
disabled={!documentModel || status === "pending"}
>
Format source
</button>
</div>
<label className="field source-field">
<span>
Text input {filename ? <small> {filename}</small> : null}
</span>
<textarea
value={source}
onChange={(event) => {
setSource(event.target.value);
setFilename(undefined);
}}
spellCheck={false}
aria-describedby="parse-status"
data-testid="source-editor"
/>
</label>
<div className="status-line">
<p id="parse-status" role="status" aria-live="polite">
{statusMessage}
</p>
<p>Auto-analysis keeps the last successful result visible.</p>
</div>
</section>
<nav className="workspace-tabs" aria-label="Data views">
<div role="tablist" aria-label="Data views">
{views.map((view) => (
<button
key={view.id}
id={`view-tab-${view.id}`}
type="button"
role="tab"
aria-selected={active === view.id}
aria-controls={`view-panel-${view.id}`}
tabIndex={active === view.id ? 0 : -1}
onClick={() => selectView(view.id)}
onKeyDown={tabKeyDown}
>
<span>{view.label}</span>
<small>{view.short}</small>
</button>
))}
</div>
</nav>
<section
className="panel view-panel"
role="tabpanel"
id={`view-panel-${active}`}
aria-labelledby={`view-tab-${active}`}
>
{active === "source" ? (
<div className="source-dashboard">
<div>
<div className="section-heading">
<div>
<p className="eyebrow">Detection</p>
<h2>Document summary</h2>
</div>
</div>
{documentModel ? (
<>
<dl className="stats">
<div>
<dt>Format</dt>
<dd>{documentModel.format.toUpperCase()}</dd>
</div>
<div>
<dt>Confidence</dt>
<dd>{documentModel.detection.confidence}</dd>
</div>
<div>
<dt>Size</dt>
<dd>{formatSize(documentModel.stats.bytes)}</dd>
</div>
<div>
<dt>Nodes</dt>
<dd>{documentModel.stats.nodes.toLocaleString()}</dd>
</div>
<div>
<dt>Depth</dt>
<dd>{documentModel.stats.maximumDepth}</dd>
</div>
<div>
<dt>Model</dt>
<dd>{documentModel.model}</dd>
</div>
</dl>
<p className="detection-reason">
{documentModel.detection.reason}
</p>
</>
) : (
<p className="empty-state">
Enter valid data to see its bounded model.
</p>
)}
</div>
<div>
<div className="section-heading">
<div>
<p className="eyebrow">Parser feedback</p>
<h2>Diagnostics</h2>
</div>
<span className="count-pill">{diagnostics.length}</span>
</div>
<Diagnostics diagnostics={diagnostics} />
</div>
</div>
) : null}
{active === "tree" ? (
<>
<div className="section-heading">
<div>
<p className="eyebrow">Bounded preview</p>
<h2>Tree</h2>
</div>
</div>
{documentModel ? (
<TreeView document={documentModel} />
) : (
<p className="empty-state">
Analyze valid input to inspect its tree.
</p>
)}
</>
) : null}
{active === "table" ? (
<>
<div className="section-heading">
<div>
<p className="eyebrow">Projection</p>
<h2>Table</h2>
</div>
<label className="toggle">
<input
type="checkbox"
checked={firstRowHeader}
onChange={(event) => setFirstRowHeader(event.target.checked)}
/>
<span>Use first row as headings</span>
</label>
</div>
{table ? (
<DataTable table={table} caption="Tabular data preview" />
) : (
<p className="empty-state">
Analyze valid input to create a table projection.
</p>
)}
<details className="flatten-panel">
<summary>Flatten scalar leaves by JSON Pointer</summary>
{flattened ? (
<DataTable
table={flattened}
caption="Flattened scalar leaves"
/>
) : null}
</details>
</>
) : null}
{active === "query" ? (
<>
<div className="section-heading">
<div>
<p className="eyebrow">No evaluation</p>
<h2>Safe query</h2>
</div>
</div>
<div className="query-controls">
<label className="field">
<span>Query syntax</span>
<select
value={queryMode}
onChange={(event) => {
const mode = event.target.value as "pointer" | "path";
setQueryMode(mode);
setQuery(
mode === "pointer" ? "/features/0" : "$.features[*]",
);
}}
>
<option value="pointer">JSON Pointer (RFC 6901)</option>
<option value="path">Safe path subset</option>
</select>
</label>
<label className="field">
<span>{queryMode === "pointer" ? "Pointer" : "Path"}</span>
<input
value={query}
onChange={(event) => setQuery(event.target.value)}
maxLength={DATA_LIMITS.maxQueryCharacters}
spellCheck={false}
aria-invalid={Boolean(queryResult.error)}
/>
</label>
</div>
<p className="field-help">
Safe paths support <code>$.key</code>, <code>$['key']</code>,
array indices and <code>[*]</code>. Filters, recursive descent and
scripts are deliberately rejected.
</p>
{queryResult.error ? (
<p className="field-error" role="alert">
{queryResult.error}
</p>
) : (
<QueryResults matches={queryResult.matches} />
)}
</>
) : null}
{active === "convert" ? (
<>
<div className="section-heading">
<div>
<p className="eyebrow">Explicit trade-offs</p>
<h2>Convert</h2>
</div>
<div className="button-row">
<button
type="button"
onClick={() => void copyOutput()}
disabled={!conversion.result}
>
Copy
</button>
<button
type="button"
className="primary-button"
onClick={() =>
conversion.result &&
downloadText(conversion.result.text, target)
}
disabled={!conversion.result}
>
Download
</button>
</div>
</div>
<div className="conversion-controls">
<label className="field">
<span>Output format</span>
<select
value={target}
onChange={(event) =>
setTarget(event.target.value as DataFormat)
}
>
{DATA_FORMATS.map((format) => (
<option key={format} value={format}>
{format.toUpperCase()}
</option>
))}
</select>
</label>
<label className="toggle">
<input
type="checkbox"
checked={spreadsheetSafe}
onChange={(event) => setSpreadsheetSafe(event.target.checked)}
/>
<span>
<strong>Spreadsheet-safe cells</strong>
<small>
Prefix formula-like CSV/TSV cells with an apostrophe
</small>
</span>
</label>
</div>
{conversion.error ? (
<p className="field-error" role="alert">
{conversion.error}
</p>
) : conversion.result ? (
<>
<label className="field output-field">
<span>Generated output</span>
<textarea
readOnly
value={conversion.result.text}
spellCheck={false}
data-testid="conversion-output"
/>
</label>
<ConversionDisclosure result={conversion.result} />
</>
) : (
<p className="empty-state">
Analyze valid input to generate output.
</p>
)}
</>
) : null}
</section>
<p className="action-notice" role="status" aria-live="polite">
{actionNotice}
</p>
</main>
);
}
+510
View File
@@ -0,0 +1,510 @@
import {
isSafeNumber,
LosslessNumber,
stringify as stringifyLosslessJson,
} from "lossless-json";
import Papa from "papaparse";
import { stringify as stringifyToml, TomlDate } from "smol-toml";
import { stringify as stringifyYaml } from "yaml";
import { assertBoundedOutput } from "./limits";
import { objectValue, scalarText } from "./model";
import type {
ConversionOptions,
ConversionResult,
DataFormat,
DataNode,
LossEvent,
ParsedDocument,
} from "./types";
function addEvent(events: LossEvent[], event: LossEvent): void {
const previous = events.find(
(item) => item.code === event.code && item.message === event.message,
);
if (previous) previous.count = (previous.count ?? 1) + (event.count ?? 1);
else events.push(event);
}
function losslessValue(
node: DataNode,
events: LossEvent[],
path: string,
): unknown {
switch (node.type) {
case "null":
return null;
case "boolean":
return node.value;
case "string":
return node.value;
case "number":
return new LosslessNumber(node.raw);
case "date":
addEvent(events, {
code: "date.to-string",
message: "Typed date/time values are represented as strings in JSON.",
path,
severity: "coercion",
});
return node.value;
case "array":
return node.items.map((item, index) =>
losslessValue(item, events, `${path}/${index}`),
);
case "object": {
const result: Record<string, unknown> = Object.create(null) as Record<
string,
unknown
>;
for (const entry of node.entries)
result[entry.key] = losslessValue(
entry.value,
events,
`${path}/${entry.key}`,
);
return result;
}
}
}
function interoperableValue(
node: DataNode,
target: "yaml" | "toml",
events: LossEvent[],
path: string,
): unknown {
switch (node.type) {
case "null":
if (target === "toml") {
addEvent(events, {
code: "toml.null",
message: "TOML has no null value; nulls become empty strings.",
path,
severity: "loss",
});
return "";
}
return null;
case "boolean":
return node.value;
case "string":
return node.value;
case "date": {
if (target === "toml") {
try {
return new TomlDate(node.value);
} catch {
addEvent(events, {
code: "toml.date-string",
message:
"A date could not be represented as a TOML date and remains a string.",
path,
severity: "coercion",
});
}
}
return node.value;
}
case "number": {
if (/^-?(?:0|[1-9]\d*)$/u.test(node.raw)) return BigInt(node.raw);
if (isSafeNumber(node.raw, { approx: false })) return Number(node.raw);
addEvent(events, {
code: `${target}.unsafe-number`,
message: `A number outside exact JavaScript floating-point range becomes a string in ${target.toUpperCase()}.`,
path,
severity: "coercion",
});
return node.raw;
}
case "array":
return node.items.map((item, index) =>
interoperableValue(item, target, events, `${path}/${index}`),
);
case "object": {
const result: Record<string, unknown> = Object.create(null) as Record<
string,
unknown
>;
for (const entry of node.entries)
result[entry.key] = interoperableValue(
entry.value,
target,
events,
`${path}/${entry.key}`,
);
return result;
}
}
}
function jsonText(
node: DataNode,
events: LossEvent[],
indentation: number,
): string {
const text = stringifyLosslessJson(
losslessValue(node, events, ""),
null,
indentation,
);
if (text === undefined)
throw new TypeError("The value cannot be represented as JSON.");
return text;
}
function xmlEscapeText(value: string): string {
return value
.replace(/&/gu, "&amp;")
.replace(/</gu, "&lt;")
.replace(/>/gu, "&gt;");
}
function xmlEscapeAttribute(value: string): string {
return xmlEscapeText(value)
.replace(/"/gu, "&quot;")
.replace(/\r/gu, "&#13;")
.replace(/\n/gu, "&#10;");
}
function nodeString(node: DataNode | undefined): string | undefined {
return node?.type === "string" ? node.value : undefined;
}
function xmlKind(node: DataNode): string | undefined {
return nodeString(objectValue(node, "$kind"));
}
function serializeExplicitXmlElement(node: DataNode, depth: number): string {
const name = nodeString(objectValue(node, "name"));
if (node.type !== "object" || xmlKind(node) !== "element" || !name)
throw new TypeError("The explicit XML model is invalid.");
const attributes = objectValue(node, "attributes");
const children = objectValue(node, "children");
const attributeText =
attributes?.type === "object"
? attributes.entries
.map((entry) => {
const raw =
entry.value.type === "object"
? nodeString(objectValue(entry.value, "value"))
: nodeString(entry.value);
return ` ${entry.key}="${xmlEscapeAttribute(raw ?? "")}"`;
})
.join("")
: "";
if (children?.type !== "array" || children.items.length === 0)
return `<${name}${attributeText}/>`;
const hasSignificantText = children.items.some(
(child) =>
xmlKind(child) === "text" &&
Boolean(nodeString(objectValue(child, "value"))?.trim()),
);
const pieces = children.items.map((child) => {
const kind = xmlKind(child);
const value = nodeString(objectValue(child, "value")) ?? "";
if (kind === "element")
return serializeExplicitXmlElement(child, depth + 1);
if (kind === "text") return xmlEscapeText(value);
if (kind === "cdata") return `<![CDATA[${value}]]>`;
if (kind === "comment") return `<!--${value}-->`;
if (kind === "processing-instruction")
return `<?${nodeString(objectValue(child, "name")) ?? "pi"}${value ? ` ${value}` : ""}?>`;
return "";
});
if (hasSignificantText)
return `<${name}${attributeText}>${pieces.join("")}</${name}>`;
const indentation = " ".repeat(depth + 1);
const inner = pieces
.filter(Boolean)
.map((piece) => `${indentation}${piece}`)
.join("\n");
return inner
? `<${name}${attributeText}>\n${inner}\n${" ".repeat(depth)}</${name}>`
: `<${name}${attributeText}></${name}>`;
}
function validXmlName(name: string): boolean {
return /^[A-Za-z_][\w.:-]*$/u.test(name);
}
function genericXmlElement(
name: string,
node: DataNode,
events: LossEvent[],
path: string,
depth: number,
keyAttribute?: string,
): string {
const safeName = validXmlName(name) ? name : "item";
const key =
safeName === name
? ""
: ` key="${xmlEscapeAttribute(keyAttribute ?? name)}"`;
const indent = " ".repeat(depth);
if (node.type === "object") {
const content = node.entries
.map((entry) =>
genericXmlElement(
entry.key,
entry.value,
events,
`${path}/${entry.key}`,
depth + 1,
entry.key,
),
)
.join("\n");
return content
? `${indent}<${safeName}${key}>\n${content}\n${indent}</${safeName}>`
: `${indent}<${safeName}${key}/>`;
}
if (node.type === "array") {
const content = node.items
.map((item, index) =>
genericXmlElement("item", item, events, `${path}/${index}`, depth + 1),
)
.join("\n");
return content
? `${indent}<${safeName}${key}>\n${content}\n${indent}</${safeName}>`
: `${indent}<${safeName}${key}/>`;
}
if (node.type === "null") {
addEvent(events, {
code: "xml.null",
message: "Null becomes an empty XML element.",
path,
severity: "loss",
});
return `${indent}<${safeName}${key}/>`;
}
addEvent(events, {
code: "xml.scalar-text",
message: "Typed scalar values become XML text.",
path,
severity: "coercion",
});
return `${indent}<${safeName}${key}>${xmlEscapeText(scalarText(node))}</${safeName}>`;
}
function xmlText(document: ParsedDocument, events: LossEvent[]): string {
if (document.model === "xml-explicit") {
addEvent(events, {
code: "xml.prolog",
message:
"Formatting preserves the document element model; XML declaration and nodes outside it are not retained.",
path: "",
severity: "notice",
});
return `<?xml version="1.0" encoding="UTF-8"?>\n${serializeExplicitXmlElement(document.root, 0)}\n`;
}
addEvent(events, {
code: "xml.mapping",
message:
"Objects become named elements, arrays become repeated <item> elements, and invalid XML keys use a key attribute.",
path: "",
severity: "notice",
});
return `<?xml version="1.0" encoding="UTF-8"?>\n${genericXmlElement("root", document.root, events, "", 0)}\n`;
}
function delimitedCell(
node: DataNode,
events: LossEvent[],
path: string,
): string {
if (node.type === "array" || node.type === "object") {
addEvent(events, {
code: "delimited.nested-json",
message: "Nested values are encoded as compact JSON inside a cell.",
path,
severity: "coercion",
});
return jsonText(node, events, 0);
}
if (node.type === "null") {
addEvent(events, {
code: "delimited.null-empty",
message: "Null becomes an empty cell.",
path,
severity: "loss",
});
return "";
}
if (node.type !== "string")
addEvent(events, {
code: "delimited.scalar-text",
message: "Typed scalar values become cell text.",
path,
severity: "coercion",
});
return scalarText(node);
}
function rowsFromNode(node: DataNode, events: LossEvent[]): string[][] {
if (
node.type === "array" &&
node.items.every((item) => item.type === "array")
) {
return (node.items as Array<Extract<DataNode, { type: "array" }>>).map(
(row, rowIndex) =>
row.items.map((cell, columnIndex) =>
delimitedCell(cell, events, `/${rowIndex}/${columnIndex}`),
),
);
}
if (
node.type === "array" &&
node.items.every((item) => item.type === "object")
) {
const keys: string[] = [];
const seen = new Set<string>();
for (const item of node.items as Array<
Extract<DataNode, { type: "object" }>
>)
for (const entry of item.entries)
if (!seen.has(entry.key)) {
seen.add(entry.key);
keys.push(entry.key);
}
return [
keys,
...(node.items as Array<Extract<DataNode, { type: "object" }>>).map(
(item, rowIndex) =>
keys.map((key) => {
const value = item.entries.find((entry) => entry.key === key)
?.value ?? { type: "null" };
return delimitedCell(value, events, `/${rowIndex}/${key}`);
}),
),
];
}
if (node.type === "object") {
addEvent(events, {
code: "delimited.key-value",
message: "A standalone object becomes Key and Value rows.",
path: "",
severity: "notice",
});
return [
["Key", "Value"],
...node.entries.map((entry) => [
entry.key,
delimitedCell(entry.value, events, `/${entry.key}`),
]),
];
}
return [[delimitedCell(node, events, "")]];
}
function protectSpreadsheetCells(rows: string[][], events: LossEvent[]): void {
let count = 0;
for (const row of rows)
for (let index = 0; index < row.length; index += 1) {
const value = row[index] ?? "";
if (/^[=+\-@\t\r]/u.test(value)) {
row[index] = `'${value}`;
count += 1;
}
}
if (count)
addEvent(events, {
code: "csv.formula-neutralized",
message:
"Potential spreadsheet formulas were prefixed with an apostrophe.",
path: "",
severity: "coercion",
count,
});
}
function delimitedText(
document: ParsedDocument,
target: "csv" | "tsv",
options: ConversionOptions,
events: LossEvent[],
): string {
const rows = rowsFromNode(document.root, events);
if (options.spreadsheetSafe) protectSpreadsheetCells(rows, events);
else
addEvent(events, {
code: "csv.formula-unchecked",
message:
"Spreadsheet formula neutralisation is off; treat exported cells as untrusted when opening them in a spreadsheet.",
path: "",
severity: "notice",
});
return Papa.unparse(rows, {
delimiter: target === "tsv" ? "\t" : ",",
newline: "\r\n",
quotes: false,
});
}
function ndjsonText(node: DataNode, events: LossEvent[]): string {
const items = node.type === "array" ? node.items : [node];
if (node.type !== "array")
addEvent(events, {
code: "ndjson.single-record",
message: "The root value becomes one NDJSON record.",
path: "",
severity: "notice",
});
return `${items.map((item) => jsonText(item, events, 0).replace(/\n/gu, "")).join("\n")}\n`;
}
export function convertDocument(
document: ParsedDocument,
target: DataFormat,
options: ConversionOptions = {},
): ConversionResult {
const events: LossEvent[] = [];
if (document.model === "xml-explicit" && target !== "xml") {
addEvent(events, {
code: "xml.explicit-conversion",
message:
"XML converts through the documented explicit element/attribute/children record model.",
path: "",
severity: "notice",
});
}
let text: string;
switch (target) {
case "json":
text = `${jsonText(document.root, events, 2)}\n`;
break;
case "yaml":
text = stringifyYaml(
interoperableValue(document.root, "yaml", events, ""),
{ version: "1.2", schema: "core", indent: 2, lineWidth: 0 },
);
break;
case "toml": {
let value = interoperableValue(document.root, "toml", events, "");
if (document.root.type !== "object") {
addEvent(events, {
code: "toml.root-table",
message:
"TOML requires a root table; the value is placed in a value field.",
path: "",
severity: "coercion",
});
value = { value };
}
text = stringifyToml(value as never);
break;
}
case "xml":
text = xmlText(document, events);
break;
case "csv":
text = delimitedText(document, "csv", options, events);
break;
case "tsv":
text = delimitedText(document, "tsv", options, events);
break;
case "ndjson":
text = ndjsonText(document.root, events);
break;
}
return { text: assertBoundedOutput(text), events, target };
}
+121
View File
@@ -0,0 +1,121 @@
import type { DataFormat, Detection } from "./types";
const EXTENSIONS: Readonly<Record<string, DataFormat>> = Object.freeze({
json: "json",
jsonl: "ndjson",
ndjson: "ndjson",
yaml: "yaml",
yml: "yaml",
toml: "toml",
xml: "xml",
csv: "csv",
tsv: "tsv",
tab: "tsv",
});
function extensionOf(filename: string | undefined): DataFormat | undefined {
const match = filename?.toLocaleLowerCase().match(/\.([a-z0-9]+)$/u);
return match?.[1] ? EXTENSIONS[match[1]] : undefined;
}
function looksLikeDelimited(lines: string[], delimiter: string): boolean {
if (lines.length < 2) return false;
const counts = lines.slice(0, 12).map((line) => line.split(delimiter).length);
const expected = counts[0] ?? 1;
return (
expected > 1 &&
counts.filter((count) => count === expected).length >=
Math.min(3, counts.length)
);
}
function detectFromContent(source: string): Detection {
const trimmed = source.trim();
if (!trimmed)
return {
format: "json",
confidence: "low",
reason: "Empty input defaults to JSON.",
};
if (/^<\?xml\b|^<[A-Za-z_][\w:.-]*(?:\s|>|\/)/u.test(trimmed)) {
return {
format: "xml",
confidence: "high",
reason: "The first token is an XML element.",
};
}
const nonEmptyLines = trimmed.split(/\r?\n/u).filter((line) => line.trim());
if (nonEmptyLines.length > 1) {
try {
if (nonEmptyLines.every((line) => (JSON.parse(line), true))) {
return {
format: "ndjson",
confidence: "high",
reason: "Every non-empty line is a JSON value.",
};
}
} catch {
// Continue with the other deterministic heuristics.
}
}
try {
JSON.parse(trimmed);
return {
format: "json",
confidence: "high",
reason: "The complete input is valid JSON.",
};
} catch {
// A lossless parse will provide the authoritative JSON diagnostic later.
}
if (/^(?:\[\[?[^\]\r\n]+\]\]?|[A-Za-z0-9_.-]+\s*=)/mu.test(trimmed)) {
return {
format: "toml",
confidence: "medium",
reason: "TOML table or assignment syntax was found.",
};
}
if (/^(?:---|%YAML\b)|^[^#\s][^:\r\n]*:\s*(?:$|[^/])/mu.test(trimmed)) {
return {
format: "yaml",
confidence: "medium",
reason: "YAML document or mapping syntax was found.",
};
}
const lines = nonEmptyLines.slice(0, 12);
if (looksLikeDelimited(lines, "\t")) {
return {
format: "tsv",
confidence: "medium",
reason: "Rows have a consistent tab-separated shape.",
};
}
if (looksLikeDelimited(lines, ",")) {
return {
format: "csv",
confidence: "medium",
reason: "Rows have a consistent comma-separated shape.",
};
}
return {
format: "yaml",
confidence: "low",
reason: "YAML can represent a standalone scalar; verify the format.",
};
}
export function detectFormat(source: string, filename?: string): Detection {
const extension = extensionOf(filename);
if (extension) {
return {
format: extension,
confidence: "high",
reason: `The .${filename?.split(".").pop() ?? ""} extension selects ${extension.toUpperCase()}.`,
};
}
return detectFromContent(source);
}
export function detectContentFormat(source: string): Detection {
return detectFromContent(source);
}
+143
View File
@@ -0,0 +1,143 @@
import type { DataNode, DocumentStats } from "./types";
export const DATA_LIMITS = Object.freeze({
maxInputBytes: 16 * 1024 * 1024,
maxTextCharacters: 8_000_000,
maxNodes: 100_000,
maxDepth: 128,
maxCells: 250_000,
maxRows: 50_000,
maxColumns: 2_000,
maxFieldCharacters: 1_000_000,
maxOutputCharacters: 16_000_000,
maxQueryCharacters: 4_096,
maxQueryMatches: 1_000,
parseTimeoutMs: 30_000,
maxPreviewRows: 250,
maxPreviewColumns: 100,
});
export class DataLimitError extends RangeError {
readonly actual: number;
readonly limit: number;
constructor(label: string, actual: number, limit: number) {
super(
`${label} is ${actual.toLocaleString()}; the limit is ${limit.toLocaleString()}.`,
);
this.name = "DataLimitError";
this.actual = actual;
this.limit = limit;
}
}
export function assertBoundedSource(source: string): number {
if (source.length > DATA_LIMITS.maxTextCharacters) {
throw new DataLimitError(
"Input character count",
source.length,
DATA_LIMITS.maxTextCharacters,
);
}
const bytes = new TextEncoder().encode(source).byteLength;
if (bytes > DATA_LIMITS.maxInputBytes) {
throw new DataLimitError(
"UTF-8 input size",
bytes,
DATA_LIMITS.maxInputBytes,
);
}
return bytes;
}
export function assertBoundedFile(file: File): void {
if (file.size > DATA_LIMITS.maxInputBytes) {
throw new DataLimitError("File size", file.size, DATA_LIMITS.maxInputBytes);
}
}
export function assertBoundedOutput(output: string): string {
if (output.length > DATA_LIMITS.maxOutputCharacters) {
throw new DataLimitError(
"Generated output character count",
output.length,
DATA_LIMITS.maxOutputCharacters,
);
}
return output;
}
export function scanBracketDepth(
source: string,
open: string,
close: string,
): void {
let depth = 0;
let quoted = false;
let escaped = false;
for (let index = 0; index < source.length; index += 1) {
const character = source[index];
if (quoted) {
if (escaped) escaped = false;
else if (character === "\\") escaped = true;
else if (character === '"') quoted = false;
continue;
}
if (character === '"') quoted = true;
else if (open.includes(character ?? "")) {
depth += 1;
if (depth > DATA_LIMITS.maxDepth) {
throw new DataLimitError(
"Structural depth",
depth,
DATA_LIMITS.maxDepth,
);
}
} else if (close.includes(character ?? "")) depth = Math.max(0, depth - 1);
}
}
export function measureNode(
root: DataNode,
bytes: number,
characters: number,
): DocumentStats {
const stack: Array<{ node: DataNode; depth: number }> = [
{ node: root, depth: 0 },
];
let nodes = 0;
let maximumDepth = 0;
let scalarCount = 0;
while (stack.length > 0) {
const item = stack.pop();
if (!item) break;
nodes += 1;
if (nodes > DATA_LIMITS.maxNodes) {
throw new DataLimitError(
"Parsed node count",
nodes,
DATA_LIMITS.maxNodes,
);
}
if (item.depth > DATA_LIMITS.maxDepth) {
throw new DataLimitError(
"Parsed depth",
item.depth,
DATA_LIMITS.maxDepth,
);
}
maximumDepth = Math.max(maximumDepth, item.depth);
if (item.node.type === "array") {
for (let index = item.node.items.length - 1; index >= 0; index -= 1) {
const child = item.node.items[index];
if (child) stack.push({ node: child, depth: item.depth + 1 });
}
} else if (item.node.type === "object") {
for (let index = item.node.entries.length - 1; index >= 0; index -= 1) {
const child = item.node.entries[index]?.value;
if (child) stack.push({ node: child, depth: item.depth + 1 });
}
} else scalarCount += 1;
}
return { bytes, characters, nodes, maximumDepth, scalarCount };
}
+180
View File
@@ -0,0 +1,180 @@
import { isLosslessNumber } from "lossless-json";
import { TomlDate } from "smol-toml";
import { DataToolsError, type DataNode, type Diagnostic } from "./types";
import { DATA_LIMITS, DataLimitError } from "./limits";
const DANGEROUS_KEYS = new Set(["__proto__", "constructor", "prototype"]);
interface NormalizeState {
nodes: number;
seen: WeakSet<object>;
diagnostics: Diagnostic[];
}
function dateKind(
value: TomlDate,
): Extract<DataNode, { type: "date" }>["dateKind"] {
if (value.isDate()) return "local-date";
if (value.isTime()) return "local-time";
if (value.isLocal()) return "local-date-time";
return "offset-date-time";
}
export function normalizeValue(
value: unknown,
diagnostics: Diagnostic[] = [],
representation: "exact" | "binary" = "binary",
): DataNode {
const state: NormalizeState = { nodes: 0, seen: new WeakSet(), diagnostics };
const visit = (current: unknown, depth: number, path: string): DataNode => {
state.nodes += 1;
if (state.nodes > DATA_LIMITS.maxNodes)
throw new DataLimitError(
"Parsed node count",
state.nodes,
DATA_LIMITS.maxNodes,
);
if (depth > DATA_LIMITS.maxDepth)
throw new DataLimitError("Parsed depth", depth, DATA_LIMITS.maxDepth);
if (current === null) return { type: "null" };
if (typeof current === "string") return { type: "string", value: current };
if (typeof current === "boolean")
return { type: "boolean", value: current };
if (isLosslessNumber(current))
return { type: "number", raw: current.value, representation: "exact" };
if (typeof current === "bigint")
return {
type: "number",
raw: current.toString(),
representation: "bigint",
};
if (typeof current === "number") {
if (!Number.isFinite(current))
throw new DataToolsError("Non-finite numbers are not supported.", [
{
code: "number.non-finite",
message: `Non-finite number at ${path}.`,
severity: "error",
},
]);
return { type: "number", raw: String(current), representation };
}
if (current instanceof TomlDate) {
return {
type: "date",
value: current.toISOString(),
dateKind: dateKind(current),
};
}
if (current instanceof Date) {
return {
type: "date",
value: current.toISOString(),
dateKind: "offset-date-time",
};
}
if (typeof current !== "object") {
throw new DataToolsError("The parser produced an unsupported value.", [
{
code: "model.unsupported",
message: `Unsupported ${typeof current} value at ${path}.`,
severity: "error",
},
]);
}
if (state.seen.has(current)) {
throw new DataToolsError("Cyclic structures are not supported.", [
{
code: "model.cycle",
message: `A cyclic reference was found at ${path}.`,
severity: "error",
},
]);
}
state.seen.add(current);
try {
if (Array.isArray(current)) {
return {
type: "array",
items: current.map((item, index) =>
visit(item, depth + 1, `${path}/${index}`),
),
};
}
const pairs: Array<[string, unknown]> =
current instanceof Map
? Array.from(current.entries()).map(([key, item]) => [
String(key),
item,
])
: Object.entries(current);
const seenKeys = new Set<string>();
const entries: Array<{ key: string; value: DataNode }> = [];
for (const [key, item] of pairs) {
if (DANGEROUS_KEYS.has(key)) {
throw new DataToolsError("A dangerous object key was rejected.", [
{
code: "object.dangerous-key",
message: `The key “${key}” is prohibited at ${path}.`,
severity: "error",
},
]);
}
if (seenKeys.has(key)) {
throw new DataToolsError("A duplicate mapping key was rejected.", [
{
code: "object.duplicate-key",
message: `Duplicate key “${key}” at ${path}.`,
severity: "error",
},
]);
}
seenKeys.add(key);
entries.push({
key,
value: visit(item, depth + 1, `${path}/${escapePointerToken(key)}`),
});
}
return { type: "object", entries };
} finally {
state.seen.delete(current);
}
};
return visit(value, 0, "");
}
export function escapePointerToken(value: string): string {
return value.replace(/~/gu, "~0").replace(/\//gu, "~1");
}
export function unescapePointerToken(value: string): string {
if (/~(?:[^01]|$)/u.test(value))
throw new SyntaxError(`Invalid JSON Pointer escape in “${value}”.`);
return value.replace(/~1/gu, "/").replace(/~0/gu, "~");
}
export function objectValue(node: DataNode, key: string): DataNode | undefined {
return node.type === "object"
? node.entries.find((entry) => entry.key === key)?.value
: undefined;
}
export function scalarText(node: DataNode): string {
switch (node.type) {
case "null":
return "null";
case "boolean":
return node.value ? "true" : "false";
case "number":
return node.raw;
case "string":
return node.value;
case "date":
return node.value;
case "array":
return `[${node.items.length} items]`;
case "object":
return `{${node.entries.length} entries}`;
}
}
+611
View File
@@ -0,0 +1,611 @@
import {
DOMParser,
type Document as XmlDocument,
type Element as XmlElement,
} from "@xmldom/xmldom";
import { LosslessNumber, parse as parseLosslessJson } from "lossless-json";
import Papa from "papaparse";
import { parse as parseToml } from "smol-toml";
import { parseDocument as parseYamlDocument } from "yaml";
import { detectContentFormat, detectFormat } from "./detect";
import {
assertBoundedSource,
DATA_LIMITS,
measureNode,
scanBracketDepth,
} from "./limits";
import { normalizeValue } from "./model";
import {
DataToolsError,
type DataFormat,
type DataNode,
type Detection,
type Diagnostic,
type ParsedDocument,
type ParseRequest,
} from "./types";
function locationAt(source: string, offset: number | undefined) {
if (offset === undefined || offset < 0) return undefined;
const before = source.slice(0, offset);
const lines = before.split(/\n/u);
return {
offset,
line: lines.length,
column: (lines.at(-1)?.length ?? 0) + 1,
};
}
function parserFailure(
message: string,
code: string,
source: string,
offset?: number,
): DataToolsError {
return new DataToolsError(message, [
{ code, message, severity: "error", location: locationAt(source, offset) },
]);
}
function rejectDangerousJsonKeys(source: string): void {
const prohibited = new Set(["__proto__", "constructor", "prototype"]);
for (let index = 0; index < source.length; index += 1) {
if (source[index] !== '"') continue;
const start = index;
let escaped = false;
index += 1;
while (index < source.length) {
const character = source[index];
if (escaped) escaped = false;
else if (character === "\\") escaped = true;
else if (character === '"') break;
index += 1;
}
if (index >= source.length) return;
const literal = source.slice(start, index + 1);
let next = index + 1;
while (/\s/u.test(source[next] ?? "")) next += 1;
if (source[next] !== ":") continue;
let key: unknown;
try {
key = JSON.parse(literal) as unknown;
} catch {
continue;
}
if (typeof key === "string" && prohibited.has(key)) {
throw parserFailure(
`A dangerous object key was rejected: “${key}”.`,
"json.dangerous-key",
source,
start,
);
}
}
}
function parseJson(source: string): DataNode {
scanBracketDepth(source, "[{", "]}");
rejectDangerousJsonKeys(source);
try {
const value = parseLosslessJson(source, null, {
parseNumber: (raw) => new LosslessNumber(raw),
onDuplicateKey: ({ key, position }) => {
throw parserFailure(
`Duplicate JSON key “${key}”.`,
"json.duplicate-key",
source,
position,
);
},
});
return normalizeValue(value, [], "exact");
} catch (error) {
if (error instanceof DataToolsError) throw error;
const message = error instanceof Error ? error.message : "Invalid JSON.";
const position = /position\s+(\d+)/iu.exec(message)?.[1];
throw parserFailure(
message,
"json.syntax",
source,
position ? Number(position) : undefined,
);
}
}
function parseYaml(source: string, diagnostics: Diagnostic[]): DataNode {
let document;
try {
document = parseYamlDocument(source, {
version: "1.2",
schema: "core",
customTags: [],
merge: false,
resolveKnownTags: false,
intAsBigInt: true,
strict: true,
stringKeys: true,
uniqueKeys: true,
});
} catch (error) {
const message = error instanceof Error ? error.message : "Invalid YAML.";
throw parserFailure(message, "yaml.syntax", source);
}
for (const warning of document.warnings) {
const diagnostic: Diagnostic = {
code: `yaml.${warning.code.toLocaleLowerCase()}`,
message: warning.message,
severity: warning.code === "TAG_RESOLVE_FAILED" ? "error" : "warning",
location: locationAt(source, warning.pos[0]),
};
if (diagnostic.severity === "error")
throw new DataToolsError("Unsupported YAML tag.", [diagnostic]);
diagnostics.push(diagnostic);
}
if (document.errors.length > 0) {
throw new DataToolsError(
"Invalid YAML 1.2 document.",
document.errors.map((item) => ({
code: `yaml.${item.code.toLocaleLowerCase()}`,
message: item.message,
severity: "error",
location: locationAt(source, item.pos[0]),
})),
);
}
let value: unknown;
try {
value = document.toJS({ mapAsMap: true, maxAliasCount: 50 });
} catch (error) {
const message =
error instanceof Error ? error.message : "YAML alias expansion failed.";
throw parserFailure(message, "yaml.alias-limit", source);
}
const root = normalizeValue(value, diagnostics, "binary");
if (containsKey(root, "<<")) {
throw parserFailure(
"YAML merge keys are disabled in this workbench.",
"yaml.merge-disabled",
source,
);
}
if (containsRepresentation(root, "binary")) {
diagnostics.push({
code: "yaml.float-binary",
message:
"YAML floating-point values use the browsers binary number representation; conversions disclose unsafe values.",
severity: "info",
});
}
return root;
}
function parseTomlDocument(
source: string,
diagnostics: Diagnostic[],
): DataNode {
try {
const root = normalizeValue(
parseToml(source, {
integersAsBigInt: true,
maxDepth: DATA_LIMITS.maxDepth,
}),
diagnostics,
"binary",
);
if (containsRepresentation(root, "binary")) {
diagnostics.push({
code: "toml.float-binary",
message:
"TOML floats use the browsers binary number representation; integers remain exact.",
severity: "info",
});
}
return root;
} catch (error) {
if (error instanceof DataToolsError) throw error;
const message = error instanceof Error ? error.message : "Invalid TOML.";
throw parserFailure(message, "toml.syntax", source);
}
}
function containsRepresentation(
node: DataNode,
representation: "binary",
): boolean {
if (node.type === "number") return node.representation === representation;
if (node.type === "array")
return node.items.some((child) =>
containsRepresentation(child, representation),
);
if (node.type === "object")
return node.entries.some((entry) =>
containsRepresentation(entry.value, representation),
);
return false;
}
function containsKey(node: DataNode, key: string): boolean {
if (node.type === "array")
return node.items.some((child) => containsKey(child, key));
if (node.type === "object") {
return node.entries.some(
(entry) => entry.key === key || containsKey(entry.value, key),
);
}
return false;
}
function parseDelimited(
source: string,
delimiter: "," | "\t",
diagnostics: Diagnostic[],
): DataNode {
preflightDelimited(source, delimiter);
const result = Papa.parse<string[]>(source, {
delimiter,
dynamicTyping: false,
header: false,
skipEmptyLines: false,
worker: false,
});
if (result.errors.length > 0) {
const fatal = result.errors.find(
(error) => error.type === "Quotes" || error.type === "Delimiter",
);
const messages = result.errors.slice(0, 20).map((error) => ({
code: `delimited.${error.code.toLocaleLowerCase()}`,
message: error.message,
severity: fatal === error ? ("error" as const) : ("warning" as const),
location: error.row === undefined ? undefined : { line: error.row + 1 },
}));
if (fatal)
throw new DataToolsError("The delimited input is malformed.", messages);
diagnostics.push(...messages);
}
const rows = result.data;
if (rows.length > DATA_LIMITS.maxRows)
throw new RangeError(
`Row count exceeds ${DATA_LIMITS.maxRows.toLocaleString()}.`,
);
let cells = 0;
for (const [rowIndex, row] of rows.entries()) {
if (row.length > DATA_LIMITS.maxColumns)
throw new RangeError(
`Row ${rowIndex + 1} exceeds ${DATA_LIMITS.maxColumns.toLocaleString()} columns.`,
);
cells += row.length;
if (cells > DATA_LIMITS.maxCells)
throw new RangeError(
`Cell count exceeds ${DATA_LIMITS.maxCells.toLocaleString()}.`,
);
for (const field of row) {
if (field.length > DATA_LIMITS.maxFieldCharacters)
throw new RangeError(
`A field exceeds ${DATA_LIMITS.maxFieldCharacters.toLocaleString()} characters.`,
);
}
}
diagnostics.push({
code: "delimited.strings",
message:
"CSV and TSV fields remain strings; no automatic number, date or boolean coercion is applied.",
severity: "info",
});
return normalizeValue(rows, diagnostics, "exact");
}
function preflightDelimited(source: string, delimiter: "," | "\t"): void {
let rows = 0;
let cells = 0;
let columns = 0;
let fieldCharacters = 0;
let quoted = false;
let atFieldStart = true;
const finishField = () => {
if (fieldCharacters > DATA_LIMITS.maxFieldCharacters)
throw new RangeError(
`A field exceeds ${DATA_LIMITS.maxFieldCharacters.toLocaleString()} characters.`,
);
columns += 1;
cells += 1;
if (columns > DATA_LIMITS.maxColumns)
throw new RangeError(
`A row exceeds ${DATA_LIMITS.maxColumns.toLocaleString()} columns.`,
);
if (cells > DATA_LIMITS.maxCells)
throw new RangeError(
`Cell count exceeds ${DATA_LIMITS.maxCells.toLocaleString()}.`,
);
fieldCharacters = 0;
atFieldStart = true;
};
const finishRow = () => {
finishField();
rows += 1;
if (rows > DATA_LIMITS.maxRows)
throw new RangeError(
`Row count exceeds ${DATA_LIMITS.maxRows.toLocaleString()}.`,
);
columns = 0;
};
for (let index = 0; index < source.length; index += 1) {
const character = source[index] ?? "";
if (quoted) {
if (character === '"') {
if (source[index + 1] === '"') {
fieldCharacters += 1;
index += 1;
} else quoted = false;
} else fieldCharacters += 1;
} else if (character === '"' && atFieldStart) {
quoted = true;
atFieldStart = false;
} else if (character === delimiter) {
finishField();
} else if (character === "\r" || character === "\n") {
if (character === "\r" && source[index + 1] === "\n") index += 1;
finishRow();
} else {
fieldCharacters += 1;
atFieldStart = false;
}
if (fieldCharacters > DATA_LIMITS.maxFieldCharacters)
throw new RangeError(
`A field exceeds ${DATA_LIMITS.maxFieldCharacters.toLocaleString()} characters.`,
);
}
finishRow();
}
function parseNdjson(source: string, diagnostics: Diagnostic[]): DataNode {
const lines = source.split(/\r?\n/u);
if (lines.length > DATA_LIMITS.maxRows)
throw new RangeError(
`Line count exceeds ${DATA_LIMITS.maxRows.toLocaleString()}.`,
);
const items: DataNode[] = [];
let blankLines = 0;
for (const [index, line] of lines.entries()) {
if (!line.trim()) {
blankLines += 1;
continue;
}
try {
items.push(parseJson(line));
} catch (error) {
const message =
error instanceof Error ? error.message : "Invalid JSON value.";
throw new DataToolsError(`NDJSON line ${index + 1} is invalid.`, [
{
code: "ndjson.invalid-line",
message,
severity: "error",
location: { line: index + 1, column: 1 },
},
]);
}
}
if (blankLines > 0)
diagnostics.push({
code: "ndjson.blank-lines",
message: `${blankLines} blank line${blankLines === 1 ? " was" : "s were"} ignored.`,
severity: "info",
});
return { type: "array", items };
}
function scanXmlDepth(source: string): void {
let depth = 0;
const tags = source.match(/<\/?[A-Za-z_][^<>]*?>/gu) ?? [];
for (const tag of tags) {
if (tag.startsWith("</")) depth = Math.max(0, depth - 1);
else if (!tag.endsWith("/>")) {
depth += 1;
if (depth > DATA_LIMITS.maxDepth)
throw new RangeError(`XML depth exceeds ${DATA_LIMITS.maxDepth}.`);
}
}
}
function xmlElementModel(
element: XmlElement,
depth = 0,
counter = { value: 0 },
): unknown {
counter.value += 1;
if (counter.value > DATA_LIMITS.maxNodes)
throw new RangeError(
`XML node count exceeds ${DATA_LIMITS.maxNodes.toLocaleString()}.`,
);
if (depth > DATA_LIMITS.maxDepth)
throw new RangeError(`XML depth exceeds ${DATA_LIMITS.maxDepth}.`);
const attributes: Record<string, unknown> = Object.create(null) as Record<
string,
unknown
>;
for (let index = 0; index < element.attributes.length; index += 1) {
const attribute = element.attributes.item(index);
if (!attribute) continue;
attributes[attribute.name] = attribute.namespaceURI
? { value: attribute.value, namespace: attribute.namespaceURI }
: attribute.value;
}
const children: unknown[] = [];
for (let child = element.firstChild; child; child = child.nextSibling) {
counter.value += 1;
if (counter.value > DATA_LIMITS.maxNodes)
throw new RangeError(
`XML node count exceeds ${DATA_LIMITS.maxNodes.toLocaleString()}.`,
);
if (child.nodeType === 1)
children.push(xmlElementModel(child as XmlElement, depth + 1, counter));
else if (child.nodeType === 3)
children.push({ $kind: "text", value: child.nodeValue ?? "" });
else if (child.nodeType === 4)
children.push({ $kind: "cdata", value: child.nodeValue ?? "" });
else if (child.nodeType === 8)
children.push({ $kind: "comment", value: child.nodeValue ?? "" });
else if (child.nodeType === 7)
children.push({
$kind: "processing-instruction",
name: child.nodeName,
value: child.nodeValue ?? "",
});
}
return {
$kind: "element",
name: element.tagName,
namespace: element.namespaceURI,
attributes,
children,
};
}
function parseXml(source: string, diagnostics: Diagnostic[]): DataNode {
if (/<\s*!\s*(?:DOCTYPE|ENTITY)\b/iu.test(source)) {
throw parserFailure(
"XML DOCTYPE and entity declarations are rejected.",
"xml.doctype-rejected",
source,
);
}
if (
/<\s*xi:include\b/iu.test(source) ||
/\bxmlns(?::[A-Za-z_][\w.-]*)?\s*=\s*["']http:\/\/www\.w3\.org\/2001\/XInclude["']/iu.test(
source,
)
) {
throw parserFailure(
"XML XInclude is not supported.",
"xml.xinclude-rejected",
source,
);
}
scanXmlDepth(source);
const warnings: Diagnostic[] = [];
let document: XmlDocument;
try {
document = new DOMParser({
onError(level, message, context) {
const diagnostic: Diagnostic = {
code: `xml.${level.toLocaleLowerCase()}`,
message,
severity: level === "warning" ? "warning" : "error",
location: context?.locator
? {
line: context.locator.lineNumber,
column: context.locator.columnNumber,
}
: undefined,
};
if (diagnostic.severity === "error")
throw new DataToolsError("Invalid XML document.", [diagnostic]);
warnings.push(diagnostic);
},
}).parseFromString(source, "application/xml");
} catch (error) {
if (error instanceof DataToolsError) throw error;
const message = error instanceof Error ? error.message : "Invalid XML.";
throw parserFailure(message, "xml.syntax", source);
}
if (!document.documentElement)
throw parserFailure("XML has no document element.", "xml.no-root", source);
diagnostics.push(...warnings, {
code: "xml.explicit-model",
message:
"XML is represented explicitly as element, namespace, attribute and ordered child records. The XML declaration and nodes outside the document element are not retained.",
severity: "info",
});
return normalizeValue(
xmlElementModel(document.documentElement),
diagnostics,
"exact",
);
}
function selectedDetection(request: ParseRequest): {
selected: DataFormat;
detection: Detection;
diagnostics: Diagnostic[];
} {
const content = detectContentFormat(request.source);
const automatic = detectFormat(request.source, request.filename);
const selected =
request.format === "auto" ? automatic.format : request.format;
const detection: Detection =
request.format === "auto"
? automatic
: {
format: selected,
confidence: "high",
reason: `${selected.toUpperCase()} was selected explicitly.`,
};
const diagnostics: Diagnostic[] = [];
if (content.confidence === "high" && content.format !== selected) {
diagnostics.push({
code: "format.possible-mismatch",
message: `The selected ${selected.toUpperCase()} format differs from content that looks like ${content.format.toUpperCase()}.`,
severity: "warning",
});
}
return { selected, detection, diagnostics };
}
export function parseDataDocument(request: ParseRequest): ParsedDocument {
let bytes: number;
try {
bytes = assertBoundedSource(request.source);
} catch (error) {
const message =
error instanceof Error ? error.message : "Input exceeds a safety limit.";
throw parserFailure(message, "limit.input", request.source);
}
const { selected, detection, diagnostics } = selectedDetection(request);
let root: DataNode;
try {
switch (selected) {
case "json":
root = parseJson(request.source);
break;
case "yaml":
root = parseYaml(request.source, diagnostics);
break;
case "toml":
root = parseTomlDocument(request.source, diagnostics);
break;
case "xml":
root = parseXml(request.source, diagnostics);
break;
case "csv":
root = parseDelimited(request.source, ",", diagnostics);
break;
case "tsv":
root = parseDelimited(request.source, "\t", diagnostics);
break;
case "ndjson":
root = parseNdjson(request.source, diagnostics);
break;
}
const stats = measureNode(root, bytes, request.source.length);
return {
format: selected,
detection,
root,
diagnostics,
stats,
model:
selected === "xml"
? "xml-explicit"
: selected === "csv" || selected === "tsv"
? "tabular"
: "native",
};
} catch (error) {
if (error instanceof DataToolsError) throw error;
const message =
error instanceof Error ? error.message : "The input could not be parsed.";
throw parserFailure(message, `parse.${selected}`, request.source);
}
}
+364
View File
@@ -0,0 +1,364 @@
import { DATA_LIMITS, DataLimitError } from "./limits";
import { escapePointerToken, scalarText, unescapePointerToken } from "./model";
import type { DataNode, QueryMatch, TableModel } from "./types";
function childAt(node: DataNode, token: string): DataNode | undefined {
if (node.type === "object")
return node.entries.find((entry) => entry.key === token)?.value;
if (node.type === "array" && /^(?:0|[1-9]\d*)$/u.test(token))
return node.items[Number(token)];
return undefined;
}
export function queryPointer(root: DataNode, pointer: string): QueryMatch[] {
assertBoundedQuery(pointer);
if (pointer === "") return [{ pointer: "", node: root }];
if (!pointer.startsWith("/"))
throw new SyntaxError("A JSON Pointer is empty or starts with /.");
const tokens = pointer.slice(1).split("/").map(unescapePointerToken);
let current: DataNode | undefined = root;
for (const token of tokens) {
current = current ? childAt(current, token) : undefined;
if (!current) return [];
}
return [{ pointer, node: current }];
}
type PathStep =
| { kind: "key"; key: string }
| { kind: "index"; index: number }
| { kind: "wildcard" };
function decodeSingleQuoted(value: string): string {
return value.replace(/\\(['\\])/gu, "$1");
}
export function parseSafePath(path: string): PathStep[] {
assertBoundedQuery(path);
if (!path.startsWith("$"))
throw new SyntaxError("A safe path starts with $.");
const steps: PathStep[] = [];
let rest = path.slice(1);
while (rest) {
let match = /^\.([A-Za-z_$][\w$]*|\*)/u.exec(rest);
if (match) {
steps.push(
match[1] === "*"
? { kind: "wildcard" }
: { kind: "key", key: match[1] ?? "" },
);
rest = rest.slice(match[0].length);
continue;
}
match = /^\[(\d+|\*)\]/u.exec(rest);
if (match) {
steps.push(
match[1] === "*"
? { kind: "wildcard" }
: { kind: "index", index: Number(match[1]) },
);
rest = rest.slice(match[0].length);
continue;
}
const doubleQuoted = /^\[("(?:[^"\\]|\\.)*")\]/u.exec(rest);
if (doubleQuoted) {
steps.push({
kind: "key",
key: JSON.parse(doubleQuoted[1] ?? '""') as string,
});
rest = rest.slice(doubleQuoted[0].length);
continue;
}
const singleQuoted = /^\['((?:[^'\\]|\\['\\])*)'\]/u.exec(rest);
if (singleQuoted) {
steps.push({
kind: "key",
key: decodeSingleQuoted(singleQuoted[1] ?? ""),
});
rest = rest.slice(singleQuoted[0].length);
continue;
}
throw new SyntaxError(
`Unsupported path syntax near “${rest.slice(0, 24)}”. Filters, scripts and recursive descent are intentionally unavailable.`,
);
}
return steps;
}
function assertBoundedQuery(query: string): void {
if (query.length > DATA_LIMITS.maxQueryCharacters) {
throw new DataLimitError(
"Query character count",
query.length,
DATA_LIMITS.maxQueryCharacters,
);
}
}
export function querySafePath(root: DataNode, path: string): QueryMatch[] {
let matches: QueryMatch[] = [{ pointer: "", node: root }];
for (const step of parseSafePath(path)) {
const next: QueryMatch[] = [];
const add = (match: QueryMatch) => {
next.push(match);
if (next.length > DATA_LIMITS.maxQueryMatches) {
throw new RangeError(
`Query matches exceed the ${DATA_LIMITS.maxQueryMatches.toLocaleString()} result limit.`,
);
}
};
for (const match of matches) {
if (step.kind === "key") {
const child = childAt(match.node, step.key);
if (child)
add({
pointer: `${match.pointer}/${escapePointerToken(step.key)}`,
node: child,
});
} else if (step.kind === "index") {
const child =
match.node.type === "array"
? match.node.items[step.index]
: undefined;
if (child)
add({ pointer: `${match.pointer}/${step.index}`, node: child });
} else if (match.node.type === "array") {
match.node.items.forEach((node, index) =>
add({ pointer: `${match.pointer}/${index}`, node }),
);
} else if (match.node.type === "object") {
match.node.entries.forEach((entry) =>
add({
pointer: `${match.pointer}/${escapePointerToken(entry.key)}`,
node: entry.value,
}),
);
}
}
matches = next;
}
return matches;
}
export function runQuery(
root: DataNode,
mode: "pointer" | "path",
query: string,
): QueryMatch[] {
return mode === "pointer"
? queryPointer(root, query)
: querySafePath(root, query);
}
export interface TreeRow {
pointer: string;
depth: number;
label: string;
type: DataNode["type"];
summary: string;
}
export function treeRows(
root: DataNode,
maximum = 2_000,
): { rows: TreeRow[]; truncated: boolean } {
const rows: TreeRow[] = [];
const stack: Array<{
node: DataNode;
pointer: string;
label: string;
depth: number;
}> = [{ node: root, pointer: "", label: "$", depth: 0 }];
let truncated = false;
while (stack.length > 0) {
const current = stack.pop();
if (!current) break;
if (rows.length >= maximum) {
truncated = true;
break;
}
rows.push({
pointer: current.pointer,
depth: current.depth,
label: current.label,
type: current.node.type,
summary: scalarText(current.node),
});
if (current.node.type === "array") {
for (let index = current.node.items.length - 1; index >= 0; index -= 1) {
const child = current.node.items[index];
if (child)
stack.push({
node: child,
pointer: `${current.pointer}/${index}`,
label: `[${index}]`,
depth: current.depth + 1,
});
}
} else if (current.node.type === "object") {
for (
let index = current.node.entries.length - 1;
index >= 0;
index -= 1
) {
const entry = current.node.entries[index];
if (entry)
stack.push({
node: entry.value,
pointer: `${current.pointer}/${escapePointerToken(entry.key)}`,
label: entry.key,
depth: current.depth + 1,
});
}
}
}
return { rows, truncated };
}
function cellText(node: DataNode): string {
if (node.type === "array" || node.type === "object") return scalarText(node);
return scalarText(node);
}
function boundedTable(
columns: string[],
rows: string[][],
totalRows = rows.length,
totalColumns = columns.length,
): TableModel {
const columnLimit = DATA_LIMITS.maxPreviewColumns;
const rowLimit = DATA_LIMITS.maxPreviewRows;
const visibleColumns = columns.slice(0, columnLimit);
return {
columns: visibleColumns,
rows: rows.slice(0, rowLimit).map((row) => row.slice(0, columnLimit)),
truncatedRows: Math.max(0, totalRows - rowLimit),
truncatedColumns: Math.max(0, totalColumns - columnLimit),
};
}
export function tableFromNode(
root: DataNode,
firstRowHeader = false,
): TableModel {
if (
root.type === "array" &&
root.items.every((item) => item.type === "array")
) {
const rowNodes = root.items as Array<Extract<DataNode, { type: "array" }>>;
const width = rowNodes.reduce(
(maximum, row) => Math.max(maximum, row.items.length),
0,
);
const first = firstRowHeader ? rowNodes[0] : undefined;
const visibleWidth = Math.min(width, DATA_LIMITS.maxPreviewColumns);
const columns = first
? Array.from(
{ length: visibleWidth },
(_, index) =>
cellText(first.items[index] ?? { type: "string", value: "" }) ||
`Column ${index + 1}`,
)
: Array.from(
{ length: visibleWidth },
(_, index) => `Column ${index + 1}`,
);
const rows = rowNodes
.slice(first ? 1 : 0, (first ? 1 : 0) + DATA_LIMITS.maxPreviewRows)
.map((row) =>
Array.from({ length: visibleWidth }, (_, index) =>
cellText(row.items[index] ?? { type: "string", value: "" }),
),
);
return boundedTable(
columns,
rows,
Math.max(0, rowNodes.length - (first ? 1 : 0)),
width,
);
}
if (
root.type === "array" &&
root.items.every((item) => item.type === "object")
) {
const keys: string[] = [];
const seen = new Set<string>();
for (const item of root.items as Array<
Extract<DataNode, { type: "object" }>
>) {
for (const entry of item.entries)
if (!seen.has(entry.key)) {
seen.add(entry.key);
keys.push(entry.key);
}
}
const visibleKeys = keys.slice(0, DATA_LIMITS.maxPreviewColumns);
const objectRows = root.items as Array<
Extract<DataNode, { type: "object" }>
>;
const rows = objectRows.slice(0, DATA_LIMITS.maxPreviewRows).map((item) => {
const values = new Map(
item.entries.map((entry) => [entry.key, entry.value] as const),
);
return visibleKeys.map((key) => {
const value = values.get(key);
return value ? cellText(value) : "";
});
});
return boundedTable(visibleKeys, rows, objectRows.length, keys.length);
}
if (root.type === "object") {
return boundedTable(
["Key", "Type", "Value"],
root.entries
.slice(0, DATA_LIMITS.maxPreviewRows)
.map((entry) => [entry.key, entry.value.type, cellText(entry.value)]),
root.entries.length,
3,
);
}
return boundedTable(
["Path", "Type", "Value"],
[["", root.type, cellText(root)]],
);
}
export function flattenRows(
root: DataNode,
maximum = DATA_LIMITS.maxQueryMatches,
): TableModel {
const rows: string[][] = [];
const stack: Array<{ node: DataNode; pointer: string }> = [
{ node: root, pointer: "" },
];
let omitted = 0;
while (stack.length > 0) {
const current = stack.pop();
if (!current) break;
if (current.node.type === "array") {
for (let index = current.node.items.length - 1; index >= 0; index -= 1) {
const child = current.node.items[index];
if (child)
stack.push({ node: child, pointer: `${current.pointer}/${index}` });
}
} else if (current.node.type === "object") {
for (
let index = current.node.entries.length - 1;
index >= 0;
index -= 1
) {
const entry = current.node.entries[index];
if (entry)
stack.push({
node: entry.value,
pointer: `${current.pointer}/${escapePointerToken(entry.key)}`,
});
}
} else if (rows.length < maximum)
rows.push([current.pointer, current.node.type, scalarText(current.node)]);
else omitted += 1;
}
const table = boundedTable(["JSON Pointer", "Type", "Value"], rows);
table.truncatedRows += omitted;
return table;
}
+119
View File
@@ -0,0 +1,119 @@
export const DATA_FORMATS = [
"json",
"yaml",
"toml",
"xml",
"csv",
"tsv",
"ndjson",
] as const;
export type DataFormat = (typeof DATA_FORMATS)[number];
export type FormatSelection = DataFormat | "auto";
export type Severity = "error" | "warning" | "info";
export interface SourceLocation {
line?: number;
column?: number;
offset?: number;
}
export interface Diagnostic {
code: string;
message: string;
severity: Severity;
location?: SourceLocation;
}
export type DataNode =
| { type: "null" }
| { type: "boolean"; value: boolean }
| { type: "string"; value: string }
| {
type: "number";
raw: string;
representation: "exact" | "bigint" | "binary";
}
| {
type: "date";
value: string;
dateKind:
"offset-date-time" | "local-date-time" | "local-date" | "local-time";
}
| { type: "array"; items: DataNode[] }
| { type: "object"; entries: Array<{ key: string; value: DataNode }> };
export interface Detection {
format: DataFormat;
confidence: "high" | "medium" | "low";
reason: string;
}
export interface DocumentStats {
bytes: number;
characters: number;
nodes: number;
maximumDepth: number;
scalarCount: number;
}
export interface ParsedDocument {
format: DataFormat;
detection: Detection;
root: DataNode;
diagnostics: Diagnostic[];
stats: DocumentStats;
model: "native" | "tabular" | "xml-explicit";
}
export interface ParseRequest {
source: string;
format: FormatSelection;
filename?: string;
}
export interface ParseFailureData {
message: string;
diagnostics: Diagnostic[];
}
export interface LossEvent {
code: string;
message: string;
path: string;
severity: "loss" | "coercion" | "notice";
count?: number;
}
export interface ConversionOptions {
spreadsheetSafe?: boolean;
firstRowHeader?: boolean;
}
export interface ConversionResult {
text: string;
events: LossEvent[];
target: DataFormat;
}
export interface QueryMatch {
pointer: string;
node: DataNode;
}
export interface TableModel {
columns: string[];
rows: string[][];
truncatedRows: number;
truncatedColumns: number;
}
export class DataToolsError extends Error {
readonly diagnostics: Diagnostic[];
constructor(message: string, diagnostics: Diagnostic[]) {
super(message);
this.name = "DataToolsError";
this.diagnostics = diagnostics;
}
}
+106
View File
@@ -0,0 +1,106 @@
import { parseDataDocument } from "./parse";
import { DATA_LIMITS } from "./limits";
import {
DataToolsError,
type ParsedDocument,
type ParseRequest,
} from "./types";
interface WorkerResponseOk {
id: number;
ok: true;
document: ParsedDocument;
}
interface WorkerResponseError {
id: number;
ok: false;
message: string;
diagnostics: DataToolsError["diagnostics"];
}
export interface ParseTask {
promise: Promise<ParsedDocument>;
cancel(): void;
}
let requestId = 0;
export function createParseTask(request: ParseRequest): ParseTask {
const id = ++requestId;
if (typeof Worker === "undefined") {
let cancelled = false;
return {
promise: Promise.resolve().then(() => {
if (cancelled)
throw new DOMException("Parsing cancelled.", "AbortError");
return parseDataDocument(request);
}),
cancel() {
cancelled = true;
},
};
}
const worker = new Worker(
new URL("../workers/data.worker.ts", import.meta.url),
{ type: "module", name: "data-tools-parser" },
);
let settled = false;
let rejectPromise: ((reason?: unknown) => void) | undefined;
const timeout = globalThis.setTimeout(() => {
if (settled) return;
settled = true;
worker.terminate();
rejectPromise?.(
new DataToolsError(
`Parsing exceeded the ${DATA_LIMITS.parseTimeoutMs / 1000}-second safety limit.`,
[
{
code: "worker.timeout",
message:
"The disposable parser worker was terminated before it completed.",
severity: "error",
},
],
),
);
}, DATA_LIMITS.parseTimeoutMs);
const finish = () => {
if (settled) return false;
settled = true;
globalThis.clearTimeout(timeout);
worker.terminate();
return true;
};
const promise = new Promise<ParsedDocument>((resolve, reject) => {
rejectPromise = reject;
worker.onmessage = (
event: MessageEvent<WorkerResponseOk | WorkerResponseError>,
) => {
if (event.data.id !== id || !finish()) return;
if (event.data.ok) resolve(event.data.document);
else
reject(new DataToolsError(event.data.message, event.data.diagnostics));
};
worker.onerror = (event) => {
if (!finish()) return;
reject(
new DataToolsError(event.message || "The parser worker failed.", [
{
code: "worker.failure",
message: event.message || "The parser worker failed.",
severity: "error",
},
]),
);
};
worker.postMessage({ id, request });
});
return {
promise,
cancel() {
if (!finish()) return;
rejectPromise?.(new DOMException("Parsing cancelled.", "AbortError"));
},
};
}
+18
View File
@@ -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);
});
}
+911
View File
@@ -0,0 +1,911 @@
:root {
--toolbox-background: #f6f7fb;
--toolbox-surface: #ffffff;
--toolbox-surface-soft: #eff1f7;
--toolbox-text: #202332;
--toolbox-muted: #656b7d;
--toolbox-border: #d9dce7;
--toolbox-accent: #5b4ec4;
--toolbox-accent-hover: #493caf;
--toolbox-accent-soft: #ece9ff;
--toolbox-accent-contrast: #ffffff;
--toolbox-focus: #137d75;
--toolbox-danger: #b42342;
--data-success: #11715c;
--data-warning: #9a5d06;
--data-radius: 0.82rem;
--data-shadow: 0 1px 2px rgb(24 31 65 / 4%), 0 10px 30px rgb(24 31 65 / 3%);
}
* {
box-sizing: border-box;
}
html {
min-width: 20rem;
min-height: 100%;
background: var(--toolbox-background);
scrollbar-gutter: stable;
}
body {
min-width: 20rem;
min-height: 100vh;
margin: 0;
background: var(--toolbox-background);
color: var(--toolbox-text);
font-family:
Inter,
ui-sans-serif,
system-ui,
-apple-system,
sans-serif;
text-rendering: optimizeLegibility;
}
#root {
min-height: 100vh;
}
::selection {
background: color-mix(in srgb, var(--toolbox-focus) 38%, transparent);
}
.toolbox-shell__main {
width: min(100%, 90rem);
padding: clamp(0.75rem, 1.8vw, 1.5rem);
}
.workbench {
display: grid;
gap: 1rem;
color: var(--toolbox-text);
}
.workbench :where(h1, h2, h3),
.help-dialog :where(h2, h3),
.fatal h1 {
margin: 0;
color: var(--toolbox-text);
font-weight: 760;
letter-spacing: -0.027em;
line-height: 1.16;
}
.workbench h1 {
font-size: clamp(1.75rem, 3vw, 2.55rem);
}
.workbench h2,
.help-dialog h2 {
font-size: clamp(1.2rem, 2vw, 1.55rem);
}
.workbench h3 {
font-size: 0.96rem;
}
.workbench p,
.workbench ul,
.workbench ol,
.workbench dl {
margin-block: 0;
}
.sr-only {
position: absolute !important;
width: 1px !important;
height: 1px !important;
padding: 0 !important;
margin: -1px !important;
overflow: hidden !important;
clip: rect(0, 0, 0, 0) !important;
white-space: nowrap !important;
border: 0 !important;
}
.workbench :where(button, input, select, textarea),
.help-dialog button {
font: inherit;
}
.workbench button,
.workbench .button,
.help-dialog button {
min-height: 2.55rem;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.4rem;
padding: 0.55rem 0.8rem;
border: 1px solid var(--toolbox-border);
border-radius: 0.64rem;
background: var(--toolbox-surface);
color: var(--toolbox-text);
font-size: 0.82rem;
font-weight: 720;
line-height: 1.2;
cursor: pointer;
touch-action: manipulation;
transition:
border-color 140ms ease,
background-color 140ms ease,
transform 140ms ease;
}
.workbench button:hover:not(:disabled),
.workbench .button:hover {
border-color: color-mix(
in srgb,
var(--toolbox-accent) 58%,
var(--toolbox-border)
);
background: var(--toolbox-surface-soft);
}
.workbench button:active:not(:disabled) {
transform: translateY(1px);
}
.workbench button:disabled {
cursor: not-allowed;
opacity: 0.45;
}
.workbench .primary-button {
border-color: var(--toolbox-accent);
background: var(--toolbox-accent);
color: var(--toolbox-accent-contrast);
}
.workbench .primary-button:hover:not(:disabled) {
border-color: var(--toolbox-accent-hover);
background: var(--toolbox-accent-hover);
}
:where(.workbench, .help-dialog)
:where(button, input, select, textarea, summary):focus-visible,
.table-scroll:focus-visible {
outline: 3px solid color-mix(in srgb, var(--toolbox-focus) 42%, transparent);
outline-offset: 2px;
}
.workbench :where(input:not([type="checkbox"]), select, textarea) {
width: 100%;
min-width: 0;
min-height: 2.55rem;
padding: 0.58rem 0.7rem;
border: 1px solid var(--toolbox-border);
border-radius: 0.62rem;
background: var(--toolbox-surface);
color: var(--toolbox-text);
line-height: 1.4;
}
.workbench textarea {
resize: vertical;
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
font-size: 0.84rem;
tab-size: 2;
}
.workbench input[aria-invalid="true"] {
border-color: var(--toolbox-danger);
}
.hero,
.panel {
border: 1px solid var(--toolbox-border);
border-radius: var(--data-radius);
background: var(--toolbox-surface);
box-shadow: var(--data-shadow);
}
.hero {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
padding: clamp(1.1rem, 3vw, 2rem);
}
.hero p:not(.eyebrow) {
max-width: 55rem;
margin-top: 0.55rem;
color: var(--toolbox-muted);
line-height: 1.55;
}
.eyebrow {
margin: 0 0 0.3rem !important;
color: var(--toolbox-accent);
font-size: 0.68rem;
font-weight: 820;
letter-spacing: 0.115em;
line-height: 1.35;
text-transform: uppercase;
}
.privacy-pill,
.count-pill {
flex: 0 0 auto;
padding: 0.38rem 0.64rem;
border-radius: 999px;
background: var(--toolbox-accent-soft);
color: var(--toolbox-accent);
font-size: 0.75rem;
font-weight: 780;
}
.panel {
min-width: 0;
padding: clamp(0.9rem, 2vw, 1.2rem);
}
.panel-heading,
.section-heading {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 1rem;
}
.panel-heading {
margin-bottom: 0.85rem;
}
.section-heading {
margin-bottom: 0.75rem;
}
.editor-toolbar {
display: grid;
grid-template-columns: minmax(11rem, 1fr) auto auto auto;
align-items: end;
gap: 0.55rem;
margin-bottom: 0.75rem;
}
.field {
min-width: 0;
display: grid;
gap: 0.34rem;
}
.field > span,
.field-label {
font-size: 0.76rem;
font-weight: 750;
}
.field small,
.toggle small {
color: var(--toolbox-muted);
font-weight: 500;
}
.source-field textarea {
min-height: clamp(12rem, 26vh, 21rem);
}
.output-field textarea {
min-height: 18rem;
}
.file-button {
position: relative;
overflow: hidden;
}
.file-button input {
position: absolute;
width: 1px !important;
height: 1px;
opacity: 0;
}
.status-badge {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.34rem 0.55rem;
border: 1px solid var(--toolbox-border);
border-radius: 999px;
color: var(--toolbox-muted);
font-size: 0.69rem;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.status-badge span {
width: 0.48rem;
height: 0.48rem;
border-radius: 50%;
background: currentColor;
}
.status-badge[data-status="ready"] {
color: var(--data-success);
}
.status-badge[data-status="error"] {
color: var(--toolbox-danger);
}
.status-badge[data-status="pending"] {
color: var(--toolbox-accent);
}
.status-badge[data-status="pending"] span {
animation: status-pulse 900ms ease-in-out infinite alternate;
}
@keyframes status-pulse {
to {
opacity: 0.25;
}
}
.status-line {
display: flex;
justify-content: space-between;
gap: 1rem;
margin-top: 0.55rem;
color: var(--toolbox-muted);
font-size: 0.75rem;
line-height: 1.45;
}
.status-line p:first-child {
color: var(--toolbox-text);
font-weight: 650;
}
.workspace-tabs {
min-width: 0;
overflow-x: auto;
padding: 0.1rem 0 0.15rem;
}
.workspace-tabs [role="tablist"] {
min-width: max-content;
display: grid;
grid-template-columns: repeat(5, minmax(9.5rem, 1fr));
gap: 0.45rem;
}
.workspace-tabs button {
min-height: 3.55rem;
display: grid;
justify-items: start;
align-content: center;
padding: 0.58rem 0.75rem;
text-align: left;
}
.workspace-tabs button small {
color: var(--toolbox-muted);
font-size: 0.69rem;
font-weight: 560;
}
.workspace-tabs button[aria-selected="true"] {
border-color: var(--toolbox-accent);
background: var(--toolbox-accent);
color: var(--toolbox-accent-contrast);
}
.workspace-tabs button[aria-selected="true"] small {
color: color-mix(in srgb, var(--toolbox-accent-contrast) 78%, transparent);
}
.view-panel {
min-height: 21rem;
}
.source-dashboard {
display: grid;
grid-template-columns: minmax(0, 0.9fr) minmax(0, 1.1fr);
gap: 1.25rem;
}
.source-dashboard > div + div {
padding-left: 1.25rem;
border-left: 1px solid var(--toolbox-border);
}
.stats {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 0.55rem;
}
.stats div {
min-width: 0;
padding: 0.7rem;
border: 1px solid var(--toolbox-border);
border-radius: 0.64rem;
background: var(--toolbox-surface-soft);
}
.stats dt {
color: var(--toolbox-muted);
font-size: 0.67rem;
font-weight: 760;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.stats dd {
margin: 0.25rem 0 0;
overflow-wrap: anywhere;
font-size: 0.9rem;
font-weight: 760;
}
.detection-reason,
.empty-state,
.field-help,
.preview-note {
color: var(--toolbox-muted);
font-size: 0.8rem;
line-height: 1.55;
}
.detection-reason {
margin-top: 0.75rem !important;
}
.empty-state {
padding: 1rem;
border: 1px dashed var(--toolbox-border);
border-radius: 0.65rem;
background: var(--toolbox-surface-soft);
}
.diagnostic-list {
display: grid;
gap: 0.5rem;
padding: 0;
list-style: none;
}
.diagnostic {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
align-items: start;
gap: 0.65rem;
padding: 0.65rem;
border: 1px solid var(--toolbox-border);
border-left: 3px solid var(--toolbox-muted);
border-radius: 0.62rem;
}
.diagnostic--error {
border-left-color: var(--toolbox-danger);
}
.diagnostic--warning {
border-left-color: var(--data-warning);
}
.diagnostic--info {
border-left-color: var(--toolbox-accent);
}
.diagnostic__severity {
padding: 0.2rem 0.35rem;
border-radius: 0.3rem;
background: var(--toolbox-surface-soft);
color: var(--toolbox-muted);
font-size: 0.61rem;
font-weight: 820;
text-transform: uppercase;
}
.diagnostic strong {
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
font-size: 0.74rem;
}
.diagnostic p {
margin-top: 0.18rem;
color: var(--toolbox-muted);
font-size: 0.76rem;
line-height: 1.45;
}
.diagnostic small {
color: var(--toolbox-muted);
font-size: 0.68rem;
}
.tree {
max-height: 42rem;
overflow: auto;
border: 1px solid var(--toolbox-border);
border-radius: 0.65rem;
background: var(--toolbox-surface-soft);
}
.tree-row {
min-width: 44rem;
display: grid;
grid-template-columns: minmax(9rem, 0.75fr) auto minmax(8rem, 1fr) minmax(
12rem,
1fr
);
align-items: center;
gap: 0.55rem;
padding: 0.38rem 0.55rem 0.38rem
calc(0.55rem + min(var(--tree-depth), 12) * 0.9rem);
border-bottom: 1px solid var(--toolbox-border);
font-size: 0.76rem;
}
.tree-row:last-child {
border-bottom: 0;
}
.tree-row:hover {
background: var(--toolbox-surface);
}
.tree-row__label,
.tree-row__summary,
.tree-row__path {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tree-row__label {
color: var(--toolbox-text);
font-weight: 720;
}
.tree-row__summary {
color: var(--toolbox-muted);
}
.tree-row__path {
color: var(--toolbox-muted);
font-size: 0.68rem;
}
.type-chip {
display: inline-flex;
width: fit-content;
padding: 0.17rem 0.35rem;
border-radius: 0.3rem;
background: var(--toolbox-accent-soft);
color: var(--toolbox-accent);
font-size: 0.62rem;
font-weight: 800;
letter-spacing: 0.03em;
text-transform: uppercase;
}
.type-chip--string {
color: var(--data-success);
background: color-mix(
in srgb,
var(--data-success) 11%,
var(--toolbox-surface)
);
}
.type-chip--number {
color: #9a4f10;
background: color-mix(in srgb, #c96814 12%, var(--toolbox-surface));
}
.type-chip--boolean {
color: #235cb0;
background: color-mix(in srgb, #3478cf 12%, var(--toolbox-surface));
}
.type-chip--null {
color: var(--toolbox-muted);
background: var(--toolbox-surface-soft);
}
.table-scroll {
max-height: 38rem;
overflow: auto;
border: 1px solid var(--toolbox-border);
border-radius: 0.65rem;
}
.table-scroll table {
min-width: 100%;
border-collapse: collapse;
font-size: 0.77rem;
}
.table-scroll :where(th, td) {
max-width: 24rem;
padding: 0.52rem 0.62rem;
overflow: hidden;
border-right: 1px solid var(--toolbox-border);
border-bottom: 1px solid var(--toolbox-border);
text-align: left;
text-overflow: ellipsis;
white-space: nowrap;
}
.table-scroll th {
position: sticky;
z-index: 1;
top: 0;
background: var(--toolbox-surface-soft);
font-weight: 760;
}
.table-scroll tr:hover td {
background: var(--toolbox-surface-soft);
}
.table-scroll :where(th, td):last-child {
border-right: 0;
}
.preview-note {
padding: 0.65rem;
}
.toggle {
display: flex;
align-items: center;
gap: 0.55rem;
color: var(--toolbox-text);
font-size: 0.75rem;
font-weight: 700;
cursor: pointer;
}
.toggle input {
width: 1.05rem;
height: 1.05rem;
flex: 0 0 auto;
accent-color: var(--toolbox-accent);
}
.toggle > span {
display: grid;
gap: 0.08rem;
}
.flatten-panel {
margin-top: 0.85rem;
border: 1px solid var(--toolbox-border);
border-radius: 0.65rem;
}
.flatten-panel summary {
padding: 0.72rem;
font-size: 0.78rem;
font-weight: 740;
cursor: pointer;
}
.flatten-panel .table-scroll {
margin: 0 0.7rem 0.7rem;
}
.query-controls,
.conversion-controls {
display: grid;
gap: 0.75rem;
margin-bottom: 0.65rem;
}
.query-controls {
grid-template-columns: minmax(12rem, 0.45fr) minmax(14rem, 1fr);
}
.conversion-controls {
grid-template-columns: minmax(12rem, 0.4fr) minmax(15rem, 1fr);
align-items: end;
}
.field-help {
margin-bottom: 0.75rem !important;
}
.field-error {
margin: 0.6rem 0 !important;
color: var(--toolbox-danger);
font-size: 0.8rem;
font-weight: 650;
}
.query-results {
display: grid;
gap: 0.45rem;
margin-top: 0.75rem;
}
.result-count {
color: var(--toolbox-muted);
font-size: 0.72rem;
font-weight: 740;
}
.query-results ol {
display: grid;
gap: 0.4rem;
padding: 0;
list-style: none;
}
.query-results li {
display: grid;
grid-template-columns: minmax(9rem, 0.6fr) auto minmax(9rem, 1fr);
align-items: center;
gap: 0.55rem;
padding: 0.52rem 0.6rem;
border: 1px solid var(--toolbox-border);
border-radius: 0.55rem;
font-size: 0.77rem;
}
.query-results li > :last-child {
overflow: hidden;
color: var(--toolbox-muted);
text-overflow: ellipsis;
white-space: nowrap;
}
.button-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.45rem;
}
.disclosure {
margin-top: 0.75rem;
padding: 0.75rem;
border: 1px solid var(--toolbox-border);
border-radius: 0.65rem;
background: var(--toolbox-surface-soft);
}
.disclosure--clean {
color: var(--data-success);
font-size: 0.8rem;
font-weight: 650;
}
.disclosure ul {
display: grid;
gap: 0.38rem;
margin-top: 0.55rem;
padding: 0;
list-style: none;
}
.loss-event {
display: grid;
grid-template-columns: 5.2rem minmax(0, 1fr) minmax(7rem, auto);
gap: 0.55rem;
padding: 0.48rem 0.55rem;
border-radius: 0.5rem;
background: var(--toolbox-surface);
font-size: 0.74rem;
}
.loss-event strong {
color: var(--toolbox-muted);
font-size: 0.64rem;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.loss-event--loss strong {
color: var(--toolbox-danger);
}
.loss-event--coercion strong {
color: var(--data-warning);
}
.loss-event code {
overflow: hidden;
color: var(--toolbox-muted);
text-align: right;
text-overflow: ellipsis;
white-space: nowrap;
}
.action-notice {
min-height: 1.2rem;
color: var(--toolbox-muted);
font-size: 0.75rem;
text-align: center;
}
.loading,
.fatal {
width: min(100% - 2rem, 60rem);
margin: 2rem auto;
padding: 1rem;
}
.help-dialog {
width: min(36rem, calc(100% - 2rem));
border: 1px solid var(--toolbox-border);
border-radius: 0.9rem;
background: var(--toolbox-surface);
color: var(--toolbox-text);
}
.help-dialog::backdrop {
background: rgb(20 24 45 / 55%);
}
.dialog-heading {
display: flex;
justify-content: space-between;
gap: 1rem;
align-items: start;
}
.help-dialog p {
line-height: 1.55;
}
@media (max-width: 54rem) {
.editor-toolbar {
grid-template-columns: 1fr 1fr;
}
.source-dashboard {
grid-template-columns: 1fr;
}
.source-dashboard > div + div {
padding: 1rem 0 0;
border-top: 1px solid var(--toolbox-border);
border-left: 0;
}
}
@media (max-width: 42rem) {
.hero {
flex-direction: column;
}
.privacy-pill {
order: -1;
}
.editor-toolbar,
.query-controls,
.conversion-controls {
grid-template-columns: 1fr;
}
.editor-toolbar > :not(.format-field) {
width: 100%;
}
.status-line {
display: grid;
gap: 0.25rem;
}
.panel-heading,
.section-heading {
align-items: flex-start;
}
.section-heading:has(.toggle) {
flex-direction: column;
}
.stats {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.query-results li {
grid-template-columns: 1fr auto;
}
.query-results li > :last-child {
grid-column: 1 / -1;
}
.loss-event {
grid-template-columns: auto 1fr;
}
.loss-event code {
grid-column: 1 / -1;
text-align: left;
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
scroll-behavior: auto !important;
transition-duration: 0.01ms !important;
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
}
}
+8
View File
@@ -0,0 +1,8 @@
import "@testing-library/jest-dom/vitest";
import { afterEach } from "vitest";
import { cleanup } from "@testing-library/react";
afterEach(() => {
cleanup();
localStorage.clear();
});
+41
View File
@@ -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.data-tools",
"name": "Data Tools",
"version": "0.1.0",
"description": "Inspect, query and convert structured data locally in the browser.",
"entry": "./",
"icon": "./favicon.svg",
"categories": ["data", "developer", "documents"],
"tags": ["json", "yaml", "toml", "xml", "csv", "tsv", "ndjson"],
"integration": {
"contextVersion": 1,
"launchModes": ["navigate", "new-tab"],
"embedding": "unsupported"
},
"requirements": {
"secureContext": false,
"workers": true,
"indexedDb": false,
"crossOriginIsolated": false,
"topLevelContext": false
},
"privacy": {
"processing": "local",
"fileUploads": false,
"telemetry": false,
"label": "Inputs stay in this browser; nothing is uploaded."
},
"source": {
"repository": "https://git.add-ideas.de/lotobo/data-tools",
"license": "GPL-3.0-or-later"
},
"actions": [
{
"id": "source",
"label": "Source",
"url": "https://git.add-ideas.de/lotobo/data-tools"
}
]
}
+4
View File
@@ -0,0 +1,4 @@
import { defineToolboxApp, parseToolboxApp } from "@add-ideas/toolbox-contract";
import source from "./manifest.source.json";
export const manifest = defineToolboxApp(parseToolboxApp(source));
+1
View File
@@ -0,0 +1 @@
export const APP_VERSION = "0.1.0";
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+54
View File
@@ -0,0 +1,54 @@
/// <reference lib="webworker" />
import { parseDataDocument } from "../core/parse";
import {
DataToolsError,
type ParsedDocument,
type ParseRequest,
} from "../core/types";
interface WorkerRequest {
id: number;
request: ParseRequest;
}
type WorkerResponse =
| { id: number; ok: true; document: ParsedDocument }
| {
id: number;
ok: false;
message: string;
diagnostics: DataToolsError["diagnostics"];
};
self.onmessage = (event: MessageEvent<WorkerRequest>) => {
const { id, request } = event.data;
let response: WorkerResponse;
try {
response = { id, ok: true, document: parseDataDocument(request) };
} catch (error) {
response = {
id,
ok: false,
message:
error instanceof Error
? error.message
: "The input could not be parsed.",
diagnostics:
error instanceof DataToolsError
? error.diagnostics
: [
{
code: "parse.unknown",
message:
error instanceof Error
? error.message
: "Unknown parser failure.",
severity: "error",
},
],
};
}
self.postMessage(response);
};
export {};
+130
View File
@@ -0,0 +1,130 @@
import { expect, test, type Page, type Response } from "@playwright/test";
const ORIGIN = "http://127.0.0.1:4173";
async function localOnly(page: Page) {
const external: string[] = [];
await page.route("**/*", async (route) => {
const url = new URL(route.request().url());
if (url.origin !== ORIGIN) {
external.push(url.href);
await route.abort();
} else await route.continue();
});
return external;
}
function collectErrors(page: Page): string[] {
const errors: string[] = [];
page.on("pageerror", (error) => errors.push(error.message));
page.on("console", (message) => {
if (message.type() === "error") errors.push(message.text());
});
return errors;
}
test("runs its parser worker from a nested path without external requests", async ({
page,
}) => {
const errors = collectErrors(page);
const external = await localOnly(page);
const workerResponses: Response[] = [];
page.on("response", (response) => {
if (/data\.worker-[^/]+\.js$/u.test(new URL(response.url()).pathname))
workerResponses.push(response);
});
await page.goto("/deep/nested/data/");
await expect(page.locator(".workbench h1")).toHaveText("Data Tools");
await expect(page.getByText(/Parsed as JSON/iu)).toBeVisible();
expect(external).toEqual([]);
expect(errors).toEqual([]);
expect(workerResponses).toHaveLength(1);
const worker = workerResponses[0];
expect(worker).toBeDefined();
expect(new URL(worker!.url()).pathname).toMatch(
/^\/deep\/nested\/data\/assets\/data\.worker-[^/]+\.js$/u,
);
expect(worker!.headers()["content-type"]).toContain("text/javascript");
expect(worker!.headers()["cache-control"]).toContain("immutable");
});
test("navigates tree and safe query views", async ({ page }) => {
await page.goto("/deep/nested/data/");
await expect(page.getByText(/Parsed as JSON/iu)).toBeVisible();
await page.getByRole("tab", { name: /Tree/iu }).click();
await expect(
page.getByRole("treeitem").filter({ hasText: "exactInteger" }),
).toBeVisible();
await page.getByRole("tab", { name: /Query/iu }).click();
await page.getByLabel("Query syntax").selectOption("path");
await expect(page.getByText("4 matches")).toBeVisible();
await expect(page.getByText("detect", { exact: true })).toBeVisible();
});
test("opens CSV locally, projects a table and neutralises spreadsheet formulas", async ({
page,
}) => {
await page.goto("/deep/nested/data/");
await page.getByTestId("data-file-input").setInputFiles({
name: "records.csv",
mimeType: "text/csv",
buffer: Buffer.from("name,value\nAda,001\nFormula,=2+2", "utf8"),
});
await expect(page.getByText(/Parsed as CSV/iu)).toBeVisible();
await page.getByRole("tab", { name: /Table/iu }).click();
await page.getByText("Use first row as headings").click();
const table = page.getByRole("region", { name: "Tabular data preview" });
await expect(table.getByRole("columnheader", { name: "name" })).toBeVisible();
await expect(table.getByRole("cell", { name: "001" })).toBeVisible();
await page.getByRole("tab", { name: /Convert/iu }).click();
await page.getByLabel("Output format").selectOption("csv");
await expect(page.getByTestId("conversion-output")).toHaveValue(
/Formula,'=2\+2/u,
);
await expect(
page.getByText(/Potential spreadsheet formulas/iu),
).toBeVisible();
const downloadPromise = page.waitForEvent("download");
await page.getByRole("button", { name: "Download" }).click();
expect((await downloadPromise).suggestedFilename()).toBe("converted.csv");
});
test("shows a hardened XML error while retaining the last successful model", async ({
page,
}) => {
await page.goto("/deep/nested/data/");
await expect(page.getByText(/Parsed as JSON/iu)).toBeVisible();
await page.getByTestId("format-select").selectOption("xml");
await page
.getByTestId("source-editor")
.fill('<!DOCTYPE root [<!ENTITY x "bad">]><root>&x;</root>');
await expect(page.getByText("xml.doctype-rejected")).toBeVisible();
await page.getByRole("tab", { name: /Tree/iu }).click();
await expect(
page.getByRole("treeitem").filter({ hasText: "project" }),
).toBeVisible();
});
test("serves the release identity and hardened headers", async ({
request,
}) => {
const index = await request.get("/deep/nested/data/");
expect(index.ok()).toBe(true);
expect(index.headers()["content-security-policy"]).toContain(
"default-src 'self'",
);
expect(index.headers()["content-security-policy"]).toContain(
"worker-src 'self' blob:",
);
expect(await index.text()).not.toMatch(/\b(?:src|href)=["']\//u);
const manifest = await request.get("/deep/nested/data/toolbox-app.json");
await expect(manifest.json()).resolves.toMatchObject({
id: "de.add-ideas.data-tools",
version: "0.1.0",
entry: "./",
});
});
+63
View File
@@ -0,0 +1,63 @@
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { App } from "../../src/App";
async function renderReady() {
vi.stubGlobal(
"fetch",
vi.fn(async () => new Response("Not found", { status: 404 })),
);
render(<App />);
await screen.findByText(/Parsed as JSON/iu, {}, { timeout: 2_000 });
}
describe("Data Tools workbench", () => {
it("renders the local shell and exact JSON summary", async () => {
await renderReady();
expect(screen.getAllByRole("heading", { name: "Data Tools" })).toHaveLength(
2,
);
expect(screen.getByText("Browser-local")).toBeVisible();
expect(screen.getByText("native")).toBeVisible();
});
it("keeps the previous model while a replacement is invalid", async () => {
await renderReady();
const user = userEvent.setup();
const editor = screen.getByTestId("source-editor");
await user.clear(editor);
await user.type(editor, '{{"broken":');
await screen.findByText(
/Unexpected|invalid|property/iu,
{},
{ timeout: 2_000 },
);
await user.click(screen.getByRole("tab", { name: /Tree/iu }));
expect(screen.getByText("project")).toBeVisible();
});
it("runs safe wildcard queries", async () => {
await renderReady();
const user = userEvent.setup();
await user.click(screen.getByRole("tab", { name: /Query/iu }));
await user.selectOptions(screen.getByLabelText("Query syntax"), "path");
expect(screen.getByText("4 matches")).toBeVisible();
expect(screen.getByText("detect")).toBeVisible();
});
it("converts to CSV and displays disclosure", async () => {
await renderReady();
const user = userEvent.setup();
await user.click(screen.getByRole("tab", { name: /Convert/iu }));
await user.selectOptions(screen.getByLabelText("Output format"), "csv");
await waitFor(() =>
expect(
(screen.getByTestId("conversion-output") as HTMLTextAreaElement).value,
).toContain("Key,Value"),
);
expect(
screen.getByRole("heading", { name: "Conversion report" }),
).toBeVisible();
});
});
+187
View File
@@ -0,0 +1,187 @@
import { describe, expect, it } from "vitest";
import { convertDocument } from "../../src/core/convert";
import { DATA_LIMITS } from "../../src/core/limits";
import { objectValue } from "../../src/core/model";
import { parseDataDocument } from "../../src/core/parse";
import { DataToolsError } from "../../src/core/types";
describe("bounded format parsers", () => {
it("preserves JSON number lexemes exactly", () => {
const source =
'{"integer":9007199254740993123456789,"decimal":0.123456789012345678901}';
const document = parseDataDocument({ source, format: "json" });
expect(objectValue(document.root, "integer")).toMatchObject({
type: "number",
raw: "9007199254740993123456789",
representation: "exact",
});
expect(convertDocument(document, "json").text).toContain(
"0.123456789012345678901",
);
});
it("rejects duplicate and prototype-affecting JSON keys", () => {
expect(() =>
parseDataDocument({ source: '{"a":1,"a":2}', format: "json" }),
).toThrow(DataToolsError);
expect(() =>
parseDataDocument({ source: '{"__proto__":1}', format: "json" }),
).toThrow(/dangerous object key/iu);
});
it("uses YAML 1.2 core semantics and rejects custom tags and merges", () => {
const document = parseDataDocument({
source: "answer: yes\nactual: true\ninteger: 9007199254740993\n",
format: "yaml",
});
expect(objectValue(document.root, "answer")).toEqual({
type: "string",
value: "yes",
});
expect(objectValue(document.root, "integer")).toMatchObject({
type: "number",
raw: "9007199254740993",
});
expect(() =>
parseDataDocument({ source: "value: !custom test", format: "yaml" }),
).toThrow(/tag/iu);
expect(() =>
parseDataDocument({
source: "base: &base\n a: 1\ncopy:\n <<: *base\n",
format: "yaml",
}),
).toThrow(/merge/iu);
});
it("keeps TOML integers exact and models date/time values", () => {
const document = parseDataDocument({
source:
'title = "example"\nlarge = 9007199254740993\ncreated = 2026-09-01T10:15:30Z\n',
format: "toml",
});
expect(objectValue(document.root, "large")).toMatchObject({
type: "number",
raw: "9007199254740993",
representation: "bigint",
});
expect(objectValue(document.root, "created")).toMatchObject({
type: "date",
dateKind: "offset-date-time",
});
});
it("rejects XML declarations with active resolution semantics", () => {
expect(() =>
parseDataDocument({
source: '<!DOCTYPE root [<!ENTITY x "expanded">]><root>&x;</root>',
format: "xml",
}),
).toThrow(/DOCTYPE/iu);
expect(() =>
parseDataDocument({
source:
'<root xmlns:xi="http://www.w3.org/2001/XInclude"><xi:include href="file:///etc/passwd"/></root>',
format: "xml",
}),
).toThrow(/XInclude/iu);
expect(() =>
parseDataDocument({
source:
'<root xmlns:load="http://www.w3.org/2001/XInclude"><load:include href="https://example.test/private"/></root>',
format: "xml",
}),
).toThrow(/XInclude/iu);
});
it("preserves XML namespaces, attributes and ordered children explicitly", () => {
const document = parseDataDocument({
source:
'<n:root xmlns:n="urn:test" id="7">before<n:item>one</n:item><!--note-->after</n:root>',
format: "xml",
});
expect(document.model).toBe("xml-explicit");
expect(objectValue(document.root, "name")).toEqual({
type: "string",
value: "n:root",
});
expect(objectValue(document.root, "namespace")).toEqual({
type: "string",
value: "urn:test",
});
expect(convertDocument(document, "xml").text).toContain(
"<n:item>one</n:item>",
);
});
it("parses delimited data as strings, including quoted fields", () => {
const document = parseDataDocument({
source: 'name,value\r\nAda,"1,200"\r\nZero,001',
format: "csv",
});
expect(document.model).toBe("tabular");
expect(document.root).toMatchObject({ type: "array" });
expect(document.diagnostics).toEqual(
expect.arrayContaining([
expect.objectContaining({ code: "delimited.strings" }),
]),
);
});
it("preflights delimited dimensions before allocating the parsed table", () => {
const row = new Array(DATA_LIMITS.maxColumns).fill("x").join(",");
const source = new Array(
Math.floor(DATA_LIMITS.maxCells / DATA_LIMITS.maxColumns) + 2,
)
.fill(row)
.join("\n");
expect(() => parseDataDocument({ source, format: "csv" })).toThrow(
/Cell count/iu,
);
});
it("reports an exact NDJSON line and ignores blank lines", () => {
const document = parseDataDocument({
source: '{"id":1}\n\n{"id":2}\n',
format: "ndjson",
});
expect(document.root).toMatchObject({ type: "array", items: [{}, {}] });
expect(document.diagnostics).toEqual(
expect.arrayContaining([
expect.objectContaining({ code: "ndjson.blank-lines" }),
]),
);
expect(() =>
parseDataDocument({
source: '{"id":1}\n{"id":}\n',
format: "ndjson",
}),
).toThrow(/line 2/iu);
});
it("detects by content or filename and discloses a mismatch", () => {
expect(
parseDataDocument({
source: '{"ok":true}\n{"ok":false}',
format: "auto",
}).format,
).toBe("ndjson");
const mismatch = parseDataDocument({
source: '{"looks":"json"}',
format: "auto",
filename: "values.yaml",
});
expect(mismatch.format).toBe("yaml");
expect(mismatch.diagnostics).toEqual(
expect.arrayContaining([
expect.objectContaining({ code: "format.possible-mismatch" }),
]),
);
});
it("rejects inputs deeper than the structural cap before modelling", () => {
const source = `${"[".repeat(DATA_LIMITS.maxDepth + 1)}0${"]".repeat(DATA_LIMITS.maxDepth + 1)}`;
expect(() => parseDataDocument({ source, format: "json" })).toThrow(
/depth/iu,
);
});
});
+117
View File
@@ -0,0 +1,117 @@
import { describe, expect, it } from "vitest";
import { convertDocument } from "../../src/core/convert";
import { DATA_LIMITS } from "../../src/core/limits";
import { parseDataDocument } from "../../src/core/parse";
import {
flattenRows,
queryPointer,
querySafePath,
tableFromNode,
} from "../../src/core/query";
const document = parseDataDocument({
source:
'{"a/b":{"~key":7},"people":[{"name":"Ada","role":"math"},{"name":"Grace","role":"code"}]}',
format: "json",
});
describe("safe data projections", () => {
it("resolves RFC 6901 escaping", () => {
expect(queryPointer(document.root, "/a~1b/~0key")[0]?.node).toMatchObject({
type: "number",
raw: "7",
});
});
it("supports a deliberately small non-evaluating path syntax", () => {
expect(querySafePath(document.root, "$.people[*].name")).toHaveLength(2);
expect(
querySafePath(document.root, "$['a/b']['~key']")[0]?.node,
).toMatchObject({ raw: "7" });
expect(() => querySafePath(document.root, "$..name")).toThrow(
/unsupported path syntax/iu,
);
expect(() => querySafePath(document.root, "$.people[?(@.role)]")).toThrow(
/filters/iu,
);
expect(() =>
queryPointer(
document.root,
`/${"a".repeat(DATA_LIMITS.maxQueryCharacters)}`,
),
).toThrow(/Query character count/iu);
});
it("projects record arrays and flattened scalar leaves", () => {
const people = queryPointer(document.root, "/people")[0]?.node;
expect(people && tableFromNode(people)).toMatchObject({
columns: ["name", "role"],
rows: [
["Ada", "math"],
["Grace", "code"],
],
});
expect(flattenRows(document.root).rows).toEqual(
expect.arrayContaining([["/a~1b/~0key", "number", "7"]]),
);
});
});
describe("explicit conversions", () => {
it("neutralises spreadsheet formula cells only when requested", () => {
const csv = parseDataDocument({
source: 'name,value\ncalc,"=2+2"\nsafe,text',
format: "csv",
});
const protectedOutput = convertDocument(csv, "csv", {
spreadsheetSafe: true,
});
expect(protectedOutput.text).toContain("'=2+2");
expect(protectedOutput.events).toEqual(
expect.arrayContaining([
expect.objectContaining({ code: "csv.formula-neutralized" }),
]),
);
const raw = convertDocument(csv, "csv", { spreadsheetSafe: false });
expect(raw.text).toContain("=2+2");
expect(raw.events).toEqual(
expect.arrayContaining([
expect.objectContaining({ code: "csv.formula-unchecked" }),
]),
);
});
it("turns unsafe decimals into strings rather than silently rounding", () => {
const precise = parseDataDocument({
source: '{"value":0.1234567890123456789012345}',
format: "json",
});
const yaml = convertDocument(precise, "yaml");
expect(yaml.events).toEqual(
expect.arrayContaining([
expect.objectContaining({ code: "yaml.unsafe-number" }),
]),
);
expect(yaml.text).toContain("0.1234567890123456789012345");
});
it("reports null and root coercion when targeting TOML", () => {
const value = parseDataDocument({ source: "null", format: "json" });
const result = convertDocument(value, "toml");
expect(result.text).toContain('value = ""');
expect(result.events.map((event) => event.code)).toEqual(
expect.arrayContaining(["toml.null", "toml.root-table"]),
);
});
it("converts ordinary data to XML using a disclosed stable convention", () => {
const result = convertDocument(document, "xml");
expect(result.text).toContain("<people>");
expect(result.text).toContain("<name>Ada</name>");
expect(result.events).toEqual(
expect.arrayContaining([
expect.objectContaining({ code: "xml.mapping" }),
]),
);
});
});
+27
View File
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"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"]
}
+11
View File
@@ -0,0 +1,11 @@
{
"files": [],
"references": [
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.node.json"
}
]
}
+24
View File
@@ -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"
]
}
+16
View File
@@ -0,0 +1,16 @@
/// <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,
maxWorkers: 2,
restoreMocks: true,
exclude: ["tests/browser/**", "node_modules/**", "dist/**"],
},
});