Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

schemaJson.test.ts

145 lines4.9 KB

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
22 "subject": "Update README",
23 "body": ""
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": 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 });
59​
60 it("formats schema failures with paths without exposing invalid values", () => {
61 const decodeCredential = decodeJsonResult(Schema.Struct({ token: Schema.Number }));
62 const decoded = decodeCredential('{"token":"credential=secret-value"}');
63​
64 expect(Result.isFailure(decoded)).toBe(true);
65 if (Result.isFailure(decoded)) {
66 expect(formatSchemaError(decoded.failure)).toBe('Invalid type\n at ["token"]');
67 }
68 });
69​
70 it("preserves nested paths reported by schema filters", () => {
71 const decode = decodeJsonResult(
72 Schema.String.check(
73 Schema.makeFilter(() => ({
74 path: ["session", "token"],
75 issue: "credential is invalid",
76 })),
77 ),
78 );
79 const decoded = decode('"credential=secret-value"');
80​
81 expect(Result.isFailure(decoded)).toBe(true);
82 if (Result.isFailure(decoded)) {
83 const diagnostic = formatSchemaError(decoded.failure);
84 expect(diagnostic).toBe('Invalid value\n at ["session"]["token"]');
85 expect(diagnostic).not.toContain("credential=secret-value");
86 }
87 });
88​
89 it("does not expose malformed lenient JSON input in diagnostics", () => {
90 const decode = Schema.decodeUnknownExit(fromLenientJson(Schema.Unknown));
91 const exit = decode('{"token":"credential=secret-value",,}');
92​
93 expect(Exit.isFailure(exit)).toBe(true);
94 if (Exit.isFailure(exit)) {
95 const diagnostic = formatSchemaError(exit.cause);
96 expect(diagnostic).toBe("Invalid value");
97 expect(diagnostic).not.toContain("credential=secret-value");
98 }
99 });
100​
101 it("summarizes unexpected defects without serializing their messages", () => {
102 const diagnostic = formatSchemaError(Cause.die(new Error("credential=secret-value")));
103​
104 expect(diagnostic).toBe(
105 "Schema validation failed (failureCount=0, defectCount=1, interruptionCount=0).",
106 );
107 });
108​
109 it("bounds the number of formatted schema issues", () => {
110 const decode = decodeJsonResult(Schema.Struct({ token: Schema.Number }));
111 const failures: Array<Cause.Cause<Schema.SchemaError>> = [];
112 for (let index = 0; index < 10; index += 1) {
113 const decoded = decode(`{"token":"credential=secret-value-${index}"}`);
114 if (Result.isFailure(decoded)) {
115 failures.push(decoded.failure);
116 }
117 }
118​
119 const cause = Cause.fromReasons(failures.flatMap((cause) => cause.reasons));
120 const diagnostic = formatSchemaError(cause);
121 expect(diagnostic.match(/Invalid type/g)).toHaveLength(8);
122 expect(diagnostic).toContain("... and 2 more issue(s)");
123 });
124​
125 it("retains the omitted issue count when bounding long diagnostics", () => {
126 const longPath = Array.from({ length: 16 }, (_, index) => `${index}-${"segment".repeat(16)}`);
127 const decode = decodeJsonResult(
128 Schema.String.check(
129 Schema.makeFilter(() => ({ path: longPath, issue: "credential is invalid" })),
130 ),
131 );
132 const failures: Array<Cause.Cause<Schema.SchemaError>> = [];
133 for (let index = 0; index < 10; index += 1) {
134 const decoded = decode(`"credential=secret-value-${index}"`);
135 if (Result.isFailure(decoded)) {
136 failures.push(decoded.failure);
137 }
138 }
139​
140 const cause = Cause.fromReasons(failures.flatMap((cause) => cause.reasons));
141 const diagnostic = formatSchemaError(cause);
142 expect(diagnostic.length).toBeLessThanOrEqual(2_048);
143 expect(diagnostic.endsWith("\n... and 2 more issue(s)")).toBe(true);
144 });
145});