Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/shared/src/schemaJson.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,15 @@ Done.`),
expect(() => decodeLenientJson('{ "enabled": true,, }')).toThrow();
});

it("preserves commas before brackets inside string values", () => {
// A comma inside a string value that happens to precede `}`/`]` must not
// be stripped as if it were a trailing comma.
expect(decodeLenientJson('{"note":"a,]"}')).toEqual({ note: "a,]" });
expect(decodeLenientJson('{"list":["x,}"]}')).toEqual({ list: ["x,}"] });
// Genuine trailing commas are still removed.
expect(decodeLenientJson('{"values":[1, 2,],}')).toEqual({ values: [1, 2] });
});

it("formats schema failures with paths without exposing invalid values", () => {
const decodeCredential = decodeJsonResult(Schema.Struct({ token: Schema.Number }));
const decoded = decodeCredential('{"token":"credential=secret-value"}');
Expand Down
10 changes: 8 additions & 2 deletions packages/shared/src/schemaJson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,14 @@ const parseLenientJsonGetter = SchemaGetter.onSome((input: string) => {
(match, stringLiteral: string | undefined) => (stringLiteral ? match : ""),
);

// Strip trailing commas before `}` or `]`.
stripped = stripped.replace(/,(\s*[}\]])/g, "$1");
// Strip trailing commas before `}` or `]`. The alternation preserves quoted
// strings so a comma inside a string value (e.g. `{"note":"a,]"}`) is not
// mistaken for a trailing comma and removed.
stripped = stripped.replace(
/("(?:[^"\\]|\\.)*")|,(\s*[}\]])/g,
(match, stringLiteral: string | undefined, bracket: string | undefined) =>
stringLiteral ? match : (bracket ?? ""),
);

return decodeJsonString(stripped).pipe(
Effect.map(Option.some),
Expand Down
Loading