Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Exit from "effect/Exit";
3import * as Result from "effect/Result";
4import * as Schema from "effect/Schema";
5import { describe, expect, it } from "vite-plus/test";
6
7import {
8 decodeJsonResult,
9 extractJsonObject,
10 formatSchemaError,
11 fromLenientJson,
12} from "./schemaJson.ts";
13
14const decodeLenientJson = Schema.decodeUnknownSync(fromLenientJson(Schema.Unknown));
15
16describe("schemaJson helpers", () => {
17 it("extracts a balanced JSON object from surrounding text", () => {
18 expect(
19 extractJsonObject(`Sure, here is the JSON:
20\`\`\`json
21{
22 "subject": "Update README",
23 "body": ""
24}
25\`\`\`
26Done.`),
27 ).toBe(`{
28 "subject": "Update README",
29 "body": ""
30}`);
31 });
32
33 it("ignores braces inside strings while finding the object boundary", () => {
34 expect(
35 extractJsonObject('prefix {"message":"literal } brace","nested":{"ok":true}} suffix'),
36 ).toBe('{"message":"literal } brace","nested":{"ok":true}}');
37 });
38
39 it("returns trimmed input when no JSON object starts", () => {
40 expect(extractJsonObject(" no structured output ")).toBe("no structured output");
41 });
42
43 it("decodes JSON with comments and trailing commas", () => {
44 expect(
45 decodeLenientJson(`{
46 // Comments are valid in settings files.
47 "enabled": /* See "https://example.com/config" // still in the block */ true,
48 "values": [1, 2,],
49 }`),
50 ).toEqual({
51 enabled: true,
52 values: [1, 2],
53 });
54 });
55
56 it("rejects malformed JSON after lenient preprocessing", () => {
57 expect(() => decodeLenientJson('{ "enabled": true,, }')).toThrow();
58 expect(() => decodeLenientJson("[1/* https://example.com */2]")).toThrow();
59 });
60
61 it("preserves comment markers and commas before brackets inside string values", () => {
62 expect(decodeLenientJson('"1/* https://example.com */2"')).toBe("1/* https://example.com */2");
63 expect(decodeLenientJson('{"note":"a,]"}')).toEqual({ note: "a,]" });
64 expect(decodeLenientJson('{"list":["x,}"]}')).toEqual({ list: ["x,}"] });
65 expect(decodeLenientJson('{"values":[1, 2,],}')).toEqual({ values: [1, 2] });
66 });
67
68 it("formats schema failures with paths without exposing invalid values", () => {
69 const decodeCredential = decodeJsonResult(Schema.Struct({ token: Schema.Number }));
70 const decoded = decodeCredential('{"token":"credential=secret-value"}');
71
72 expect(Result.isFailure(decoded)).toBe(true);
73 if (Result.isFailure(decoded)) {
74 expect(formatSchemaError(decoded.failure)).toBe('Invalid type\n at ["token"]');
75 }
76 });
77
78 it("preserves nested paths reported by schema filters", () => {
79 const decode = decodeJsonResult(
80 Schema.String.check(
81 Schema.makeFilter(() => ({
82 path: ["session", "token"],
83 issue: "credential is invalid",
84 })),
85 ),
86 );
87 const decoded = decode('"credential=secret-value"');
88
89 expect(Result.isFailure(decoded)).toBe(true);
90 if (Result.isFailure(decoded)) {
91 const diagnostic = formatSchemaError(decoded.failure);
92 expect(diagnostic).toBe('Invalid value\n at ["session"]["token"]');
93 expect(diagnostic).not.toContain("credential=secret-value");
94 }
95 });
96
97 it("does not expose malformed lenient JSON input in diagnostics", () => {
98 const decode = Schema.decodeUnknownExit(fromLenientJson(Schema.Unknown));
99 const exit = decode('{"token":"credential=secret-value",,}');
100
101 expect(Exit.isFailure(exit)).toBe(true);
102 if (Exit.isFailure(exit)) {
103 const diagnostic = formatSchemaError(exit.cause);
104 expect(diagnostic).toBe("Invalid value");
105 expect(diagnostic).not.toContain("credential=secret-value");
106 }
107 });
108
109 it("summarizes unexpected defects without serializing their messages", () => {
110 const diagnostic = formatSchemaError(Cause.die(new Error("credential=secret-value")));
111
112 expect(diagnostic).toBe(
113 "Schema validation failed (failureCount=0, defectCount=1, interruptionCount=0).",
114 );
115 });
116
117 it("bounds the number of formatted schema issues", () => {
118 const decode = decodeJsonResult(Schema.Struct({ token: Schema.Number }));
119 const failures: Array<Cause.Cause<Schema.SchemaError>> = [];
120 for (let index = 0; index < 10; index += 1) {
121 const decoded = decode(`{"token":"credential=secret-value-${index}"}`);
122 if (Result.isFailure(decoded)) {
123 failures.push(decoded.failure);
124 }
125 }
126
127 const cause = Cause.fromReasons(failures.flatMap((cause) => cause.reasons));
128 const diagnostic = formatSchemaError(cause);
129 expect(diagnostic.match(/Invalid type/g)).toHaveLength(8);
130 expect(diagnostic).toContain("... and 2 more issue(s)");
131 });
132
133 it("retains the omitted issue count when bounding long diagnostics", () => {
134 const longPath = Array.from({ length: 16 }, (_, index) => `${index}-${"segment".repeat(16)}`);
135 const decode = decodeJsonResult(
136 Schema.String.check(
137 Schema.makeFilter(() => ({ path: longPath, issue: "credential is invalid" })),
138 ),
139 );
140 const failures: Array<Cause.Cause<Schema.SchemaError>> = [];
141 for (let index = 0; index < 10; index += 1) {
142 const decoded = decode(`"credential=secret-value-${index}"`);
143 if (Result.isFailure(decoded)) {
144 failures.push(decoded.failure);
145 }
146 }
147
148 const cause = Cause.fromReasons(failures.flatMap((cause) => cause.reasons));
149 const diagnostic = formatSchemaError(cause);
150 expect(diagnostic.length).toBeLessThanOrEqual(2_048);
151 expect(diagnostic.endsWith("\n... and 2 more issue(s)")).toBe(true);
152 });
153});