1 Commits
Author SHA1 Message Date
zemion 46fc10f745 Release Diff Tools 0.2.0
Verify / verify (push) Canceled after 0s
2026-09-02 04:43:16 +02:00
37 changed files with 2722 additions and 455 deletions
+39
View File
@@ -0,0 +1,39 @@
name: Verify
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
concurrency:
group: verify-${{ gitea.repository }}-${{ gitea.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
verify:
runs-on: ubuntu-latest
timeout-minutes: 45
env:
CI: "true"
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: npm
- name: Select declared npm version
run: npm install --global npm@11.17.0
- name: Install dependencies
run: npm ci
- name: Audit runtime dependencies
run: npm audit --omit=dev --audit-level=moderate
- name: Check, test, and build
run: npm run check
- name: Install browser engines
run: npx playwright install --with-deps chromium firefox webkit
- name: Browser tests
run: npm run test:browser
+13
View File
@@ -1,5 +1,18 @@
# Changelog
## 0.2.0 - 2026-09-02
- Adopted `@add-ideas/toolbox-helpers` 0.2.0 for deterministic byte-size
display, safe Blob downloads and the shared worker-job protocol.
- Added a 15-second hard disposable-worker deadline with a distinct structured
diagnostic while retaining the algorithm-level two-second diff budget.
- Added bounded local directory manifests with collision-safe relative paths,
two-file SHA-256 concurrency, progress, cancellation and portable comparison.
- Added bounded line-oriented three-way merge with non-overlap combination,
explicit ours/base/theirs conflicts and a machine-readable merge report.
- Retained loss-aware semantic JSON, CSV/TSV and hardened XML comparisons beside
the new directory and merge workspaces.
## 0.1.0 - 2026-09-01
- Added line, word, code-point and grapheme text comparison with exact newline state and unified patch export.
+7 -5
View File
@@ -2,23 +2,25 @@
Compare text and structured data locally in the browser.
Diff Tools is a standalone, local-first application in the [add·ideas Toolbox](https://git.add-ideas.de/lotobo/toolbox-portal). Inputs are processed in a disposable browser worker and are never uploaded by the application.
Diff Tools is a standalone, local-first application in the [add·ideas Toolbox](https://git.add-ideas.de/lotobo/toolbox-portal). Inputs are processed through the shared cancellable disposable-worker protocol, with an algorithm budget and a 15-second hard worker deadline, and are never uploaded by the application.
## Version 0.1 scope
## Version 0.2 scope
- Text diff by line, word, Unicode code point or grapheme cluster, with exact LF, CRLF, CR and final-newline state.
- Explicit text comparison rules for case, whitespace, line endings, final newline and Unicode normalization. Normalized differences stay visible.
- Semantic JSON comparison with duplicate-key rejection, exact decimal numbers, object-order reporting and RFC 6902 output when representable.
- Namespace-aware XML comparison with visible prefix, attribute-order, comment, whitespace and CDATA normalization. DOCTYPE, entity declarations and XInclude are rejected.
- CSV and TSV comparison by one or more unique key columns, including duplicate-key diagnostics, string-preserving fields and visible column/row order changes.
- Build deterministic relative-path directory manifests with local SHA-256 hashing, bounded two-file concurrency and conservative collision checks; export/import manifests and compare them without retaining file contents.
- Perform a bounded, line-preserving three-way text merge from base/ours/theirs, with non-overlapping edits combined and explicit ours/base/theirs markers plus a JSON report for every conflict.
- Unified and side-by-side views, an exact unified text patch and a portable, versioned JSON report.
- Stable-last-result interaction: invalid or unfinished input does not blank the previous successful result.
This version intentionally does not compare images, binary documents, directories or archives.
This version does not interpret images, binary documents or archives. Directory comparison is content-digest based and cannot represent empty directories because browser directory selection exposes files only. Three-way merge is textual rather than a semantic JSON/XML merge.
## Safety limits
Each input is limited to 8 MiB and 4 million characters. Parsing and output also have explicit row, cell, token, node, nesting, edit-count, time and display limits. Imported values are rendered as React text nodes; parser-provided HTML is never inserted. See [privacy and security](docs/PRIVACY-SECURITY.md).
Each ordinary or merge input is limited to 8 MiB and 4 million characters. Directory manifests are limited to 5,000 files, 512 MiB total, 256 MiB per file, 4,096-character relative paths and two concurrent hashes. Parsing and output also have explicit row, cell, token, node, nesting, edit-count, conflict-count, time and display limits. Imported values are rendered as React text nodes; parser-provided HTML is never inserted. See [privacy and security](docs/PRIVACY-SECURITY.md).
## Development
@@ -38,7 +40,7 @@ The browser suite builds and serves the app below `/deep/nested/diff/`, blocks e
npm run release:artifact
```
This creates deterministic `release/diff-tools-0.1.0.zip` and `.sha256` files after all validation gates pass.
This creates deterministic `release/diff-tools-0.2.0.zip` and `.sha256` files after all validation gates pass.
## Licence
+2 -2
View File
@@ -1,7 +1,7 @@
# Corresponding source
The corresponding source for Diff Tools 0.1.0 is available at:
The corresponding source for Diff Tools 0.2.0 is available at:
https://git.add-ideas.de/lotobo/diff-tools/src/tag/v0.1.0
https://git.add-ideas.de/lotobo/diff-tools/src/tag/v0.2.0
Build with Node.js 22, npm 11, `npm ci`, and `npm run release:artifact`.
+10 -9
View File
@@ -2,14 +2,15 @@
Diff Tools is GPL-3.0-or-later. Its direct runtime dependencies retain their own licences:
| Package | Pinned version | Licence | Purpose |
| -------------------------------- | -------------: | ------------ | ---------------------------------------------- |
| `@add-ideas/toolbox-contract` | 0.2.3 | Apache-2.0 | Manifest validation |
| `@add-ideas/toolbox-shell-react` | 0.2.3 | Apache-2.0 | Shared Toolbox shell |
| `@xmldom/xmldom` | 0.9.12 | MIT | Inert XML DOM parsing |
| `diff` | 9.0.0 | BSD-3-Clause | Bounded sequence alignment and unified patches |
| `lossless-json` | 4.3.1 | MIT | Exact-decimal JSON parsing and serialization |
| `papaparse` | 5.7.0 | MIT | CSV and TSV parsing |
| `react` / `react-dom` | 19.2.8 | MIT | User interface |
| Package | Pinned version | Licence | Purpose |
| -------------------------------- | -------------: | ---------------- | ---------------------------------------------- |
| `@add-ideas/toolbox-contract` | 0.3.0 | Apache-2.0 | Manifest validation |
| `@add-ideas/toolbox-helpers` | 0.2.0 | GPL-3.0-or-later | Shared local-first utility primitives |
| `@add-ideas/toolbox-shell-react` | 0.3.0 | Apache-2.0 | Shared Toolbox shell |
| `@xmldom/xmldom` | 0.9.12 | MIT | Inert XML DOM parsing |
| `diff` | 9.0.0 | BSD-3-Clause | Bounded sequence alignment and unified patches |
| `lossless-json` | 4.3.1 | MIT | Exact-decimal JSON parsing and serialization |
| `papaparse` | 5.7.0 | MIT | CSV and TSV parsing |
| `react` / `react-dom` | 19.2.8 | MIT | User interface |
Release artifacts include the complete licence texts collected from every locked runtime package at `LICENSES/npm-runtime-licenses.txt`.
+1 -1
View File
@@ -1,6 +1,6 @@
# Accessibility
The workbench uses labelled native text areas, selects, checkboxes, file inputs and buttons. Comparison modes and result views are exposed as tab lists, status and diagnostic changes use live regions, and structured results use list or table semantics.
The workbench uses labelled native text areas, selects, checkboxes, file inputs and buttons. Comparison modes and result views are exposed as labelled pressed-state button groups, status and diagnostic changes use live regions, and structured results use list or table semantics.
Change kinds are written in text and indicated by `+`/`` markers, not colour alone. Exact CR, LF and tab characters have visible glyphs. Focus indicators remain visible in light, dark and system themes, and controls meet a minimum 2.55 rem target height.
+10 -3
View File
@@ -3,7 +3,10 @@
Diff Tools is a static React application with a relocatable `./` build. Its comparison pipeline is deliberately separated from the view:
1. The workbench captures strings or decodes a selected file as strict UTF-8 after a byte-size check.
2. A fresh module worker receives a plain comparison request. Changing input cancels and terminates the preceding worker; the last successful result remains on screen until a replacement succeeds.
2. A fresh module worker receives a typed shared worker-job request. Changing
input cancels and terminates the preceding worker; job IDs exclude stale
messages, and a 15-second hard deadline bounds the whole worker. The last
successful result remains on screen until a replacement succeeds.
3. A mode-specific pure comparator produces display rows and diagnostics. Normalized rows are first-class output, not discarded state.
4. The orchestrator adds exact input metadata, a bounded unified patch and a schema-labelled portable report.
5. React renders values as text. The app never consumes or inserts HTML produced by a diff or parser library.
@@ -16,7 +19,11 @@ When `Worker` is unavailable, such as in unit tests, the same pure comparator ru
- JSON uses `lossless-json`, rejects duplicate and prototype-affecting keys, and compares numbers without converting to IEEE-754. Object member order is semantically ignored but reported.
- XML rejects active declaration/include syntax and preflights structure before `@xmldom/xmldom` builds an inert DOM. Elements and attributes compare by expanded name when selected.
- CSV/TSV uses Papa Parse in string mode. Unique composite keys align rows; no spreadsheet type inference is performed.
- Directory manifests strip the one common browser-selected root, validate every relative path and conservative case/Unicode collision key, then hash file bytes with SHA-256 under count, per-file, aggregate and concurrency ceilings. The sorted, versioned JSON artifact can be compared later without the files.
- Three-way merge independently derives bounded token edits from base to ours and base to theirs. Non-overlapping regions compose; overlapping regions are compared against each other and the base before conflict markers are emitted. It does not claim semantic structured-data merging.
All report and patch formats are generated locally. `de.add-ideas.diff-tools.report.v1` is the portable report schema identifier.
All report and patch formats are generated locally. `de.add-ideas.diff-tools.report.v1`, `de.add-ideas.diff-tools.directory-manifest.v1` and `de.add-ideas.diff-tools.merge-report.v1` identify the portable artifacts.
The planned shared `@add-ideas/toolbox-helpers` package is not yet published at a compatible version, so v0.1 keeps its bounded domain functions inside `src/core`. They can be extracted without changing the worker protocol or report schema.
Diff algorithms, semantic models and reports remain bounded domain functions in
`src/core`. Generic byte-size display, safe Blob downloads and cancellable
worker lifecycle come from `@add-ideas/toolbox-helpers` 0.2.0.
+3
View File
@@ -13,6 +13,9 @@ The production CSP permits same-origin scripts and workers and blocks objects, f
- XML containing DOCTYPE, entity declaration or XInclude syntax is rejected before DOM parsing. A lexical preflight rejects excessive element count or nesting before DOM construction.
- JSON rejects duplicate keys and the prototype-affecting keys `__proto__`, `prototype` and `constructor`.
- CSV/TSV fields remain strings; formulas are displayed as text and are not evaluated.
- Directory hashing rejects traversal, absolute/control-laden and case/Unicode-colliding relative paths. SHA-256 reads use bounded concurrency, file/count/aggregate ceilings and an abort signal.
- Imported manifests are schema-, path-, digest-, order- and total-validated before comparison. Directory names and digests are sensitive metadata and should be reviewed before sharing.
- Three-way inputs use the same text ceilings plus an explicit conflict cap; conflict labels have CR/LF removed before entering marker lines.
- Imported strings are rendered through React text nodes and form controls. No library-generated HTML, imported markup or script is inserted into the document.
These controls bound this tool's work; they are not a general-purpose sanitizer and do not make imported data safe for another application.
+24 -16
View File
@@ -1,16 +1,17 @@
{
"name": "diff-tools",
"version": "0.1.0",
"version": "0.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "diff-tools",
"version": "0.1.0",
"version": "0.2.0",
"license": "GPL-3.0-or-later",
"dependencies": {
"@add-ideas/toolbox-contract": "0.2.3",
"@add-ideas/toolbox-shell-react": "0.2.3",
"@add-ideas/toolbox-contract": "0.3.0",
"@add-ideas/toolbox-helpers": "0.2.0",
"@add-ideas/toolbox-shell-react": "0.3.0",
"@xmldom/xmldom": "0.9.12",
"diff": "9.0.0",
"lossless-json": "4.3.1",
@@ -19,7 +20,7 @@
"react-dom": "19.2.8"
},
"devDependencies": {
"@add-ideas/toolbox-testkit": "0.2.3",
"@add-ideas/toolbox-testkit": "0.3.0",
"@eslint/js": "10.0.1",
"@playwright/test": "1.62.1",
"@testing-library/jest-dom": "6.9.1",
@@ -46,18 +47,25 @@
}
},
"node_modules/@add-ideas/toolbox-contract": {
"version": "0.2.3",
"resolved": "https://git.add-ideas.de/api/packages/lotobo/npm/%40add-ideas%2Ftoolbox-contract/-/0.2.3/toolbox-contract-0.2.3.tgz",
"integrity": "sha512-T0PVSuMT40GjTDfQJhEEY3ZawQq8zz1/ry95JdKI6W39CdLacaRXdGnEpDCMHt+jUbf1Jz7Nat/M5dFCgKVM9A==",
"version": "0.3.0",
"resolved": "https://git.add-ideas.de/api/packages/lotobo/npm/%40add-ideas%2Ftoolbox-contract/-/0.3.0/toolbox-contract-0.3.0.tgz",
"integrity": "sha512-dKrK7BjOFwqJaBfJuhKxZKIld4sH0AKjEn6a0yLnbdMUFY+fFv4VSLGV2tNSBD016gumc2iNqOjUj/ld7x4rtA==",
"license": "Apache-2.0"
},
"node_modules/@add-ideas/toolbox-helpers": {
"version": "0.2.0",
"license": "GPL-3.0-or-later",
"engines": {
"node": ">=22"
}
},
"node_modules/@add-ideas/toolbox-shell-react": {
"version": "0.2.3",
"resolved": "https://git.add-ideas.de/api/packages/lotobo/npm/%40add-ideas%2Ftoolbox-shell-react/-/0.2.3/toolbox-shell-react-0.2.3.tgz",
"integrity": "sha512-DT5lQDH48BFkFcmFLZnQh7+Cm73JzBPcmp5WzUXypfkUXpEyDYHzaXgmW4kZ0edSwh4RK4sPmx+JPtK0X4aKCQ==",
"version": "0.3.0",
"resolved": "https://git.add-ideas.de/api/packages/lotobo/npm/%40add-ideas%2Ftoolbox-shell-react/-/0.3.0/toolbox-shell-react-0.3.0.tgz",
"integrity": "sha512-74p6JzAOG0YCAKdlc1hLofV4ZIko7vb448S75cIiM88PKm93EHl5VD7g8YVyfM56Ui97UY9dmy+Whiq4sGzpsg==",
"license": "Apache-2.0",
"dependencies": {
"@add-ideas/toolbox-contract": "0.2.3"
"@add-ideas/toolbox-contract": "0.3.0"
},
"peerDependencies": {
"react": ">=18 <20",
@@ -65,13 +73,13 @@
}
},
"node_modules/@add-ideas/toolbox-testkit": {
"version": "0.2.3",
"resolved": "https://git.add-ideas.de/api/packages/lotobo/npm/%40add-ideas%2Ftoolbox-testkit/-/0.2.3/toolbox-testkit-0.2.3.tgz",
"integrity": "sha512-sq1MwhKWfFKen+N+124hl74qQimRSvmQ9sOU7jdcI+2qCKZ67+2B8rWyezeV80uTFu4Jv6deHksfYQ/tKNV6XQ==",
"version": "0.3.0",
"resolved": "https://git.add-ideas.de/api/packages/lotobo/npm/%40add-ideas%2Ftoolbox-testkit/-/0.3.0/toolbox-testkit-0.3.0.tgz",
"integrity": "sha512-4Fk+oSvZFspOMIXr8Xy040nhAaBsIQAzsGyXWSpjn3+k3yBKq7nB1r5zCHhsXzfdLzvPDAx2KcmSNOhM330D9w==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@add-ideas/toolbox-contract": "0.2.3"
"@add-ideas/toolbox-contract": "0.3.0"
},
"bin": {
"toolbox-check": "dist/cli.js"
+6 -5
View File
@@ -1,7 +1,7 @@
{
"name": "diff-tools",
"version": "0.1.0",
"description": "Compare text and structured data locally in the browser.",
"version": "0.2.0",
"description": "Compare files and directories or perform bounded three-way merges locally.",
"license": "GPL-3.0-or-later",
"author": "Albrecht Degering",
"repository": {
@@ -39,8 +39,9 @@
"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",
"@add-ideas/toolbox-contract": "0.3.0",
"@add-ideas/toolbox-helpers": "0.2.0",
"@add-ideas/toolbox-shell-react": "0.3.0",
"@xmldom/xmldom": "0.9.12",
"diff": "9.0.0",
"lossless-json": "4.3.1",
@@ -49,7 +50,7 @@
"react-dom": "19.2.8"
},
"devDependencies": {
"@add-ideas/toolbox-testkit": "0.2.3",
"@add-ideas/toolbox-testkit": "0.3.0",
"@eslint/js": "10.0.1",
"@playwright/test": "1.62.1",
"@testing-library/jest-dom": "6.9.1",
+20 -2
View File
@@ -15,7 +15,25 @@ export default defineConfig({
timeout: 180_000,
},
projects: [
{ name: "chromium", use: { ...devices["Desktop Chrome"] } },
{ name: "firefox", use: { ...devices["Desktop Firefox"] } },
{
name: "chromium",
testIgnore: /responsive\.spec\.ts/,
use: { ...devices["Desktop Chrome"] },
},
{
name: "firefox",
testIgnore: /responsive\.spec\.ts/,
use: { ...devices["Desktop Firefox"] },
},
{
name: "webkit",
testIgnore: /responsive\.spec\.ts/,
use: { ...devices["Desktop Safari"] },
},
{
name: "mobile-chromium",
testMatch: /responsive\.spec\.ts/,
use: { ...devices["Pixel 5"] },
},
],
});
+13
View File
@@ -1,5 +1,18 @@
# Changelog
## 0.2.0 - 2026-09-02
- Adopted `@add-ideas/toolbox-helpers` 0.2.0 for deterministic byte-size
display, safe Blob downloads and the shared worker-job protocol.
- Added a 15-second hard disposable-worker deadline with a distinct structured
diagnostic while retaining the algorithm-level two-second diff budget.
- Added bounded local directory manifests with collision-safe relative paths,
two-file SHA-256 concurrency, progress, cancellation and portable comparison.
- Added bounded line-oriented three-way merge with non-overlap combination,
explicit ours/base/theirs conflicts and a machine-readable merge report.
- Retained loss-aware semantic JSON, CSV/TSV and hardened XML comparisons beside
the new directory and merge workspaces.
## 0.1.0 - 2026-09-01
- Added line, word, code-point and grapheme text comparison with exact newline state and unified patch export.
+683 -2
View File
@@ -1,5 +1,5 @@
==============================================================================
@add-ideas/toolbox-contract@0.2.3
@add-ideas/toolbox-contract@0.3.0
Declared licence: Apache-2.0
==============================================================================
--- LICENSE ---
@@ -198,7 +198,688 @@ Declared licence: Apache-2.0
==============================================================================
@add-ideas/toolbox-shell-react@0.2.3
@add-ideas/toolbox-helpers@0.2.0
Declared licence: GPL-3.0-or-later
==============================================================================
--- LICENSE ---
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>.
==============================================================================
@add-ideas/toolbox-shell-react@0.3.0
Declared licence: Apache-2.0
==============================================================================
--- LICENSE ---
+7 -5
View File
@@ -2,23 +2,25 @@
Compare text and structured data locally in the browser.
Diff Tools is a standalone, local-first application in the [add·ideas Toolbox](https://git.add-ideas.de/lotobo/toolbox-portal). Inputs are processed in a disposable browser worker and are never uploaded by the application.
Diff Tools is a standalone, local-first application in the [add·ideas Toolbox](https://git.add-ideas.de/lotobo/toolbox-portal). Inputs are processed through the shared cancellable disposable-worker protocol, with an algorithm budget and a 15-second hard worker deadline, and are never uploaded by the application.
## Version 0.1 scope
## Version 0.2 scope
- Text diff by line, word, Unicode code point or grapheme cluster, with exact LF, CRLF, CR and final-newline state.
- Explicit text comparison rules for case, whitespace, line endings, final newline and Unicode normalization. Normalized differences stay visible.
- Semantic JSON comparison with duplicate-key rejection, exact decimal numbers, object-order reporting and RFC 6902 output when representable.
- Namespace-aware XML comparison with visible prefix, attribute-order, comment, whitespace and CDATA normalization. DOCTYPE, entity declarations and XInclude are rejected.
- CSV and TSV comparison by one or more unique key columns, including duplicate-key diagnostics, string-preserving fields and visible column/row order changes.
- Build deterministic relative-path directory manifests with local SHA-256 hashing, bounded two-file concurrency and conservative collision checks; export/import manifests and compare them without retaining file contents.
- Perform a bounded, line-preserving three-way text merge from base/ours/theirs, with non-overlapping edits combined and explicit ours/base/theirs markers plus a JSON report for every conflict.
- Unified and side-by-side views, an exact unified text patch and a portable, versioned JSON report.
- Stable-last-result interaction: invalid or unfinished input does not blank the previous successful result.
This version intentionally does not compare images, binary documents, directories or archives.
This version does not interpret images, binary documents or archives. Directory comparison is content-digest based and cannot represent empty directories because browser directory selection exposes files only. Three-way merge is textual rather than a semantic JSON/XML merge.
## Safety limits
Each input is limited to 8 MiB and 4 million characters. Parsing and output also have explicit row, cell, token, node, nesting, edit-count, time and display limits. Imported values are rendered as React text nodes; parser-provided HTML is never inserted. See [privacy and security](docs/PRIVACY-SECURITY.md).
Each ordinary or merge input is limited to 8 MiB and 4 million characters. Directory manifests are limited to 5,000 files, 512 MiB total, 256 MiB per file, 4,096-character relative paths and two concurrent hashes. Parsing and output also have explicit row, cell, token, node, nesting, edit-count, conflict-count, time and display limits. Imported values are rendered as React text nodes; parser-provided HTML is never inserted. See [privacy and security](docs/PRIVACY-SECURITY.md).
## Development
@@ -38,7 +40,7 @@ The browser suite builds and serves the app below `/deep/nested/diff/`, blocks e
npm run release:artifact
```
This creates deterministic `release/diff-tools-0.1.0.zip` and `.sha256` files after all validation gates pass.
This creates deterministic `release/diff-tools-0.2.0.zip` and `.sha256` files after all validation gates pass.
## Licence
+2 -2
View File
@@ -1,7 +1,7 @@
# Corresponding source
The corresponding source for Diff Tools 0.1.0 is available at:
The corresponding source for Diff Tools 0.2.0 is available at:
https://git.add-ideas.de/lotobo/diff-tools/src/tag/v0.1.0
https://git.add-ideas.de/lotobo/diff-tools/src/tag/v0.2.0
Build with Node.js 22, npm 11, `npm ci`, and `npm run release:artifact`.
+10 -9
View File
@@ -2,14 +2,15 @@
Diff Tools is GPL-3.0-or-later. Its direct runtime dependencies retain their own licences:
| Package | Pinned version | Licence | Purpose |
| -------------------------------- | -------------: | ------------ | ---------------------------------------------- |
| `@add-ideas/toolbox-contract` | 0.2.3 | Apache-2.0 | Manifest validation |
| `@add-ideas/toolbox-shell-react` | 0.2.3 | Apache-2.0 | Shared Toolbox shell |
| `@xmldom/xmldom` | 0.9.12 | MIT | Inert XML DOM parsing |
| `diff` | 9.0.0 | BSD-3-Clause | Bounded sequence alignment and unified patches |
| `lossless-json` | 4.3.1 | MIT | Exact-decimal JSON parsing and serialization |
| `papaparse` | 5.7.0 | MIT | CSV and TSV parsing |
| `react` / `react-dom` | 19.2.8 | MIT | User interface |
| Package | Pinned version | Licence | Purpose |
| -------------------------------- | -------------: | ---------------- | ---------------------------------------------- |
| `@add-ideas/toolbox-contract` | 0.3.0 | Apache-2.0 | Manifest validation |
| `@add-ideas/toolbox-helpers` | 0.2.0 | GPL-3.0-or-later | Shared local-first utility primitives |
| `@add-ideas/toolbox-shell-react` | 0.3.0 | Apache-2.0 | Shared Toolbox shell |
| `@xmldom/xmldom` | 0.9.12 | MIT | Inert XML DOM parsing |
| `diff` | 9.0.0 | BSD-3-Clause | Bounded sequence alignment and unified patches |
| `lossless-json` | 4.3.1 | MIT | Exact-decimal JSON parsing and serialization |
| `papaparse` | 5.7.0 | MIT | CSV and TSV parsing |
| `react` / `react-dom` | 19.2.8 | MIT | User interface |
Release artifacts include the complete licence texts collected from every locked runtime package at `LICENSES/npm-runtime-licenses.txt`.
+1 -1
View File
@@ -1,6 +1,6 @@
# Accessibility
The workbench uses labelled native text areas, selects, checkboxes, file inputs and buttons. Comparison modes and result views are exposed as tab lists, status and diagnostic changes use live regions, and structured results use list or table semantics.
The workbench uses labelled native text areas, selects, checkboxes, file inputs and buttons. Comparison modes and result views are exposed as labelled pressed-state button groups, status and diagnostic changes use live regions, and structured results use list or table semantics.
Change kinds are written in text and indicated by `+`/`` markers, not colour alone. Exact CR, LF and tab characters have visible glyphs. Focus indicators remain visible in light, dark and system themes, and controls meet a minimum 2.55 rem target height.
+10 -3
View File
@@ -3,7 +3,10 @@
Diff Tools is a static React application with a relocatable `./` build. Its comparison pipeline is deliberately separated from the view:
1. The workbench captures strings or decodes a selected file as strict UTF-8 after a byte-size check.
2. A fresh module worker receives a plain comparison request. Changing input cancels and terminates the preceding worker; the last successful result remains on screen until a replacement succeeds.
2. A fresh module worker receives a typed shared worker-job request. Changing
input cancels and terminates the preceding worker; job IDs exclude stale
messages, and a 15-second hard deadline bounds the whole worker. The last
successful result remains on screen until a replacement succeeds.
3. A mode-specific pure comparator produces display rows and diagnostics. Normalized rows are first-class output, not discarded state.
4. The orchestrator adds exact input metadata, a bounded unified patch and a schema-labelled portable report.
5. React renders values as text. The app never consumes or inserts HTML produced by a diff or parser library.
@@ -16,7 +19,11 @@ When `Worker` is unavailable, such as in unit tests, the same pure comparator ru
- JSON uses `lossless-json`, rejects duplicate and prototype-affecting keys, and compares numbers without converting to IEEE-754. Object member order is semantically ignored but reported.
- XML rejects active declaration/include syntax and preflights structure before `@xmldom/xmldom` builds an inert DOM. Elements and attributes compare by expanded name when selected.
- CSV/TSV uses Papa Parse in string mode. Unique composite keys align rows; no spreadsheet type inference is performed.
- Directory manifests strip the one common browser-selected root, validate every relative path and conservative case/Unicode collision key, then hash file bytes with SHA-256 under count, per-file, aggregate and concurrency ceilings. The sorted, versioned JSON artifact can be compared later without the files.
- Three-way merge independently derives bounded token edits from base to ours and base to theirs. Non-overlapping regions compose; overlapping regions are compared against each other and the base before conflict markers are emitted. It does not claim semantic structured-data merging.
All report and patch formats are generated locally. `de.add-ideas.diff-tools.report.v1` is the portable report schema identifier.
All report and patch formats are generated locally. `de.add-ideas.diff-tools.report.v1`, `de.add-ideas.diff-tools.directory-manifest.v1` and `de.add-ideas.diff-tools.merge-report.v1` identify the portable artifacts.
The planned shared `@add-ideas/toolbox-helpers` package is not yet published at a compatible version, so v0.1 keeps its bounded domain functions inside `src/core`. They can be extracted without changing the worker protocol or report schema.
Diff algorithms, semantic models and reports remain bounded domain functions in
`src/core`. Generic byte-size display, safe Blob downloads and cancellable
worker lifecycle come from `@add-ideas/toolbox-helpers` 0.2.0.
+3
View File
@@ -13,6 +13,9 @@ The production CSP permits same-origin scripts and workers and blocks objects, f
- XML containing DOCTYPE, entity declaration or XInclude syntax is rejected before DOM parsing. A lexical preflight rejects excessive element count or nesting before DOM construction.
- JSON rejects duplicate keys and the prototype-affecting keys `__proto__`, `prototype` and `constructor`.
- CSV/TSV fields remain strings; formulas are displayed as text and are not evaluated.
- Directory hashing rejects traversal, absolute/control-laden and case/Unicode-colliding relative paths. SHA-256 reads use bounded concurrency, file/count/aggregate ceilings and an abort signal.
- Imported manifests are schema-, path-, digest-, order- and total-validated before comparison. Directory names and digests are sensitive metadata and should be reviewed before sharing.
- Three-way inputs use the same text ceilings plus an explicit conflict cap; conflict labels have CR/LF removed before entering marker lines.
- Imported strings are rendered through React text nodes and form controls. No library-generated HTML, imported markup or script is inserted into the document.
These controls bound this tool's work; they are not a general-purpose sanitizer and do not make imported data safe for another application.
+1 -1
View File
@@ -1,5 +1,5 @@
const CACHE_PREFIX = "diff-tools-shell-";
const CACHE_NAME = CACHE_PREFIX + "0.1.0";
const CACHE_NAME = CACHE_PREFIX + "0.2.0";
const CORE = ["./", "./manifest.webmanifest", "./favicon.svg"];
self.addEventListener("install", (event) => {
event.waitUntil(
+50 -3
View File
@@ -3,12 +3,22 @@
"schemaVersion": 1,
"id": "de.add-ideas.diff-tools",
"name": "Diff Tools",
"version": "0.1.0",
"description": "Compare text and structured data locally in the browser.",
"version": "0.2.0",
"description": "Compare files and directories or perform bounded three-way merges locally.",
"entry": "./",
"icon": "./favicon.svg",
"categories": ["developer", "files", "productivity"],
"tags": ["diff", "compare", "json", "xml", "csv", "patch"],
"tags": [
"diff",
"compare",
"json",
"xml",
"csv",
"patch",
"directory",
"manifest",
"merge"
],
"integration": {
"contextVersion": 1,
"launchModes": ["navigate", "new-tab"],
@@ -21,6 +31,43 @@
"crossOriginIsolated": false,
"topLevelContext": false
},
"io": {
"accepts": [
{
"mediaType": "text/*",
"extensions": [".txt", ".md", ".csv", ".xml"],
"label": "Text, CSV and XML files"
},
{
"mediaType": "application/json",
"extensions": [".json"],
"label": "JSON documents and directory manifests"
},
{
"mediaType": "*/*",
"extensions": [],
"label": "Files selected for bounded directory hashing"
}
],
"produces": [
{
"mediaType": "text/x-diff",
"extensions": [".diff", ".patch"],
"label": "Unified and JSON patches"
},
{
"mediaType": "text/plain",
"extensions": [".txt"],
"label": "Three-way merge result"
},
{
"mediaType": "application/json",
"extensions": [".json"],
"label": "Diff, merge and directory-manifest reports"
}
]
},
"capabilities": { "required": ["workers"], "optional": ["web-crypto"] },
"privacy": {
"processing": "local",
"fileUploads": true,
+278
View File
@@ -0,0 +1,278 @@
import { formatBytes, triggerBlobDownload } from "@add-ideas/toolbox-helpers";
import { useMemo, useRef, useState, type ChangeEvent } from "react";
import {
compareDirectoryManifests,
createDirectoryManifest,
parseDirectoryManifest,
serializeDirectoryManifest,
type DirectoryManifest,
} from "../core/directory-manifest";
type Side = "left" | "right";
const directoryAttributes = {
webkitdirectory: "",
directory: "",
} as Record<string, string>;
export function DirectoryWorkspace() {
const [files, setFiles] = useState<Record<Side, File[]>>({
left: [],
right: [],
});
const [manifests, setManifests] = useState<
Partial<Record<Side, DirectoryManifest>>
>({});
const [status, setStatus] = useState(
"Choose two directories or import saved manifests.",
);
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const [changesOnly, setChangesOnly] = useState(true);
const controller = useRef<AbortController | undefined>(undefined);
const changes = useMemo(() => {
if (!manifests.left || !manifests.right) return [];
return compareDirectoryManifests(manifests.left, manifests.right);
}, [manifests]);
const visible = changes.filter(
(change) => !changesOnly || change.status !== "same",
);
async function build(): Promise<void> {
if (
(!files.left.length && !manifests.left) ||
(!files.right.length && !manifests.right)
)
return;
controller.current?.abort();
const next = new AbortController();
controller.current = next;
setBusy(true);
setError("");
try {
const left =
manifests.left ??
(await createDirectoryManifest(files.left, {
signal: next.signal,
onProgress: (progress) =>
setStatus(
`Hashing left: ${progress.completed} / ${progress.total} · ${progress.path}`,
),
}));
const right =
manifests.right ??
(await createDirectoryManifest(files.right, {
signal: next.signal,
onProgress: (progress) =>
setStatus(
`Hashing right: ${progress.completed} / ${progress.total} · ${progress.path}`,
),
}));
if (next.signal.aborted) return;
setManifests({ left, right });
const result = compareDirectoryManifests(left, right);
setStatus(
`Compared ${result.length.toLocaleString()} relative paths; ${result.filter((item) => item.status !== "same").length.toLocaleString()} changed.`,
);
} catch (reason) {
if (!next.signal.aborted)
setError(
reason instanceof Error
? reason.message
: "Directory comparison failed.",
);
} finally {
if (controller.current === next) setBusy(false);
}
}
async function importManifest(
side: Side,
event: ChangeEvent<HTMLInputElement>,
) {
const file = event.currentTarget.files?.[0];
event.currentTarget.value = "";
if (!file) return;
try {
const manifest = parseDirectoryManifest(await file.text());
setManifests((current) => ({ ...current, [side]: manifest }));
setFiles((current) => ({ ...current, [side]: [] }));
setError("");
setStatus(
`Imported ${side} manifest with ${manifest.entries.length.toLocaleString()} files.`,
);
} catch (reason) {
setError(
reason instanceof Error
? reason.message
: "Invalid directory manifest.",
);
}
}
function selectedDirectory(side: Side, event: ChangeEvent<HTMLInputElement>) {
const selected = [...(event.currentTarget.files ?? [])];
event.currentTarget.value = "";
setFiles((current) => ({ ...current, [side]: selected }));
setManifests((current) => ({ ...current, [side]: undefined }));
setStatus(`Selected ${selected.length.toLocaleString()} ${side} files.`);
}
function downloadManifest(side: Side): void {
const manifest = manifests[side];
if (!manifest) return;
triggerBlobDownload(
new Blob([serializeDirectoryManifest(manifest)], {
type: "application/json;charset=utf-8",
}),
`${side}-directory-manifest.json`,
);
}
function cancelBuild(): void {
controller.current?.abort();
setStatus(
"Directory hashing cancelled. Existing manifests were left unchanged.",
);
}
return (
<section
className="panel directory-workspace"
aria-labelledby="directory-title"
>
<div className="panel-heading">
<div>
<p className="eyebrow">Relative paths · SHA-256</p>
<h2 id="directory-title">Directory manifests</h2>
</div>
{busy ? (
<button type="button" onClick={cancelBuild}>
Cancel
</button>
) : null}
</div>
<p className="option-note">
File contents are hashed locally with bounded two-file concurrency.
Empty directories are not exposed by browser file selection and
therefore cannot appear in a manifest.
</p>
<div className="directory-inputs">
{(["left", "right"] as const).map((side) => (
<article key={side}>
<h3>{side === "left" ? "Before directory" : "After directory"}</h3>
<div className="button-row">
<label className="button file-button">
Choose directory
<input
type="file"
multiple
{...directoryAttributes}
onChange={(event) => selectedDirectory(side, event)}
data-testid={`${side}-directory-input`}
/>
</label>
<label className="button file-button">
Import manifest
<input
type="file"
accept=".json,application/json"
onChange={(event) => void importManifest(side, event)}
/>
</label>
<button
type="button"
disabled={!manifests[side]}
onClick={() => downloadManifest(side)}
>
Download manifest
</button>
</div>
<p>
{manifests[side]
? `${manifests[side]!.entries.length.toLocaleString()} manifested files · ${formatBytes(manifests[side]!.totals.bytes)}`
: `${files[side].length.toLocaleString()} selected files`}
</p>
</article>
))}
</div>
<div className="compare-bar">
<button
type="button"
className="primary-button"
disabled={
busy ||
(!files.left.length && !manifests.left) ||
(!files.right.length && !manifests.right)
}
onClick={() => void build()}
>
Build & compare manifests
</button>
<p role="status" aria-live="polite">
{status}
</p>
</div>
{error ? (
<p className="diagnostic diagnostic--error" role="alert">
{error}
</p>
) : null}
{changes.length ? (
<>
<label className="toggle manifest-filter">
<input
type="checkbox"
checked={changesOnly}
onChange={(event) => setChangesOnly(event.target.checked)}
/>
<span>
<strong>Show changes only</strong>
</span>
</label>
<div
className="table-scroll"
tabIndex={0}
role="region"
aria-label="Directory manifest comparison"
>
<table>
<thead>
<tr>
<th>Path</th>
<th>Status</th>
<th>Before</th>
<th>After</th>
<th>Meaning</th>
</tr>
</thead>
<tbody>
{visible.map((change) => (
<tr key={change.path}>
<th scope="row">
<code>{change.path}</code>
</th>
<td>
<span
className={`kind-badge kind-badge--${change.status}`}
>
{change.status}
</span>
</td>
<td>
{change.left ? formatBytes(change.left.bytes) : "—"}
</td>
<td>
{change.right ? formatBytes(change.right.bytes) : "—"}
</td>
<td>{change.detail}</td>
</tr>
))}
</tbody>
</table>
</div>
</>
) : null}
</section>
);
}
+11 -1
View File
@@ -32,7 +32,9 @@ export function HelpDialog({
</button>
</div>
<p>
Compare exact text or the structure of JSON, XML, CSV and TSV locally.
Compare exact text or the structure of JSON, XML, CSV and TSV locally,
compare bounded directory manifests, or merge two variants against an
explicit base.
</p>
<ul>
<li>Text keeps CRLF, LF, CR and final-newline state exact.</li>
@@ -41,6 +43,14 @@ export function HelpDialog({
<li>
CSV rows are matched by unique key columns and fields remain strings.
</li>
<li>
Directory comparison hashes selected files locally with SHA-256; empty
directories cannot be observed through browser file selection.
</li>
<li>
Three-way merge combines non-overlapping line edits and emits
ours/base/theirs markers plus a report for overlaps.
</li>
</ul>
<p>
Ignored and normalized differences remain visible. All processing is
+123
View File
@@ -0,0 +1,123 @@
import { triggerBlobDownload } from "@add-ideas/toolbox-helpers";
import { useState } from "react";
import { mergeThreeWay, type MergeResult } from "../core/merge";
const SAMPLE = {
base: "title\nshared\nfooter\n",
ours: "title from ours\nshared\nfooter\n",
theirs: "title\nshared\nfooter from theirs\n",
};
export function MergeWorkspace() {
const [base, setBase] = useState(SAMPLE.base);
const [ours, setOurs] = useState(SAMPLE.ours);
const [theirs, setTheirs] = useState(SAMPLE.theirs);
const [error, setError] = useState("");
const [result, setResult] = useState<MergeResult>();
function merge(): void {
try {
setResult(mergeThreeWay({ base, ours, theirs }));
setError("");
} catch (reason) {
setError(
reason instanceof Error ? reason.message : "Three-way merge failed.",
);
setResult(undefined);
}
}
function download(text: string, name: string, type: string): void {
triggerBlobDownload(new Blob([text], { type }), name);
}
return (
<section className="panel merge-workspace" aria-labelledby="merge-title">
<div className="panel-heading">
<div>
<p className="eyebrow">Bounded line merge</p>
<h2 id="merge-title">Three-way merge</h2>
</div>
</div>
<p className="option-note">
Changes are derived independently from the base. Non-overlapping edits
merge automatically; overlapping results get explicit ours/base/theirs
conflict markers. This is text merge, not a semantic JSON/XML merge.
</p>
<div className="merge-inputs">
{(
[
["Base", base, setBase],
["Ours", ours, setOurs],
["Theirs", theirs, setTheirs],
] as const
).map(([label, value, setter]) => (
<label className="field" key={label}>
<span>{label}</span>
<textarea
value={value}
onChange={(event) => setter(event.target.value)}
spellCheck={false}
/>
</label>
))}
</div>
<button type="button" className="primary-button" onClick={merge}>
Merge locally
</button>
{error ? (
<p className="diagnostic diagnostic--error" role="alert">
{error}
</p>
) : null}
{result ? (
<div className="merge-result">
<div className="artifact-heading">
<div>
<p className="eyebrow">
{result.clean ? "Clean merge" : "Review required"}
</p>
<h3>{result.conflicts.length} conflict(s)</h3>
</div>
<div>
<button
type="button"
onClick={() =>
download(
result.report,
"merge-report.json",
"application/json",
)
}
>
Download report
</button>
<button
type="button"
className="primary-button"
onClick={() =>
download(
result.text,
"merged.txt",
"text/plain;charset=utf-8",
)
}
>
Download merged text
</button>
</div>
</div>
<label className="field output-field">
<span>Merged text</span>
<textarea
readOnly
value={result.text}
data-testid="merge-output"
spellCheck={false}
/>
</label>
</div>
) : null}
</section>
);
}
+333 -305
View File
@@ -1,3 +1,4 @@
import { formatBytes, triggerBlobDownload } from "@add-ideas/toolbox-helpers";
import {
useCallback,
useEffect,
@@ -8,6 +9,8 @@ import {
} from "react";
import { DIFF_LIMITS } from "../core/limits";
import { createCompareTask, type CompareTask } from "../core/worker-client";
import { DirectoryWorkspace } from "./DirectoryWorkspace";
import { MergeWorkspace } from "./MergeWorkspace";
import {
DEFAULT_OPTIONS,
DiffToolsError,
@@ -90,11 +93,7 @@ function visibleText(value: string | undefined): string {
}
function bytes(value: number): string {
return value < 1_024
? `${value} B`
: value < 1_048_576
? `${(value / 1_024).toFixed(1)} KiB`
: `${(value / 1_048_576).toFixed(1)} MiB`;
return formatBytes(value, { fractionDigits: value < 1_024 ? 0 : 1 });
}
function fileExtension(mode: DiffMode, artifact: "report" | "patch"): string {
@@ -103,20 +102,10 @@ function fileExtension(mode: DiffMode, artifact: "report" | "patch"): string {
}
function download(value: string, name: string): void {
const blob = new Blob([value], { type: "text/plain;charset=utf-8" });
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = name;
anchor.hidden = true;
anchor.rel = "noopener";
document.body.append(anchor);
try {
anchor.click();
} finally {
anchor.remove();
queueMicrotask(() => URL.revokeObjectURL(url));
}
triggerBlobDownload(
new Blob([value], { type: "text/plain;charset=utf-8" }),
name,
);
}
function Toggle({
@@ -516,6 +505,9 @@ export function Workbench() {
);
const [statusText, setStatusText] = useState("Ready to compare locally.");
const [notice, setNotice] = useState("");
const [workspace, setWorkspace] = useState<
"compare" | "directories" | "merge"
>("compare");
const task = useRef<CompareTask | undefined>(undefined);
const sequence = useRef(0);
const input = inputs[mode];
@@ -680,320 +672,356 @@ export function Workbench() {
<span className="privacy-pill">Browser-local</span>
</header>
<nav className="mode-tabs" aria-label="Comparison modes">
<div role="tablist" aria-label="Comparison modes">
{MODES.map((item) => (
<button
key={item.id}
type="button"
role="tab"
aria-label={`${item.label} ${item.hint}`}
aria-selected={mode === item.id}
onClick={() => setRoute(item.id, view)}
>
<span>{item.label}</span>
<small>{item.hint}</small>
</button>
))}
</div>
<nav className="workspace-tabs" aria-label="Diff workspaces">
{(
[
["compare", "Two-way compare"],
["directories", "Directories"],
["merge", "Three-way merge"],
] as const
).map(([id, label]) => (
<button
key={id}
type="button"
aria-current={workspace === id ? "page" : undefined}
onClick={() => setWorkspace(id)}
>
{label}
</button>
))}
</nav>
<section className="panel options-panel" aria-labelledby="options-title">
<div className="panel-heading">
<div>
<p className="eyebrow">Visible semantics</p>
<h2 id="options-title">Comparison options</h2>
</div>
</div>
<Options mode={mode} options={options} setOptions={setOptions} />
</section>
<section className="input-grid" aria-label="Comparison inputs">
{(["left", "right"] as const).map((side) => (
<article className="panel input-panel" key={side}>
<div className="panel-heading">
<div>
<p className="eyebrow">
{side === "left" ? "Before" : "After"}
</p>
<h2>
{input[`${side}Name`] ??
(side === "left" ? "Original" : "Changed")}
</h2>
</div>
<label className="button file-button">
Open file
<input
type="file"
onChange={(event) => fileChanged(side, event)}
data-testid={`${side}-file-input`}
/>
</label>
</div>
<label className="field">
<span>{side === "left" ? "Before text" : "After text"}</span>
<textarea
value={input[side]}
onChange={(event) => updateInput(side, event.target.value)}
spellCheck={false}
data-testid={`${side}-editor`}
/>
</label>
</article>
))}
</section>
<div className="compare-bar panel">
<button
type="button"
onClick={() =>
setInputs((current) => ({
...current,
[mode]: {
left: current[mode].right,
right: current[mode].left,
leftName: current[mode].rightName,
rightName: current[mode].leftName,
},
}))
}
>
Swap sides
</button>
<button
type="button"
className="primary-button"
onClick={() => compare(request)}
>
Compare now
</button>
<p role="status" aria-live="polite" data-status={status}>
{statusText}
</p>
</div>
<Diagnostics diagnostics={diagnostics} />
{result ? (
<section className="results" aria-label="Comparison result">
<div className="summary-grid">
<article className="summary-card summary-card--verdict">
<span>Verdict</span>
<strong>
{result.exactlyEqual
? "Exactly equal"
: result.semanticallyEqual
? "Semantically equal"
: "Different"}
</strong>
<small>
{result.exactlyEqual
? "Source text matches"
: "Exact source differs"}
</small>
</article>
{(["added", "removed", "modified", "normalized"] as const).map(
(kind) => (
<article
className={`summary-card summary-card--${kind}`}
key={kind}
>
<span>{kind}</span>
<strong>{result.stats[kind]}</strong>
<small>
display row{result.stats[kind] === 1 ? "" : "s"}
</small>
</article>
),
)}
</div>
<section className="metadata panel" aria-labelledby="metadata-title">
<div className="panel-heading">
<div>
<p className="eyebrow">Exact source state</p>
<h2 id="metadata-title">Newlines and size</h2>
</div>
</div>
<div className="metadata-grid">
{[result.left, result.right].map((item, index) => (
<dl key={index}>
<div>
<dt>Side</dt>
<dd>{index === 0 ? "Before" : "After"}</dd>
</div>
<div>
<dt>Size</dt>
<dd>{bytes(item.bytes)}</dd>
</div>
<div>
<dt>Lines</dt>
<dd>{item.lines}</dd>
</div>
<div>
<dt>LF</dt>
<dd>{item.newlines.lf}</dd>
</div>
<div>
<dt>CRLF</dt>
<dd>{item.newlines.crlf}</dd>
</div>
<div>
<dt>CR</dt>
<dd>{item.newlines.cr}</dd>
</div>
<div>
<dt>Final newline</dt>
<dd>{item.newlines.final}</dd>
</div>
</dl>
))}
</div>
<div className="normalization-list">
<strong>Applied comparison rules</strong>
{result.appliedNormalizations.length ? (
result.appliedNormalizations.map((item) => (
<span key={item}>{item}</span>
))
) : (
<span>Exact source comparison</span>
)}
</div>
</section>
<nav className="result-tabs" aria-label="Result views">
<div role="tablist" aria-label="Result views">
{RESULT_VIEWS.map((item) => (
{workspace === "compare" ? (
<>
<nav className="mode-tabs" aria-label="Comparison modes">
<div role="group" aria-label="Comparison modes">
{MODES.map((item) => (
<button
type="button"
role="tab"
aria-selected={view === item.id}
key={item.id}
onClick={() => setRoute(mode, item.id)}
type="button"
aria-label={`${item.label} ${item.hint}`}
aria-pressed={mode === item.id}
onClick={() => setRoute(item.id, view)}
>
{item.label}
<span>{item.label}</span>
<small>{item.hint}</small>
</button>
))}
</div>
</nav>
<section className="panel result-panel" role="tabpanel">
{view === "unified" ? <UnifiedRows rows={result.rows} /> : null}
{view === "side-by-side" ? (
<SideBySideRows rows={result.rows} />
) : null}
{view === "report" ? (
<div className="artifact">
<div className="artifact-heading">
<section
className="panel options-panel"
aria-labelledby="options-title"
>
<div className="panel-heading">
<div>
<p className="eyebrow">Visible semantics</p>
<h2 id="options-title">Comparison options</h2>
</div>
</div>
<Options mode={mode} options={options} setOptions={setOptions} />
</section>
<section className="input-grid" aria-label="Comparison inputs">
{(["left", "right"] as const).map((side) => (
<article className="panel input-panel" key={side}>
<div className="panel-heading">
<div>
<p className="eyebrow">Portable artifact</p>
<h2>JSON report</h2>
<p className="eyebrow">
{side === "left" ? "Before" : "After"}
</p>
<h2>
{input[`${side}Name`] ??
(side === "left" ? "Original" : "Changed")}
</h2>
</div>
<label className="button file-button">
Open file
<input
type="file"
onChange={(event) => fileChanged(side, event)}
data-testid={`${side}-file-input`}
/>
</label>
</div>
<label className="field">
<span>{side === "left" ? "Before text" : "After text"}</span>
<textarea
value={input[side]}
onChange={(event) => updateInput(side, event.target.value)}
spellCheck={false}
data-testid={`${side}-editor`}
/>
</label>
</article>
))}
</section>
<div className="compare-bar panel">
<button
type="button"
onClick={() =>
setInputs((current) => ({
...current,
[mode]: {
left: current[mode].right,
right: current[mode].left,
leftName: current[mode].rightName,
rightName: current[mode].leftName,
},
}))
}
>
Swap sides
</button>
<button
type="button"
className="primary-button"
onClick={() => compare(request)}
>
Compare now
</button>
<p role="status" aria-live="polite" data-status={status}>
{statusText}
</p>
</div>
<Diagnostics diagnostics={diagnostics} />
{result ? (
<section className="results" aria-label="Comparison result">
<div className="summary-grid">
<article className="summary-card summary-card--verdict">
<span>Verdict</span>
<strong>
{result.exactlyEqual
? "Exactly equal"
: result.semanticallyEqual
? "Semantically equal"
: "Different"}
</strong>
<small>
{result.exactlyEqual
? "Source text matches"
: "Exact source differs"}
</small>
</article>
{(["added", "removed", "modified", "normalized"] as const).map(
(kind) => (
<article
className={`summary-card summary-card--${kind}`}
key={kind}
>
<span>{kind}</span>
<strong>{result.stats[kind]}</strong>
<small>
display row{result.stats[kind] === 1 ? "" : "s"}
</small>
</article>
),
)}
</div>
<section
className="metadata panel"
aria-labelledby="metadata-title"
>
<div className="panel-heading">
<div>
<button
type="button"
onClick={() => void copy(result.report, "JSON report")}
>
Copy
</button>
<button
type="button"
className="primary-button"
onClick={() =>
download(
result.report,
`diff-report.${fileExtension(mode, "report")}`,
)
}
>
Download
</button>
<p className="eyebrow">Exact source state</p>
<h2 id="metadata-title">Newlines and size</h2>
</div>
</div>
<textarea
readOnly
value={result.report}
data-testid="json-report"
/>
</div>
) : null}
{view === "patch" ? (
<div className="patch-grid">
<div className="artifact">
<div className="artifact-heading">
<div>
<p className="eyebrow">Exact source transform</p>
<h2>Unified patch</h2>
</div>
<div>
<button
type="button"
onClick={() =>
void copy(result.unifiedPatch, "Unified patch")
}
disabled={!result.unifiedPatch}
>
Copy
</button>
<button
type="button"
className="primary-button"
disabled={!result.unifiedPatch}
onClick={() =>
result.unifiedPatch &&
download(
result.unifiedPatch,
`changes.${fileExtension(mode, "patch")}`,
)
}
>
Download
</button>
</div>
</div>
{result.unifiedPatch ? (
<textarea
readOnly
value={result.unifiedPatch}
data-testid="unified-patch"
/>
<div className="metadata-grid">
{[result.left, result.right].map((item, index) => (
<dl key={index}>
<div>
<dt>Side</dt>
<dd>{index === 0 ? "Before" : "After"}</dd>
</div>
<div>
<dt>Size</dt>
<dd>{bytes(item.bytes)}</dd>
</div>
<div>
<dt>Lines</dt>
<dd>{item.lines}</dd>
</div>
<div>
<dt>LF</dt>
<dd>{item.newlines.lf}</dd>
</div>
<div>
<dt>CRLF</dt>
<dd>{item.newlines.crlf}</dd>
</div>
<div>
<dt>CR</dt>
<dd>{item.newlines.cr}</dd>
</div>
<div>
<dt>Final newline</dt>
<dd>{item.newlines.final}</dd>
</div>
</dl>
))}
</div>
<div className="normalization-list">
<strong>Applied comparison rules</strong>
{result.appliedNormalizations.length ? (
result.appliedNormalizations.map((item) => (
<span key={item}>{item}</span>
))
) : (
<p className="empty-result">
Patch unavailable at the configured safety limit.
</p>
<span>Exact source comparison</span>
)}
</div>
{mode === "json" ? (
</section>
<nav className="result-tabs" aria-label="Result views">
<div role="group" aria-label="Result views">
{RESULT_VIEWS.map((item) => (
<button
type="button"
aria-pressed={view === item.id}
key={item.id}
onClick={() => setRoute(mode, item.id)}
>
{item.label}
</button>
))}
</div>
</nav>
<section className="panel result-panel">
{view === "unified" ? <UnifiedRows rows={result.rows} /> : null}
{view === "side-by-side" ? (
<SideBySideRows rows={result.rows} />
) : null}
{view === "report" ? (
<div className="artifact">
<div className="artifact-heading">
<div>
<p className="eyebrow">Semantic transform</p>
<h2>RFC 6902 JSON Patch</h2>
<p className="eyebrow">Portable artifact</p>
<h2>JSON report</h2>
</div>
<div>
<button
type="button"
onClick={() =>
void copy(result.report, "JSON report")
}
>
Copy
</button>
<button
type="button"
className="primary-button"
onClick={() =>
download(
result.report,
`diff-report.${fileExtension(mode, "report")}`,
)
}
>
Download
</button>
</div>
<button
type="button"
onClick={() =>
void copy(result.jsonPatch, "JSON Patch")
}
>
Copy
</button>
</div>
<textarea
readOnly
value={result.jsonPatch ?? ""}
data-testid="json-patch"
aria-label="JSON comparison report"
value={result.report}
data-testid="json-report"
/>
</div>
) : null}
</div>
) : null}
</section>
</section>
) : null}
<p className="action-notice" role="status" aria-live="polite">
{notice}
</p>
{view === "patch" ? (
<div className="patch-grid">
<div className="artifact">
<div className="artifact-heading">
<div>
<p className="eyebrow">Exact source transform</p>
<h2>Unified patch</h2>
</div>
<div>
<button
type="button"
onClick={() =>
void copy(result.unifiedPatch, "Unified patch")
}
disabled={!result.unifiedPatch}
>
Copy
</button>
<button
type="button"
className="primary-button"
disabled={!result.unifiedPatch}
onClick={() =>
result.unifiedPatch &&
download(
result.unifiedPatch,
`changes.${fileExtension(mode, "patch")}`,
)
}
>
Download
</button>
</div>
</div>
{result.unifiedPatch ? (
<textarea
readOnly
aria-label="Unified patch"
value={result.unifiedPatch}
data-testid="unified-patch"
/>
) : (
<p className="empty-result">
Patch unavailable at the configured safety limit.
</p>
)}
</div>
{mode === "json" ? (
<div className="artifact">
<div className="artifact-heading">
<div>
<p className="eyebrow">Semantic transform</p>
<h2>RFC 6902 JSON Patch</h2>
</div>
<button
type="button"
onClick={() =>
void copy(result.jsonPatch, "JSON Patch")
}
>
Copy
</button>
</div>
<textarea
readOnly
aria-label="RFC 6902 JSON Patch"
value={result.jsonPatch ?? ""}
data-testid="json-patch"
/>
</div>
) : null}
</div>
) : null}
</section>
</section>
) : null}
<p className="action-notice" role="status" aria-live="polite">
{notice}
</p>
</>
) : workspace === "directories" ? (
<DirectoryWorkspace />
) : (
<MergeWorkspace />
)}
</main>
);
}
+331
View File
@@ -0,0 +1,331 @@
import { DIFF_LIMITS } from "./limits";
export interface DirectoryManifestEntry {
readonly path: string;
readonly bytes: number;
readonly sha256: string;
readonly lastModified?: string;
}
export interface DirectoryManifest {
readonly schema: "de.add-ideas.diff-tools.directory-manifest.v1";
readonly schemaVersion: 1;
readonly generatedLocally: true;
readonly rootLabel?: string;
readonly hashAlgorithm: "SHA-256";
readonly entries: readonly DirectoryManifestEntry[];
readonly totals: { readonly files: number; readonly bytes: number };
}
export interface ManifestProgress {
readonly completed: number;
readonly total: number;
readonly path: string;
}
export interface ManifestChange {
readonly path: string;
readonly status: "same" | "added" | "removed" | "modified";
readonly left?: DirectoryManifestEntry;
readonly right?: DirectoryManifestEntry;
readonly detail: string;
}
export async function createDirectoryManifest(
files: readonly File[],
options: {
readonly signal?: AbortSignal;
readonly onProgress?: (progress: ManifestProgress) => void;
readonly concurrency?: number;
} = {},
): Promise<DirectoryManifest> {
if (!globalThis.crypto?.subtle)
throw new Error("The browser Web Crypto digest API is unavailable.");
if (files.length > DIFF_LIMITS.maxDirectoryFiles)
throw new RangeError(
`Directory contains more than ${DIFF_LIMITS.maxDirectoryFiles.toLocaleString()} files.`,
);
const paths = relativePaths(files);
let totalBytes = 0;
const collisionKeys = new Set<string>();
for (const [index, file] of files.entries()) {
throwIfAborted(options.signal);
if (file.size > DIFF_LIMITS.maxDirectoryFileBytes)
throw new RangeError(
`${paths[index]} exceeds the per-file hashing limit.`,
);
totalBytes += file.size;
if (
!Number.isSafeInteger(totalBytes) ||
totalBytes > DIFF_LIMITS.maxDirectoryBytes
)
throw new RangeError(
"Directory files exceed the aggregate hashing limit.",
);
const key = paths[index]!.normalize("NFC").toLocaleLowerCase("en-US");
if (collisionKeys.has(key))
throw new Error(
`Directory path collision after conservative normalization: ${paths[index]}.`,
);
collisionKeys.add(key);
}
const entries: DirectoryManifestEntry[] = new Array(files.length);
let next = 0;
let completed = 0;
const concurrency = Math.max(
1,
Math.min(
DIFF_LIMITS.directoryHashConcurrency,
Math.floor(options.concurrency ?? DIFF_LIMITS.directoryHashConcurrency),
),
);
const worker = async () => {
while (true) {
const index = next++;
if (index >= files.length) return;
const file = files[index]!;
const path = paths[index]!;
throwIfAborted(options.signal);
const digest = await crypto.subtle.digest(
"SHA-256",
await file.arrayBuffer(),
);
throwIfAborted(options.signal);
entries[index] = {
path,
bytes: file.size,
sha256: hex(new Uint8Array(digest)),
lastModified:
Number.isFinite(file.lastModified) && file.lastModified > 0
? new Date(file.lastModified).toISOString()
: undefined,
};
completed += 1;
options.onProgress?.({ completed, total: files.length, path });
}
};
await Promise.all(
Array.from(
{ length: Math.min(concurrency, Math.max(1, files.length)) },
worker,
),
);
entries.sort((left, right) =>
left.path < right.path ? -1 : left.path > right.path ? 1 : 0,
);
const rootLabel = commonRootLabel(files);
return {
schema: "de.add-ideas.diff-tools.directory-manifest.v1",
schemaVersion: 1,
generatedLocally: true,
rootLabel,
hashAlgorithm: "SHA-256",
entries,
totals: { files: entries.length, bytes: totalBytes },
};
}
export function compareDirectoryManifests(
left: DirectoryManifest,
right: DirectoryManifest,
): ManifestChange[] {
validateDirectoryManifest(left);
validateDirectoryManifest(right);
const leftEntries = new Map(left.entries.map((entry) => [entry.path, entry]));
const rightEntries = new Map(
right.entries.map((entry) => [entry.path, entry]),
);
const paths = [
...new Set([...leftEntries.keys(), ...rightEntries.keys()]),
].sort();
return paths.map((path) => {
const before = leftEntries.get(path);
const after = rightEntries.get(path);
if (!before)
return {
path,
status: "added",
right: after,
detail: "File exists only on the right.",
};
if (!after)
return {
path,
status: "removed",
left: before,
detail: "File exists only on the left.",
};
if (before.sha256 === after.sha256 && before.bytes === after.bytes)
return {
path,
status: "same",
left: before,
right: after,
detail: "Size and SHA-256 digest match.",
};
return {
path,
status: "modified",
left: before,
right: after,
detail:
before.bytes === after.bytes
? "SHA-256 digest changed while byte size stayed equal."
: "Byte size and/or SHA-256 digest changed.",
};
});
}
export function serializeDirectoryManifest(
manifest: DirectoryManifest,
): string {
validateDirectoryManifest(manifest);
const text = `${JSON.stringify(manifest, null, 2)}\n`;
if (text.length > DIFF_LIMITS.maxOutputCharacters)
throw new RangeError("Directory manifest exceeds the output limit.");
return text;
}
export function parseDirectoryManifest(source: string): DirectoryManifest {
if (source.length > DIFF_LIMITS.maxOutputCharacters)
throw new RangeError("Directory manifest exceeds the input limit.");
let value: unknown;
try {
value = JSON.parse(source) as unknown;
} catch (error) {
throw new SyntaxError(
error instanceof Error ? error.message : "Invalid manifest JSON.",
{ cause: error },
);
}
validateDirectoryManifest(value);
return value;
}
export function validateDirectoryManifest(
value: unknown,
): asserts value is DirectoryManifest {
if (!value || typeof value !== "object" || Array.isArray(value))
throw new TypeError("Directory manifest must be an object.");
const record = value as Record<string, unknown>;
if (
record.schema !== "de.add-ideas.diff-tools.directory-manifest.v1" ||
record.schemaVersion !== 1 ||
record.generatedLocally !== true ||
record.hashAlgorithm !== "SHA-256" ||
!Array.isArray(record.entries)
)
throw new TypeError(
"Directory manifest identity or entry list is invalid.",
);
if (record.entries.length > DIFF_LIMITS.maxDirectoryFiles)
throw new RangeError("Directory manifest exceeds the file-count limit.");
let total = 0;
let previous = "";
const seen = new Set<string>();
const collisionKeys = new Set<string>();
for (const candidate of record.entries) {
if (!candidate || typeof candidate !== "object" || Array.isArray(candidate))
throw new TypeError("Directory manifest entry is invalid.");
const entry = candidate as Record<string, unknown>;
if (
typeof entry.path !== "string" ||
typeof entry.bytes !== "number" ||
!Number.isSafeInteger(entry.bytes) ||
entry.bytes < 0 ||
typeof entry.sha256 !== "string" ||
!/^[0-9a-f]{64}$/u.test(entry.sha256) ||
(entry.lastModified !== undefined &&
(typeof entry.lastModified !== "string" ||
!Number.isFinite(Date.parse(entry.lastModified))))
)
throw new TypeError("Directory manifest entry fields are invalid.");
validatePath(entry.path);
if (seen.has(entry.path))
throw new Error(`Duplicate manifest path: ${entry.path}.`);
const collisionKey = entry.path.normalize("NFC").toLocaleLowerCase("en-US");
if (collisionKeys.has(collisionKey))
throw new Error(
`Directory path collision after conservative normalization: ${entry.path}.`,
);
if (previous && entry.path < previous)
throw new Error("Directory manifest entries must be sorted by path.");
seen.add(entry.path);
collisionKeys.add(collisionKey);
previous = entry.path;
total += entry.bytes;
if (!Number.isSafeInteger(total) || total > DIFF_LIMITS.maxDirectoryBytes)
throw new RangeError(
"Directory manifest exceeds the aggregate byte limit.",
);
}
const totals = record.totals;
if (
!totals ||
typeof totals !== "object" ||
(totals as Record<string, unknown>).files !== record.entries.length ||
(totals as Record<string, unknown>).bytes !== total
)
throw new Error("Directory manifest totals do not match its entries.");
}
function relativePaths(files: readonly File[]): string[] {
const root = commonRootLabel(files);
return files.map((file) => {
const raw = file.webkitRelativePath || file.name;
const segments = raw.split("/");
if (root && segments[0] === root) segments.shift();
const path = segments.join("/").normalize("NFC");
validatePath(path);
return path;
});
}
function commonRootLabel(files: readonly File[]): string | undefined {
const roots = files
.map((file) => file.webkitRelativePath.split("/")[0])
.filter((value): value is string => Boolean(value));
return roots.length === files.length &&
roots.every((root) => root === roots[0])
? roots[0]
: undefined;
}
function validatePath(path: string): void {
if (
!path ||
path.length > DIFF_LIMITS.maxDirectoryPathCharacters ||
path.includes("\\") ||
path.startsWith("/") ||
/^[a-z]:/iu.test(path) ||
hasControlCharacter(path)
)
throw new Error(
`Unsafe or excessive directory path: ${path || "(empty)"}.`,
);
const segments = path.split("/");
if (
segments.length > DIFF_LIMITS.maxDirectoryPathSegments ||
segments.some((segment) => !segment || segment === "." || segment === "..")
)
throw new Error(`Unsafe directory path segments: ${path}.`);
}
function hasControlCharacter(value: string): boolean {
return [...value].some((character) => {
const codePoint = character.codePointAt(0)!;
return codePoint <= 0x1f || codePoint === 0x7f;
});
}
function hex(bytes: Uint8Array): string {
return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
}
function throwIfAborted(signal?: AbortSignal): void {
if (signal?.aborted)
throw signal.reason instanceof Error
? signal.reason
: new DOMException("Operation cancelled.", "AbortError");
}
+8
View File
@@ -14,7 +14,15 @@ export const DIFF_LIMITS = Object.freeze({
maxOutputCharacters: 16_000_000,
maxRowSnippet: 12_000,
diffTimeoutMilliseconds: 2_000,
workerTimeoutMilliseconds: 15_000,
maxEditLength: 10_000,
maxDirectoryFiles: 5_000,
maxDirectoryBytes: 512 * 1024 * 1024,
maxDirectoryFileBytes: 256 * 1024 * 1024,
maxDirectoryPathCharacters: 4_096,
maxDirectoryPathSegments: 64,
directoryHashConcurrency: 2,
maxMergeConflicts: 1_000,
});
export class DiffLimitError extends RangeError {
+286
View File
@@ -0,0 +1,286 @@
import { diffArrays } from "diff";
import { assertInput, assertOutput, DIFF_LIMITS } from "./limits";
import type { Diagnostic } from "./types";
interface Edit {
readonly start: number;
readonly end: number;
readonly replacement: readonly string[];
readonly side: "ours" | "theirs";
}
export interface MergeRequest {
readonly base: string;
readonly ours: string;
readonly theirs: string;
readonly oursName?: string;
readonly theirsName?: string;
}
export interface MergeConflict {
readonly index: number;
readonly baseStartLine: number;
readonly baseEndLine: number;
readonly ours: string;
readonly base: string;
readonly theirs: string;
}
export interface MergeResult {
readonly text: string;
readonly clean: boolean;
readonly conflicts: readonly MergeConflict[];
readonly diagnostics: readonly Diagnostic[];
readonly report: string;
}
export function mergeThreeWay(request: MergeRequest): MergeResult {
assertInput(request.base, "left");
assertInput(request.ours, "right");
assertInput(request.theirs, "right");
if (request.ours === request.theirs)
return result(
request,
request.ours,
[],
[notice("merge.identical-sides", "Both variants are identical.")],
);
if (request.ours === request.base)
return result(
request,
request.theirs,
[],
[notice("merge.ours-unchanged", "Only the other variant changed.")],
);
if (request.theirs === request.base)
return result(
request,
request.ours,
[],
[notice("merge.theirs-unchanged", "Only our variant changed.")],
);
const base = lineTokens(request.base);
const ours = editsFor(base, lineTokens(request.ours), "ours");
const theirs = editsFor(base, lineTokens(request.theirs), "theirs");
const all = [...ours, ...theirs].sort(
(left, right) =>
left.start - right.start ||
left.end - right.end ||
left.side.localeCompare(right.side),
);
const output: string[] = [];
const conflicts: MergeConflict[] = [];
let cursor = 0;
let index = 0;
while (index < all.length) {
const first = all[index]!;
output.push(...base.slice(cursor, first.start));
const regionStart = first.start;
let regionEnd = first.end;
const group: Edit[] = [first];
index += 1;
while (index < all.length) {
const candidate = all[index]!;
const overlaps =
candidate.start < regionEnd ||
(regionStart === regionEnd && candidate.start === regionStart);
if (!overlaps) break;
group.push(candidate);
regionEnd = Math.max(regionEnd, candidate.end);
index += 1;
}
const oursGroup = group.filter((edit) => edit.side === "ours");
const theirsGroup = group.filter((edit) => edit.side === "theirs");
const baseRegion = base.slice(regionStart, regionEnd);
const oursRegion = oursGroup.length
? applyRegion(base, regionStart, regionEnd, oursGroup)
: baseRegion;
const theirsRegion = theirsGroup.length
? applyRegion(base, regionStart, regionEnd, theirsGroup)
: baseRegion;
if (equalTokens(oursRegion, theirsRegion)) output.push(...oursRegion);
else if (equalTokens(oursRegion, baseRegion)) output.push(...theirsRegion);
else if (equalTokens(theirsRegion, baseRegion)) output.push(...oursRegion);
else {
if (conflicts.length >= DIFF_LIMITS.maxMergeConflicts)
throw new RangeError(
"Three-way merge exceeds the conflict-count limit.",
);
const conflict: MergeConflict = {
index: conflicts.length + 1,
baseStartLine: lineNumberAt(base, regionStart),
baseEndLine: lineNumberAt(base, regionEnd),
ours: oursRegion.join(""),
base: baseRegion.join(""),
theirs: theirsRegion.join(""),
};
conflicts.push(conflict);
output.push(
marker(`<<<<<<< ${safeLabel(request.oursName, "ours")}`),
...withSectionEnding(oursRegion),
marker("||||||| base"),
...withSectionEnding(baseRegion),
marker("======="),
...withSectionEnding(theirsRegion),
marker(`>>>>>>> ${safeLabel(request.theirsName, "theirs")}`),
);
}
cursor = regionEnd;
}
output.push(...base.slice(cursor));
return result(
request,
output.join(""),
conflicts,
conflicts.length
? [
{
code: "merge.conflicts",
message: `${conflicts.length} conflict(s) require review.`,
severity: "warning",
side: "both",
},
]
: [
notice(
"merge.clean",
"Changes were merged without overlapping edits.",
),
],
);
}
function editsFor(
base: string[],
variant: string[],
side: Edit["side"],
): Edit[] {
const changes = diffArrays(base, variant, {
timeout: DIFF_LIMITS.diffTimeoutMilliseconds,
maxEditLength: DIFF_LIMITS.maxEditLength,
});
if (!changes)
throw new RangeError(
"Three-way merge exceeded the edit-distance or time limit.",
);
const edits: Edit[] = [];
let cursor = 0;
let index = 0;
while (index < changes.length) {
const change = changes[index]!;
if (!change.added && !change.removed) {
cursor += change.value.length;
index += 1;
continue;
}
const start = cursor;
const replacement: string[] = [];
while (index < changes.length) {
const part = changes[index]!;
if (!part.added && !part.removed) break;
if (part.removed) cursor += part.value.length;
if (part.added) replacement.push(...part.value);
index += 1;
}
edits.push({ start, end: cursor, replacement, side });
}
return edits;
}
function applyRegion(
base: string[],
start: number,
end: number,
edits: Edit[],
): string[] {
const output: string[] = [];
let cursor = start;
for (const edit of edits.sort(
(left, right) => left.start - right.start || left.end - right.end,
)) {
output.push(...base.slice(cursor, edit.start), ...edit.replacement);
cursor = edit.end;
}
output.push(...base.slice(cursor, end));
return output;
}
function lineTokens(value: string): string[] {
if (!value) return [];
const tokens = value.match(/[^\r\n]*(?:\r\n|\r|\n)|[^\r\n]+$/gu) ?? [];
if (tokens.length > DIFF_LIMITS.maxTokensPerSide)
throw new RangeError("Three-way merge exceeds the line-token limit.");
return tokens;
}
function equalTokens(
left: readonly string[],
right: readonly string[],
): boolean {
return (
left.length === right.length &&
left.every((value, index) => value === right[index])
);
}
function marker(value: string): string {
return `${value}\n`;
}
function withSectionEnding(tokens: readonly string[]): string[] {
if (!tokens.length) return [];
const output = [...tokens];
const last = output.at(-1)!;
if (!/(?:\r\n|\r|\n)$/u.test(last)) output[output.length - 1] = `${last}\n`;
return output;
}
function safeLabel(value: string | undefined, fallback: string): string {
return (value || fallback).replace(/[\r\n]/gu, " ").slice(0, 100);
}
function lineNumberAt(tokens: readonly string[], offset: number): number {
return tokens
.slice(0, offset)
.reduce(
(lines, token) => lines + (/(?:\r\n|\r|\n)$/u.test(token) ? 1 : 0),
1,
);
}
function notice(code: string, message: string): Diagnostic {
return { code, message, severity: "info", side: "both" };
}
function result(
request: MergeRequest,
text: string,
conflicts: MergeConflict[],
diagnostics: Diagnostic[],
): MergeResult {
const bounded = assertOutput(text, "Merged output length");
const reportObject = {
schema: "de.add-ideas.diff-tools.merge-report.v1",
schemaVersion: 1,
generatedLocally: true,
clean: conflicts.length === 0,
conflicts,
diagnostics,
inputCharacters: {
base: request.base.length,
ours: request.ours.length,
theirs: request.theirs.length,
},
};
return {
text: bounded,
clean: conflicts.length === 0,
conflicts,
diagnostics,
report: assertOutput(
`${JSON.stringify(reportObject, null, 2)}\n`,
"Merge report length",
),
};
}
+50 -33
View File
@@ -1,4 +1,9 @@
import {
startWorkerJob,
WorkerJobTimeoutError,
} from "@add-ideas/toolbox-helpers";
import { compareInputs } from "./compare";
import { DIFF_LIMITS } from "./limits";
import {
DiffToolsError,
type CompareRequest,
@@ -6,19 +11,17 @@ import {
type DiffResult,
} from "./types";
type WorkerResponse =
| { id: number; ok: true; result: DiffResult }
| { id: number; ok: false; message: string; diagnostics: Diagnostic[] };
interface SerializedCompareError {
message: string;
diagnostics: Diagnostic[];
}
export interface CompareTask {
promise: Promise<DiffResult>;
cancel(): void;
}
let nextId = 0;
export function createCompareTask(request: CompareRequest): CompareTask {
const id = ++nextId;
if (typeof Worker === "undefined") {
let cancelled = false;
return {
@@ -36,42 +39,56 @@ export function createCompareTask(request: CompareRequest): CompareTask {
new URL("../workers/diff.worker.ts", import.meta.url),
{ type: "module", name: "diff-tools-comparator" },
);
let settled = false;
let rejectPromise: ((reason?: unknown) => void) | undefined;
const promise = new Promise<DiffResult>((resolve, reject) => {
rejectPromise = reject;
worker.onmessage = (event: MessageEvent<WorkerResponse>) => {
if (event.data.id !== id || settled) return;
settled = true;
worker.terminate();
if (event.data.ok) resolve(event.data.result);
else
reject(new DiffToolsError(event.data.message, event.data.diagnostics));
};
worker.onerror = (event) => {
if (settled) return;
settled = true;
worker.terminate();
reject(
new DiffToolsError(event.message || "The comparison worker failed.", [
const task = startWorkerJob<
CompareRequest,
DiffResult,
never,
SerializedCompareError
>(worker, request, {
timeoutMs: DIFF_LIMITS.workerTimeoutMilliseconds,
deserializeError: (error) =>
new DiffToolsError(error.message, error.diagnostics),
workerFailureMessage: "The comparison worker failed.",
});
const promise = task.promise.catch((error: unknown) => {
if (error instanceof WorkerJobTimeoutError) {
throw new DiffToolsError(
`Comparison exceeded the ${DIFF_LIMITS.workerTimeoutMilliseconds / 1000}-second worker safety limit.`,
[
{
code: "worker.failure",
message: event.message || "The comparison worker failed.",
code: "worker.timeout",
message:
"The disposable comparison worker was terminated before it completed.",
severity: "error",
side: "both",
},
]),
],
);
};
worker.postMessage({ id, request });
}
if (
error instanceof DiffToolsError ||
(error instanceof DOMException && error.name === "AbortError")
)
throw error;
throw new DiffToolsError(
error instanceof Error ? error.message : "The comparison worker failed.",
[
{
code: "worker.failure",
message:
error instanceof Error
? error.message
: "The comparison worker failed.",
severity: "error",
side: "both",
},
],
);
});
return {
promise,
cancel() {
if (settled) return;
settled = true;
worker.terminate();
rejectPromise?.(new DOMException("Comparison cancelled.", "AbortError"));
task.cancel("Comparison cancelled.");
},
};
}
+107 -9
View File
@@ -115,13 +115,27 @@ textarea {
.hero,
.panel,
.mode-tabs,
.result-tabs {
.result-tabs,
.workspace-tabs {
border: 1px solid var(--toolbox-border);
border-radius: 0.9rem;
background: var(--toolbox-surface);
box-shadow: 0 8px 28px rgb(30 36 70 / 4%);
}
.workspace-tabs {
display: flex;
gap: 0.35rem;
padding: 0.35rem;
overflow-x: auto;
}
.workspace-tabs button[aria-current="page"] {
border-color: var(--toolbox-accent);
background: var(--toolbox-accent);
color: var(--toolbox-accent-contrast);
}
.hero {
display: flex;
justify-content: space-between;
@@ -179,40 +193,122 @@ textarea {
margin-bottom: 0.9rem;
}
.button-row {
display: flex;
flex-wrap: wrap;
gap: 0.45rem;
align-items: center;
}
.directory-inputs {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.8rem;
margin: 0.9rem 0;
}
.directory-inputs article {
min-width: 0;
padding: 0.8rem;
border: 1px solid var(--toolbox-border);
border-radius: 0.7rem;
background: var(--toolbox-surface-soft);
}
.directory-inputs article p,
.option-note {
color: var(--toolbox-muted);
font-size: 0.78rem;
line-height: 1.5;
}
.manifest-filter {
margin: 1rem 0 0.65rem;
}
.table-scroll {
max-height: 34rem;
overflow: auto;
border: 1px solid var(--toolbox-border);
border-radius: 0.7rem;
}
.table-scroll table {
width: 100%;
border-collapse: collapse;
font-size: 0.78rem;
}
.table-scroll th,
.table-scroll td {
padding: 0.55rem 0.65rem;
border-bottom: 1px solid var(--toolbox-border);
text-align: left;
vertical-align: top;
}
.table-scroll thead th {
position: sticky;
top: 0;
z-index: 1;
background: var(--toolbox-surface-soft);
}
.merge-inputs {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 0.75rem;
margin: 0.9rem 0;
}
.merge-inputs textarea {
min-height: 14rem;
}
.merge-result {
margin-top: 1rem;
padding-top: 1rem;
border-top: 1px solid var(--toolbox-border);
}
.merge-result textarea {
min-height: 22rem;
}
.mode-tabs,
.result-tabs {
padding: 0.35rem;
overflow-x: auto;
}
.mode-tabs [role="tablist"],
.result-tabs [role="tablist"] {
.mode-tabs [role="group"],
.result-tabs [role="group"] {
display: flex;
gap: 0.35rem;
min-width: max-content;
}
.mode-tabs [role="tab"] {
.mode-tabs button {
min-width: 9.5rem;
flex-direction: column;
align-items: flex-start;
line-height: 1.2;
}
.mode-tabs [role="tab"] small {
.mode-tabs button small {
color: var(--toolbox-muted);
font-size: 0.7rem;
font-weight: 580;
}
.mode-tabs [role="tab"][aria-selected="true"],
.result-tabs [role="tab"][aria-selected="true"] {
.mode-tabs button[aria-pressed="true"],
.result-tabs button[aria-pressed="true"] {
border-color: var(--toolbox-accent);
background: var(--toolbox-accent);
color: var(--toolbox-accent-contrast);
}
.mode-tabs [role="tab"][aria-selected="true"] small {
.mode-tabs button[aria-pressed="true"] small {
color: inherit;
opacity: 0.84;
}
@@ -734,7 +830,9 @@ textarea {
@media (max-width: 52rem) {
.input-grid,
.metadata-grid,
.paired-lines {
.paired-lines,
.directory-inputs,
.merge-inputs {
grid-template-columns: 1fr;
}
.paired-lines > div + div {
+53 -3
View File
@@ -3,12 +3,22 @@
"schemaVersion": 1,
"id": "de.add-ideas.diff-tools",
"name": "Diff Tools",
"version": "0.1.0",
"description": "Compare text and structured data locally in the browser.",
"version": "0.2.0",
"description": "Compare files and directories or perform bounded three-way merges locally.",
"entry": "./",
"icon": "./favicon.svg",
"categories": ["developer", "files", "productivity"],
"tags": ["diff", "compare", "json", "xml", "csv", "patch"],
"tags": [
"diff",
"compare",
"json",
"xml",
"csv",
"patch",
"directory",
"manifest",
"merge"
],
"integration": {
"contextVersion": 1,
"launchModes": ["navigate", "new-tab"],
@@ -21,6 +31,46 @@
"crossOriginIsolated": false,
"topLevelContext": false
},
"io": {
"accepts": [
{
"mediaType": "text/*",
"extensions": [".txt", ".md", ".csv", ".xml"],
"label": "Text, CSV and XML files"
},
{
"mediaType": "application/json",
"extensions": [".json"],
"label": "JSON documents and directory manifests"
},
{
"mediaType": "*/*",
"extensions": [],
"label": "Files selected for bounded directory hashing"
}
],
"produces": [
{
"mediaType": "text/x-diff",
"extensions": [".diff", ".patch"],
"label": "Unified and JSON patches"
},
{
"mediaType": "text/plain",
"extensions": [".txt"],
"label": "Three-way merge result"
},
{
"mediaType": "application/json",
"extensions": [".json"],
"label": "Diff, merge and directory-manifest reports"
}
]
},
"capabilities": {
"required": ["workers"],
"optional": ["web-crypto"]
},
"privacy": {
"processing": "local",
"fileUploads": true,
+1 -1
View File
@@ -1 +1 @@
export const APP_VERSION = "0.1.0";
export const APP_VERSION = "0.2.0";
+11 -24
View File
@@ -1,30 +1,17 @@
/// <reference lib="webworker" />
import { createWorkerJobMessageHandler } from "@add-ideas/toolbox-helpers";
import { compareInputs, serializeFailure } from "../core/compare";
import type { CompareRequest, DiffResult } from "../core/types";
interface WorkerRequest {
id: number;
request: CompareRequest;
}
type WorkerResponse =
| { id: number; ok: true; result: DiffResult }
| {
id: number;
ok: false;
message: string;
diagnostics: ReturnType<typeof serializeFailure>["diagnostics"];
};
self.onmessage = (event: MessageEvent<WorkerRequest>) => {
const { id, request } = event.data;
let response: WorkerResponse;
try {
response = { id, ok: true, result: compareInputs(request) };
} catch (error) {
response = { id, ok: false, ...serializeFailure(error) };
}
self.postMessage(response);
};
self.onmessage = createWorkerJobMessageHandler<
CompareRequest,
DiffResult,
never,
ReturnType<typeof serializeFailure>
>(
(request) => compareInputs(request),
(response) => self.postMessage(response),
{ serializeError: serializeFailure },
);
export {};
+51 -6
View File
@@ -25,7 +25,9 @@ function auditPage(page: Page) {
async function openApp(page: Page) {
await page.goto(APP_PATH);
await expect(
page.getByRole("heading", { name: "Diff Tools", exact: true }),
page
.locator(".hero")
.getByRole("heading", { name: "Diff Tools", exact: true }),
).toBeVisible();
await expect(page.getByText(/substantive change row/u)).toBeVisible();
}
@@ -60,19 +62,19 @@ test("exports exact-decimal JSON Patch without losing the prior result", async (
}) => {
const audit = auditPage(page);
await openApp(page);
await page.getByRole("tab", { name: /JSON Semantic/u }).click();
await page.getByRole("button", { name: /JSON Semantic/u }).click();
await page.getByTestId("left-editor").fill('{"amount":1,"keep":true}');
await page
.getByTestId("right-editor")
.fill('{"amount":9007199254740993123456789,"keep":true}');
await page.getByRole("button", { name: "Compare now" }).click();
await expect(page.getByText(/1 substantive change row/u)).toBeVisible();
await page.getByRole("tab", { name: "Patches" }).click();
await page.getByRole("button", { name: "Patches" }).click();
await expect(page.getByTestId("json-patch")).toContainText(
"9007199254740993123456789",
);
await page.getByRole("tab", { name: /XML Namespace-aware/u }).click();
await page.getByRole("button", { name: /XML Namespace-aware/u }).click();
await expect(page.getByText(/substantive change row/u)).toBeVisible();
const previousVerdict = page.getByText("Different", { exact: true }).first();
await expect(previousVerdict).toBeVisible();
@@ -87,7 +89,7 @@ test("exports exact-decimal JSON Patch without losing the prior result", async (
test("opens local keyed CSV and reports duplicate keys", async ({ page }) => {
const audit = auditPage(page);
await openApp(page);
await page.getByRole("tab", { name: /CSV \/ TSV Keyed rows/u }).click();
await page.getByRole("button", { name: /CSV \/ TSV Keyed rows/u }).click();
await page.getByTestId("left-file-input").setInputFiles({
name: "duplicates.csv",
mimeType: "text/csv",
@@ -118,8 +120,51 @@ test("serves the release identity and hardened headers", async ({
const manifest = await request.get(`${APP_PATH}toolbox-app.json`);
await expect(manifest.json()).resolves.toMatchObject({
id: "de.add-ideas.diff-tools",
version: "0.1.0",
version: "0.2.0",
entry: "./",
privacy: { processing: "local", fileUploads: true, telemetry: false },
});
});
test("runs the bounded three-way merge workspace", async ({ page }) => {
await page.goto("/deep/nested/diff/");
await page.getByRole("button", { name: "Three-way merge" }).click();
await page.getByLabel("Base").fill("one\ntwo\nthree\n");
await page.getByLabel("Ours").fill("ONE\ntwo\nthree\n");
await page.getByLabel("Theirs").fill("one\ntwo\nTHREE\n");
await page.getByRole("button", { name: "Merge locally" }).click();
await expect(page.getByTestId("merge-output")).toHaveValue(
"ONE\ntwo\nTHREE\n",
);
await expect(
page.getByRole("heading", { name: "0 conflict(s)" }),
).toBeVisible();
});
test("imports and compares portable directory manifests", async ({ page }) => {
await page.goto("/deep/nested/diff/");
await page.getByRole("button", { name: "Directories" }).click();
const manifest = (digest: string) => ({
schema: "de.add-ideas.diff-tools.directory-manifest.v1",
schemaVersion: 1,
generatedLocally: true,
hashAlgorithm: "SHA-256",
entries: [{ path: "file.txt", bytes: 4, sha256: digest }],
totals: { files: 1, bytes: 4 },
});
const inputs = page.locator('input[accept*="application/json"]');
await inputs.nth(0).setInputFiles({
name: "left.json",
mimeType: "application/json",
buffer: Buffer.from(JSON.stringify(manifest("a".repeat(64)))),
});
await inputs.nth(1).setInputFiles({
name: "right.json",
mimeType: "application/json",
buffer: Buffer.from(JSON.stringify(manifest("b".repeat(64)))),
});
await page.getByRole("button", { name: "Build & compare manifests" }).click();
await expect(
page.getByRole("row", { name: /file\.txt modified/iu }),
).toBeVisible();
});
+18
View File
@@ -0,0 +1,18 @@
import { expect, test } from "@playwright/test";
test("keeps the primary workspace inside a narrow viewport", async ({
page,
}) => {
await page.goto("/deep/nested/diff/");
await expect(page.locator("main").first()).toBeVisible();
await expect(
page.locator("main .loading, main .workbench-loading"),
).toHaveCount(0);
const widths = await page.evaluate(() => ({
content: document.documentElement.scrollWidth,
viewport: document.documentElement.clientWidth,
}));
expect(widths.viewport).toBeLessThanOrEqual(430);
expect(widths.content).toBeLessThanOrEqual(widths.viewport + 1);
});
+6 -4
View File
@@ -10,7 +10,7 @@ describe("Diff Tools workbench", () => {
expect(screen.getByText("Browser-local")).toBeVisible();
expect(await screen.findByText(/substantive change row/u)).toBeVisible();
expect(screen.getAllByText("CRLF").length).toBeGreaterThan(0);
await user.click(screen.getByRole("tab", { name: "Side by side" }));
await user.click(screen.getByRole("button", { name: "Side by side" }));
expect(
screen.getByRole("table", { name: "Side-by-side differences" }),
).toBeVisible();
@@ -19,7 +19,7 @@ describe("Diff Tools workbench", () => {
it("keeps exact large numbers in the RFC 6902 artifact", async () => {
const user = userEvent.setup();
render(<Workbench />);
await user.click(screen.getByRole("tab", { name: /JSON Semantic/u }));
await user.click(screen.getByRole("button", { name: /JSON Semantic/u }));
fireEvent.change(screen.getByTestId("left-editor"), {
target: { value: '{"n":1}' },
});
@@ -30,7 +30,7 @@ describe("Diff Tools workbench", () => {
await waitFor(() =>
expect(screen.getByText(/1 substantive change row/u)).toBeVisible(),
);
await user.click(screen.getByRole("tab", { name: "Patches" }));
await user.click(screen.getByRole("button", { name: "Patches" }));
expect(
(screen.getByTestId("json-patch") as HTMLTextAreaElement).value,
).toContain("9007199254740993123456789");
@@ -39,7 +39,9 @@ describe("Diff Tools workbench", () => {
it("keeps the last successful XML result visible beside an error", async () => {
const user = userEvent.setup();
render(<Workbench />);
await user.click(screen.getByRole("tab", { name: /XML Namespace-aware/u }));
await user.click(
screen.getByRole("button", { name: /XML Namespace-aware/u }),
);
expect(await screen.findByText(/substantive change row/u)).toBeVisible();
const verdict = screen.getByText("Different", { exact: true });
fireEvent.change(screen.getByTestId("left-editor"), {
+140
View File
@@ -0,0 +1,140 @@
import { describe, expect, it } from "vitest";
import {
compareDirectoryManifests,
createDirectoryManifest,
parseDirectoryManifest,
serializeDirectoryManifest,
} from "../../src/core/directory-manifest";
import { mergeThreeWay } from "../../src/core/merge";
function file(path: string, value: string): File {
const item = new File([value], path.split("/").at(-1)!, {
lastModified: Date.UTC(2026, 0, 1),
});
Object.defineProperty(item, "webkitRelativePath", {
value: `chosen-root/${path}`,
});
return item;
}
describe("directory manifests", () => {
it("hashes bounded files deterministically and strips the selected root", async () => {
const first = await createDirectoryManifest([
file("z.txt", "last"),
file("nested/a.txt", "first"),
]);
const second = await createDirectoryManifest([
file("nested/a.txt", "first"),
file("z.txt", "last"),
]);
expect(first.entries.map((entry) => entry.path)).toEqual([
"nested/a.txt",
"z.txt",
]);
expect(first.entries).toEqual(second.entries);
expect(parseDirectoryManifest(serializeDirectoryManifest(first))).toEqual(
first,
);
});
it("compares content digests rather than timestamps", async () => {
const left = await createDirectoryManifest([
file("same.txt", "same"),
file("changed.txt", "before"),
file("removed.txt", "gone"),
]);
const right = await createDirectoryManifest([
file("same.txt", "same"),
file("changed.txt", "after"),
file("added.txt", "new"),
]);
expect(
compareDirectoryManifests(left, right).map(({ path, status }) => ({
path,
status,
})),
).toEqual([
{ path: "added.txt", status: "added" },
{ path: "changed.txt", status: "modified" },
{ path: "removed.txt", status: "removed" },
{ path: "same.txt", status: "same" },
]);
});
it("rejects traversal and inconsistent imported totals", async () => {
await expect(
createDirectoryManifest([file("../escape.txt", "bad")]),
).rejects.toThrow(/unsafe/iu);
const manifest = await createDirectoryManifest([file("safe.txt", "ok")]);
const serialized = JSON.stringify({
...manifest,
totals: { files: 1, bytes: 999 },
});
expect(() => parseDirectoryManifest(serialized)).toThrow(/totals/iu);
});
it("rejects case-normalized collisions and invalid timestamps on import", async () => {
const manifest = await createDirectoryManifest([file("safe.txt", "ok")]);
const duplicate = {
...manifest,
entries: [
manifest.entries[0],
{ ...manifest.entries[0], path: "SAFE.txt" },
],
totals: { files: 2, bytes: manifest.totals.bytes * 2 },
};
expect(() => parseDirectoryManifest(JSON.stringify(duplicate))).toThrow(
/collision/iu,
);
expect(() =>
parseDirectoryManifest(
JSON.stringify({
...manifest,
entries: [{ ...manifest.entries[0], lastModified: "not-a-date" }],
}),
),
).toThrow(/fields/iu);
});
});
describe("bounded three-way merge", () => {
it("combines non-overlapping line changes without conflict", () => {
const result = mergeThreeWay({
base: "one\ntwo\nthree\n",
ours: "ONE\ntwo\nthree\n",
theirs: "one\ntwo\nTHREE\n",
});
expect(result.clean).toBe(true);
expect(result.text).toBe("ONE\ntwo\nTHREE\n");
});
it("emits explicit ours/base/theirs markers for overlapping changes", () => {
const result = mergeThreeWay({
base: "same\nvalue\n",
ours: "same\nours\n",
theirs: "same\ntheirs\n",
oursName: "working.txt",
theirsName: "incoming.txt",
});
expect(result.clean).toBe(false);
expect(result.conflicts).toHaveLength(1);
expect(result.text).toContain("<<<<<<< working.txt");
expect(result.text).toContain("||||||| base");
expect(result.text).toContain(">>>>>>> incoming.txt");
expect(JSON.parse(result.report)).toMatchObject({
schema: "de.add-ideas.diff-tools.merge-report.v1",
clean: false,
});
});
it("keeps conflict markers on their own lines when inputs lack final newlines", () => {
const result = mergeThreeWay({
base: "base",
ours: "ours",
theirs: "theirs",
});
expect(result.text).toBe(
"<<<<<<< ours\nours\n||||||| base\nbase\n=======\ntheirs\n>>>>>>> theirs\n",
);
});
});