-
Notifications
You must be signed in to change notification settings - Fork 0
fix(json): preserve numeric lexemes when formatting #977
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
trac3r00
wants to merge
1
commit into
release/product-value-20260912-07
Choose a base branch
from
release/product-value-20260912-08
base: release/product-value-20260912-07
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| import { describe, expect, it } from "vitest"; | ||
| import { handleJSONFormatterRoutes } from "./json-formatter.js"; | ||
|
|
||
| describe("JSON formatter route", () => { | ||
| it("wires the lossless formatter into both browser actions", async () => { | ||
| const request = new Request("https://example.com/json-formatter"); | ||
| const response = await handleJSONFormatterRoutes( | ||
| request, | ||
| new URL(request.url), | ||
| ); | ||
| const html = await response.text(); | ||
|
|
||
| expect(html).toContain("function formatJsonLosslessly"); | ||
| expect(html).toContain("formatJsonLosslessly(input, 2)"); | ||
| expect(html).toContain("formatJsonLosslessly(input, 0)"); | ||
| }); | ||
| }); |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| /** | ||
| * Validate JSON and change only insignificant whitespace. | ||
| * | ||
| * JSON.parse remains the syntax oracle, while the lexical pass deliberately | ||
| * avoids serializing parsed numbers through JavaScript's Number type. | ||
| */ | ||
| export function formatJsonLosslessly(input, indent = 2) { | ||
| const text = String(input).trim(); | ||
| JSON.parse(text); | ||
|
|
||
| let gap = ""; | ||
| if (typeof indent === "number") { | ||
| const width = Math.min(10, Math.max(0, Math.trunc(indent))); | ||
| gap = " ".repeat(width); | ||
| } else if (typeof indent === "string") { | ||
| gap = indent.slice(0, 10); | ||
| } | ||
|
|
||
| let output = ""; | ||
| let depth = 0; | ||
| let inString = false; | ||
| let escaped = false; | ||
| let previousToken = ""; | ||
|
|
||
| for (let index = 0; index < text.length; index += 1) { | ||
| const character = text[index]; | ||
|
|
||
| if (inString) { | ||
| output += character; | ||
| if (escaped) { | ||
| escaped = false; | ||
| } else if (character === "\\") { | ||
| escaped = true; | ||
| } else if (character === '"') { | ||
| inString = false; | ||
| } | ||
| continue; | ||
| } | ||
|
|
||
| if ( | ||
| character === " " || | ||
| character === "\t" || | ||
| character === "\n" || | ||
| character === "\r" | ||
| ) { | ||
| continue; | ||
| } | ||
|
|
||
| if (character === '"') { | ||
| inString = true; | ||
| output += character; | ||
| } else if (character === "{" || character === "[") { | ||
| output += character; | ||
| depth += 1; | ||
|
|
||
| if (gap) { | ||
| let nextIndex = index + 1; | ||
| while ( | ||
| text[nextIndex] === " " || | ||
| text[nextIndex] === "\t" || | ||
| text[nextIndex] === "\n" || | ||
| text[nextIndex] === "\r" | ||
| ) { | ||
| nextIndex += 1; | ||
| } | ||
| const closing = character === "{" ? "}" : "]"; | ||
| if (text[nextIndex] !== closing) { | ||
| output += `\n${gap.repeat(depth)}`; | ||
| } | ||
| } | ||
| } else if (character === "}" || character === "]") { | ||
| depth -= 1; | ||
| if (gap && previousToken !== "{" && previousToken !== "[") { | ||
| output += `\n${gap.repeat(depth)}`; | ||
| } | ||
| output += character; | ||
| } else if (character === ",") { | ||
| output += gap ? `,\n${gap.repeat(depth)}` : ","; | ||
| } else if (character === ":") { | ||
| output += gap ? ": " : ":"; | ||
| } else { | ||
| output += character; | ||
| } | ||
|
|
||
| previousToken = character; | ||
| } | ||
|
|
||
| return output; | ||
| } |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| import { describe, expect, it } from "vitest"; | ||
| import { formatJsonLosslessly } from "./lossless-json.js"; | ||
|
|
||
| const LOSSLESS_INPUT = | ||
| '{"max":9007199254740993,"min":-9007199254740993,"huge":1e400,"fixed":1.2300,"negativeZero":-0,"nested":[[9007199254740993],{"text":"quote: \\" slash: \\\\"}]}'; | ||
|
|
||
| const LOSSLESS_PRETTY = [ | ||
| "{", | ||
| ' "max": 9007199254740993,', | ||
| ' "min": -9007199254740993,', | ||
| ' "huge": 1e400,', | ||
| ' "fixed": 1.2300,', | ||
| ' "negativeZero": -0,', | ||
| ' "nested": [', | ||
| " [", | ||
| " 9007199254740993", | ||
| " ],", | ||
| " {", | ||
| ' "text": "quote: \\" slash: \\\\"', | ||
| " }", | ||
| " ]", | ||
| "}", | ||
| ].join("\n"); | ||
|
|
||
| describe("formatJsonLosslessly", () => { | ||
| it("preserves numeric and escaped-string lexemes while formatting", () => { | ||
| expect(formatJsonLosslessly(LOSSLESS_INPUT, 2)).toBe(LOSSLESS_PRETTY); | ||
| }); | ||
|
|
||
| it("preserves numeric and escaped-string lexemes while minifying", () => { | ||
| const spaced = | ||
| ' { "max" : 9007199254740993, "min" : -9007199254740993, "huge" : 1e400, "fixed" : 1.2300, "negativeZero" : -0, "nested" : [ [ 9007199254740993 ], { "text" : "quote: \\" slash: \\\\" } ] } '; | ||
| expect(formatJsonLosslessly(spaced, 0)).toBe(LOSSLESS_INPUT); | ||
| }); | ||
|
|
||
| it("formats ordinary nested JSON with the requested indentation", () => { | ||
| expect(formatJsonLosslessly('{"a":1,"b":[true,false]}', 4)).toBe( | ||
| [ | ||
| "{", | ||
| ' "a": 1,', | ||
| ' "b": [', | ||
| " true,", | ||
| " false", | ||
| " ]", | ||
| "}", | ||
| ].join("\n"), | ||
| ); | ||
| }); | ||
|
|
||
| it("matches JSON.stringify indentation options for empty and nested values", () => { | ||
| expect(formatJsonLosslessly('{"empty":{},"items":[]}', "\t")).toBe( | ||
| ['{', '\t"empty": {},', '\t"items": []', '}'].join("\n"), | ||
| ); | ||
| expect(formatJsonLosslessly('{"a":1}', null)).toBe('{"a":1}'); | ||
| }); | ||
|
|
||
| it("rejects malformed JSON with the native parse error", () => { | ||
| expect(() => formatJsonLosslessly('{"a":}', 2)).toThrow(SyntaxError); | ||
| }); | ||
| }); |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| import { test, expect } from "@playwright/test"; | ||
|
|
||
| const evidenceDirectory = process.env.JSON_EVIDENCE_DIR; | ||
| const input = '{"id":9007199254740993,"ok":true}'; | ||
| const pretty = ['{', ' "id": 9007199254740993,', ' "ok": true', '}'].join("\n"); | ||
|
|
||
| test("desktop Format Minify and Copy preserve an unsafe integer", async ({ | ||
| page, | ||
| }) => { | ||
| await page.setViewportSize({ width: 1440, height: 1000 }); | ||
| await page.goto("/json-formatter"); | ||
| await page.locator("#re-input").fill(input); | ||
|
|
||
| await page.locator("#format-btn").click(); | ||
| await expect(page.locator("#json-output")).toHaveValue(pretty); | ||
| await expect(page.locator("#re-output")).toHaveText(pretty); | ||
| await expect(page.locator("#status-indicator")).toHaveText(/Valid/); | ||
| await page.locator("#re-output-wrap").scrollIntoViewIfNeeded(); | ||
| if (evidenceDirectory) { | ||
| await page.screenshot({ | ||
| path: `${evidenceDirectory}/json-desktop-1440x1000.png`, | ||
| }); | ||
| } | ||
|
|
||
| await page.locator("#minify-btn").click(); | ||
| await expect(page.locator("#json-output")).toHaveValue(input); | ||
| await expect(page.locator("#re-output")).toHaveText(input); | ||
| await page.evaluate(() => { | ||
| const nativeWriteText = navigator.clipboard.writeText.bind(navigator.clipboard); | ||
| window.clipboardWriteCompleted = new Promise((resolve, reject) => { | ||
| const timeout = setTimeout(() => reject(new Error("Clipboard write did not complete")), 5000); | ||
| navigator.clipboard.writeText = async (text) => { | ||
| try { | ||
| await nativeWriteText(text); | ||
| clearTimeout(timeout); | ||
| resolve(); | ||
| } catch (error) { | ||
| clearTimeout(timeout); | ||
| reject(error); | ||
| throw error; | ||
| } finally { | ||
| navigator.clipboard.writeText = nativeWriteText; | ||
| } | ||
| }; | ||
| }); | ||
| }); | ||
| await page.locator("#copy-btn").click(); | ||
| await page.evaluate(() => window.clipboardWriteCompleted); | ||
| expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(input); | ||
| }); | ||
|
|
||
| test("malformed input errors and clears stale success output", async ({ page }) => { | ||
| await page.goto("/json-formatter"); | ||
| await page.locator("#re-input").fill('{"ok":true}'); | ||
| await page.locator("#format-btn").click(); | ||
| await expect(page.locator("#status-indicator")).toHaveText(/Valid/); | ||
|
|
||
| await page.locator("#re-input").fill('{"id":}'); | ||
| await page.locator("#format-btn").click(); | ||
| await expect(page.locator("#status-indicator")).toHaveText(/Invalid/); | ||
| await expect(page.locator("#status-content")).not.toBeEmpty(); | ||
| await expect(page.locator("#json-output")).toHaveValue(""); | ||
| await expect(page.locator("#re-output")).toHaveText(""); | ||
| }); | ||
|
|
||
| test("mobile JSON formatting preserves ordinary structure and numeric lexemes", async ({ page }) => { | ||
| await page.setViewportSize({ width: 390, height: 844 }); | ||
| await page.goto("/json-formatter"); | ||
| await page.locator("#re-input").fill('{"a":1,"b":[true,false]}'); | ||
| await page.locator("#format-btn").click(); | ||
| await expect(page.locator("#json-output")).toHaveValue( | ||
| ['{', ' "a": 1,', ' "b": [', " true,", " false", " ]", '}'].join("\n"), | ||
| ); | ||
| await expect(page.locator("#status-indicator")).toHaveText(/Valid/); | ||
|
|
||
| const preciseInput = '{"id":9007199254740993,"ok":true}'; | ||
| await page.locator("#re-input").fill(preciseInput); | ||
| await page.locator("#format-btn").click(); | ||
| await expect(page.locator("#json-output")).toHaveValue( | ||
| ['{', ' "id": 9007199254740993,', ' "ok": true', '}'].join("\n"), | ||
| ); | ||
| await page.locator("#re-output-wrap").scrollIntoViewIfNeeded(); | ||
| if (evidenceDirectory) { | ||
| await page.screenshot({ | ||
| path: `${evidenceDirectory}/json-mobile-390x844.png`, | ||
| }); | ||
| } | ||
| await page.locator("#minify-btn").click(); | ||
| await expect(page.locator("#json-output")).toHaveValue(preciseInput); | ||
| }); |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P3: These new contract tests duplicate the exact fixture and expected outputs already present in src/utils/lossless-json.test.js (LOSSLESS_INPUT, LOSSLESS_PRETTY). The escaped-string lexeme is subtle and error-prone, and maintaining two independent copies means a fix or coverage change in one fixture silently drifts from the other. Keep the contract-level tests (they do verify the transform wrapper), but share the fixture instead of copying it: export LOSSLESS_INPUT/LOSSLESS_PRETTY from lossless-json.test.js (or move them to a shared fixture module) and import them here.
Prompt for AI agents