Repository navigation
feat(engine): repair without corrupting, align array diffs, and format at scale - #8
Merged
Merged
Conversation
The wildcard let the left-hand document use `*` as a key or value that matched anything, turning the diff into a template matcher. It was never documented -- no README mention, no UI affordance -- and it was the largest source of branching in the engine: `compareObjects` carried two entirely separate implementations, and the wildcard path silently skipped the strict-mode key handling the normal path applies. Removing it collapses `compareObjects` to one code path and drops the value-level early return from `compareJson`, which makes the array alignment and null-semantics work that follows tractable. 41 wildcard tests removed with it; the remaining 225 pass. Co-Authored-By: Claude Opus 5 <[email protected]>
…ates Four defects, each of which could produce a wrong document rather than just a confusing one. `null` was conflated with absence. A key changing from null to a value reported as "added", and a key changing to null reported as "removed" -- so applying that change *deleted the key* instead of setting it to null. Presence is now decided by key membership alone, never by value. Arrays compared strictly by index, so inserting one element at the head of a hundred-element array reported a hundred modifications. Arrays are now aligned first: by an identity key (id/_id/uuid/key/name) when both sides carry a unique one, otherwise by a longest-common-subsequence pass with matching heads and tails stripped, falling back to index comparison above a size budget. Adjacent removals and insertions are zipped into modifications, so replacing an element in place still reads as one change rather than an unrelated delete and insert. `applyDiffs` deep-cloned the whole document once per change, and spliced arrays one at a time -- each splice shifting the indices the remaining changes still referred to. It now clones once and rebuilds each array in a single pass, reading positions in the coordinates of the document the comparison ran against. The result no longer depends on the order the changes are applied in, which is what the diff view needs: undoing a row re-derives the document from the original with that change left out, rather than trying to un-mutate in place. Missing intermediate containers were created as arrays whenever the next path segment looked numeric, turning an object keyed "0" into an array. Each segment now records whether it is a key or an index. Also: the comparison walks an explicit stack instead of recursing, and carries paths as a shared chain materialised only when a change is emitted -- copying the path array at every level made a 50,000-deep comparison take 5.4s, now 43ms. And the diff view stops recomputing the comparison it already holds just to render it. The node jest project now matches `__tests__/*.test.ts` instead of listing files, which is why the new suite runs at all. 296 tests pass, up from 225. Co-Authored-By: Claude Opus 5 <[email protected]>
The old parser repaired input by running regular expressions over the
whole document -- quoting bare property names, rewriting Python
literals, stripping trailing commas. None of those passes knew where a
string started or ended, so they rewrote string contents too. Verified
against the shipped code:
{'note': "True story about None"} -> {note: "true story about null"}
{a: "x, b: 1"} -> {"a": "x, "b": 1"}
{a: "ends with , ]"} -> {a: "ends with ]"}
The first silently changes what the document says. The second produces
invalid JSON out of valid intent. All three only trigger once something
else in the document fails JSON.parse -- which is exactly the repair
path this tool exists to provide.
Replaced with a scanner and a recursive-descent parser that recovers in
place. A quoted string is consumed as one token and never examined
again, so that class of damage is not possible. Repairs also compose:
they used to run as a fixed sequence of separate passes, so `{"a": 1,`
-- a trailing comma *and* a missing brace -- threw, though either alone
was handled. It now parses.
Parsing no longer throws. Broken input is repaired as far as it can be
and shown, which is the point: the tool should fix JSON, not judge it.
Each repair is recorded with a kind, a severity and a position, and the
panel lists them under the toolbar -- replacing a banner that said only
that "errors were corrected automatically", without saying what or
where. Clicking a row puts the caret on the offending line.
Cosmetic repairs (quoting, Python literals, comments) are separated
from structural ones (missing commas, unclosed containers), so tidying
up quoting no longer reads as loudly as inventing a brace. The diff view
reports repairs too, since a difference could otherwise be an artefact
of one.
Also adds --jb-marker-{warn,error,info} mapped to the editorWarning /
editorError colours. The panel first used inputValidation-warningForeground,
which is the text colour *for* that validation panel -- in Light Modern
it is near-black, so severity was invisible there. Caught by rendering
both themes, not by the tests.
The parser is iterative, so deeply nested input cannot overflow the
stack, and the scanner reads from a CharSource rather than a string so
the same code can later run over chunked storage.
334 tests pass, up from 296. Of the 200 existing parser cases, 189
passed unchanged; the 3 that asserted throwing and 8 that asserted the
old suggestion strings now assert the new contract.
Co-Authored-By: Claude Opus 5 <[email protected]>
Formatting built the whole document as one HTML string and handed it to innerHTML: a div per line, a div per gutter entry, and -- because each level wrapped every line its children had produced -- a `foldable-content` span per line per level of nesting. The markup therefore grew with depth as well as with length, and a large file meant hundreds of thousands of elements and a freeze measured in seconds. Folding then hid those elements one at a time and hunted down each of their gutter entries, and the status bar re-serialised the entire document on every format just to count its lines. Replaced with a document model and a virtual list: - The parser drives a sink rather than always building a value, so formatting goes straight from the parse to text. A 200 MB document becomes about a gigabyte of JavaScript objects but only about as much text as it started with, so this is the difference between working and not. `ValueSink` keeps the old behaviour for the diff view. - Text is held in chunks, so nothing is copied to grow it and the engine's maximum string length is not a ceiling. - Lines are three numbers in typed arrays -- start, depth, and the line that closes the container opening here -- about twelve bytes each. - Folding is a change to that index, not to the output. Collapsed folds are a short list of hidden ranges, so folding a node the size of the document costs the same as folding a small one. - Only rows in view are rendered; the element count follows the window height, not the document. Past ~33 million pixels browsers stop scrolling, so beyond that the spacer is capped and the scroll position maps onto rows by proportion. Search moved with it, because walking the rendered DOM stops being possible when most of the document has no DOM -- and walking it was what made searching slow: it looped every text node against every match, so 50,000 nodes and 5,000 matches meant a quarter of a billion comparisons, on every keystroke, with no debounce. Matching now runs over the text a line at a time and yields line and column numbers, which stay meaningful whether or not a row is on screen. Typing is debounced, matching stops at 50,000 hits, and the find widget no longer searches anything itself. Measured on a 3 MB document of 25,000 records: 325,004 lines formatted in 467ms, 25 rows and 168 elements in the DOM, and a search that matches one line out of 325,004 finds and reveals it with the panel responsive throughout. The gutter number now lives inside its row rather than in a parallel column, since two columns had to be scrolled and folded in step. 364 tests pass, up from 334. formatter.test.ts follows renderJson being replaced by renderLine, and find-widget.test.ts follows the debounce. src/webview/search.ts is deleted. Co-Authored-By: Claude Opus 5 <[email protected]>
The work PR #7 shipped without. Panels are serialised, so a window reload no longer throws away whatever was pasted: `registerWebviewPanelSerializer` adopts the panel VS Code offers back, and the webview keeps mode, input and toggles in setState. Writes are coalesced and anything over 512 KB is dropped rather than carried, since the whole state is re-serialised on each write and reformatting is cheaper than stalling every keystroke. Sidebar history moves to globalState. It was a plain array on the tree provider, so every entry a user saved vanished on restart -- which made the feature close to pointless. Entries now carry a timestamp and a size and are described as "3 minutes ago - 12.4 KB" instead of "Entry 1" plus a raw fifty-character slice, which all look alike when they start with `{"`. Documents over 256 KB are stored as a preview and say so, rather than keeping fifty large documents in global state forever. `getChildren` dispatched on the item's *label* matching the string 'Format History', so renaming a heading would have silently emptied the tree under it; items carry a typed kind now. Added a "Clear history" title action. contributes.configuration adds nine settings -- line numbers, indent size, strict diff, pane ratio, format on paste, default search scope, and the three limits the engines now respect. They are pushed to open panels on the ready handshake and again whenever they change. The diff view reports the document-size limit plainly instead of attempting a comparison that will not fit. `jsonbro.loadFormatHistory` and `jsonbro.loadDiffHistory` were registered in code but absent from contributes; they are declared now, and hidden from the palette since they take arguments. Also: .vscodeignore was packaging the preview harness output and .claude/launch.json into the .vsix -- vsce includes untracked files unless they are named there. Verified with `vsce ls`: 60 files, media and out only. README.md untouched, as asked. 400 tests pass, up from 375. Co-Authored-By: Claude Opus 5 <[email protected]>
Rendering stopped being the bottleneck in the previous commit; parsing took its place. Formatting a 3 MB document took 467ms on the panel's own thread, which for a few hundred megabytes is long enough to lock the window for the duration -- and the input still had to arrive through a textarea, which is not a viable way to hand over a very large file. The engine now runs in a worker. Formatting the same 3 MB document returns control to the panel in 1ms rather than 467ms; the result arrives when it is ready. Small documents are still formatted in place, since below a couple of megabytes the round trip costs more than it saves, and the threshold is jsonbro.maxInlineSize. The worker also reads files itself. `JSONBro: Open JSON File` widens the panel's resource roots to the chosen file's folder and sends only its URI; the worker streams it with fetch and a streaming TextDecoder straight into chunked storage. The text never crosses postMessage and never enters a textarea. Progress is reported while it reads. The line index crosses the thread boundary as transferable buffers, so it moves rather than copies. The text chunks are copied -- strings are not transferable -- but that is one copy at the end of a long job, against the alternative of the panel being unresponsive throughout. The worker is a third webpack bundle rather than an inlined script because the content security policy allows worker-src from the webview's own origin but not blob: URLs. CSP gains worker-src and connect-src. If the worker cannot start, formatting falls back to the panel's thread rather than failing: slower, but working. Results carry a token so a format that has been overtaken by a newer one is discarded instead of overwriting it. Verified in a browser against the real bundles: 3 MB and 325,004 lines, click returns in 1ms, no console errors, output correct. Co-Authored-By: Claude Opus 5 <[email protected]>
LucianCrainic
added a commit
that referenced
this pull request
Aug 15, 2026
feat(engine): repair without corrupting, align array diffs, and format at scale
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Follows #7, which rebuilt the UI and deliberately left the engines alone. This is the engines:
json-parser.ts,diff.ts,search.tsandformatter.tswere all still pre-revamp code, plus the persistence and settings work #7 shipped without.The parser was corrupting data
Repairs ran as regular expressions over the whole document — quoting bare property names, rewriting Python literals, stripping trailing commas. None of those passes knew where a string started or ended. Verified against the shipped code:
{'note': "True story about None"}{note: "true story about null"}{a: "x, b: 1"}{"a": "x, "b": 1"}{a: "ends with , ]"}{a: "ends with ]"}The first silently changes what the document says. The second turns valid intent into invalid JSON. All three only trigger once something else in the document fails
JSON.parse— which is exactly the repair path this tool exists to provide.Replaced with a scanner and a recovering parser. A quoted string is consumed as one token and never examined again, so that class of damage is not possible. Repairs also compose now: they used to run as a fixed sequence of separate passes, so
{"a": 1,— a trailing comma and a missing brace — threw, though either alone was handled.Parsing no longer throws. Broken input is repaired as far as it can be and shown, with each repair named, placed on a line, and listed under the toolbar. That replaces a banner that said only that "errors were corrected automatically", without saying what or where.
The diff engine had four real bugs
nullwas conflated with absence. A key changing fromnullto a value reported as added, and a key changing tonullreported as removed — so applying that change deleted the key instead of setting it. Data loss.applyDiffsdeep-cloned the whole document once per change, and spliced arrays one at a time, each splice shifting the indices the remaining changes still referred to."0"into an array.Arrays are now aligned first — by identity key where both sides carry a unique one, otherwise by longest common subsequence with matching heads and tails stripped, falling back to index comparison above a budget. Changes are applied in the coordinates of the document they were computed against, so the result no longer depends on the order rows are resolved in.
*wildcard removedIt let the left document use
*as a key or value matching anything. Undocumented — no README mention, no UI affordance — and the largest source of branching in the engine:compareObjectscarried two separate implementations and the wildcard path silently skipped strict-mode handling.Large documents
Formatting built the whole document as one HTML string: a div per line, a div per gutter entry, and a
foldable-contentspan per line per level of nesting, so markup grew with depth as well as length. Folding then hid those elements one at a time; the status bar re-serialised the entire document on every format just to count its lines.The parser now drives a sink rather than always building a value, so formatting goes from the parse straight to text — a 200 MB document becomes about a gigabyte of objects but only about as much text as it started with. Lines are three numbers in typed arrays. Folding is a change to that index, not to the output. Only rows in view are rendered.
Measured on a 3 MB document of 25,000 records:
The engine runs in a worker, and
JSONBro: Open JSON Filelets the worker stream a file itself — the text never crossespostMessageand never enters a textarea. Past ~33 million pixels browsers stop scrolling, so beyond that the spacer is capped and scroll position maps onto rows proportionally.Search
It walked the rendered DOM: one string built from every text node, then, for each node, a loop over every match — so cost grew as nodes × matches. 50,000 nodes against 5,000 matches meant a quarter of a billion comparisons, on every keystroke, with no debounce. It also could not survive virtual rendering, where most of the document has no nodes.
Matching now runs over the text a line at a time and yields line and column numbers, which stay meaningful whether or not a row is on screen. Typing is debounced; matching stops at 50,000 hits.
What #7 left out
State persistence and a panel serializer (content survives a reload), history in
globalStatewith relative time and size instead ofEntry 1(it was an in-memory array wiped on every restart), a typedkindon tree items replacing dispatch on the label string, a clear-history action, nine settings, keybindings, and the two commands that were registered in code but absent fromcontributes.Reviewer notes
revertDiffis no longer used in production and is documented as single-change only; undoing a row re-derives the document from the original with that change left out. Undoing several in sequence is not sound where arrays restructure, and the tests say so rather than pretending otherwise.worker-srcfrom the webview origin but notblob:. If that copy step breaks, formatting silently falls back to the panel's thread..vscodeignorewas packaging dev files into the.vsix— vsce includes untracked files unless named there. Now 66 files,media/andout/only.inputValidation-warningForeground, which is the text colour for that panel — near-black in Light Modern, so severity was invisible there.Not included
autoFormatOnPasteis declared and plumbed but not yet acted on.jsonbro.diff.maxDocumentSizethe view says so rather than freezing. Formatting is unbounded; diffing is not.Tests
400 passing, up from 266. The wildcard suite (~590 lines) is gone with the feature; of 200 existing parser cases 189 passed unchanged, and the 11 that did not asserted throwing or the old suggestion strings.
formatter.test.tsfollowsrenderJsonbecomingrenderLine.🤖 Generated with Claude Code