Open History to see the last commit
1import * as Schema from "effect/Schema";
2import { describe, expect, it } from "vite-plus/test";
3
4import { extractJsonObject, fromLenientJson } from "./schemaJson.ts";
5
6const decodeLenientJson = Schema.decodeUnknownSync(fromLenientJson(Schema.Unknown));
7
8describe("schemaJson helpers", () => {
9 it("extracts a balanced JSON object from surrounding text", () => {
10 expect(
11 extractJsonObject(`Sure, here is the JSON:
12\`\`\`json
13{
14 "subject": "Update README",
15 "body": ""
16}
17\`\`\`
18Done.`),
19 ).toBe(`{
20 "subject": "Update README",
21 "body": ""
22}`);
23 });
24
25 it("ignores braces inside strings while finding the object boundary", () => {
26 expect(
27 extractJsonObject('prefix {"message":"literal } brace","nested":{"ok":true}} suffix'),
28 ).toBe('{"message":"literal } brace","nested":{"ok":true}}');
29 });
30
31 it.each(["\n", "\r\n", "\r"])(
32 "decodes comments and trailing commas with %j line endings",
33 (eol) => {
34 expect(
35 decodeLenientJson(
36 `{
37 // Comments are valid in settings files.
38 "enabled": /* See "https://example.com/config" // still in the block */ true,
39 "values": [1, 2,],
40 }`.replaceAll("\n", eol),
41 ),
42 ).toEqual({
43 enabled: true,
44 values: [1, 2],
45 });
46 },
47 );
48
49 it("preserves comment markers and commas before brackets inside string values", () => {
50 expect(decodeLenientJson('"1/* https://example.com */2"')).toBe("1/* https://example.com */2");
51 expect(decodeLenientJson('{"note":"a,]"}')).toEqual({ note: "a,]" });
52 expect(decodeLenientJson('{"list":["x,}"]}')).toEqual({ list: ["x,}"] });
53 expect(decodeLenientJson('{"values":[1, 2,],}')).toEqual({ values: [1, 2] });
54 });
55
56 it("rejects a comma as the only array or object entry", () => {
57 for (const input of ["[,]", "[ /* note */ , ]", "{,}", '{"values":[,]}']) {
58 expect(() => decodeLenientJson(input)).toThrow();
59 }
60 expect(decodeLenientJson("[1, /* note */ ]")).toEqual([1]);
61 });
62
63 it("keeps properties after CR-terminated comments in mixed line endings", () => {
64 expect(decodeLenientJson('{\n"enabled":true,// comment\r"values":[1,2],\n}')).toEqual({
65 enabled: true,
66 values: [1, 2],
67 });
68 });
69
70 it("strips a leading UTF-8 BOM and keeps one inside a string", () => {
71 expect(decodeLenientJson('\uFEFF// comment\n{"value":"\uFEFFkeep",}')).toEqual({
72 value: "\uFEFFkeep",
73 });
74 });
75});