Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Effect from "effect/Effect";
3import * as Exit from "effect/Exit";
4import * as Option from "effect/Option";
5import * as Result from "effect/Result";
6import * as Schema from "effect/Schema";
7import * as SchemaGetter from "effect/SchemaGetter";
8import * as SchemaIssue from "effect/SchemaIssue";
9import * as SchemaTransformation from "effect/SchemaTransformation";
10
11const MAX_SCHEMA_DIAGNOSTIC_ISSUES = 8;
12const MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENTS = 16;
13const MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENT_LENGTH = 64;
14const MAX_SCHEMA_DIAGNOSTIC_LENGTH = 2_048;
15
16interface SchemaDiagnosticIssue {
17 readonly message: string;
18 readonly path: ReadonlyArray<PropertyKey>;
19}
20
21// Schema's default formatter includes actual values. These diagnostics cross
22// process and UI boundaries, so retain only issue kinds and bounded paths.
23
24function truncateDiagnostic(value: string, maxLength: number): string {
25 return value.length <= maxLength ? value : `${value.slice(0, maxLength - 3)}...`;
26}
27
28function formatDiagnosticPathSegment(key: PropertyKey): string {
29 if (typeof key === "number") {
30 return `[${key}]`;
31 }
32 const value = truncateDiagnostic(
33 typeof key === "symbol" ? String(key) : key,
34 MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENT_LENGTH,
35 );
36 return `[${JSON.stringify(value)}]`;
37}
38
39function formatDiagnosticIssue(issue: SchemaDiagnosticIssue): string {
40 if (issue.path.length === 0) {
41 return issue.message;
42 }
43 const path = issue.path
44 .slice(0, MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENTS)
45 .map(formatDiagnosticPathSegment)
46 .join("");
47 const suffix = issue.path.length > MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENTS ? "[...]" : "";
48 return `${issue.message}\n at ${path}${suffix}`;
49}
50
51function schemaDiagnosticMessage(issue: SchemaIssue.Issue): string {
52 switch (issue._tag) {
53 case "InvalidType":
54 return "Invalid type";
55 case "InvalidValue":
56 case "Filter":
57 case "AnyOf":
58 case "Encoding":
59 case "Pointer":
60 case "Composite":
61 return "Invalid value";
62 case "MissingKey":
63 return "Missing key";
64 case "UnexpectedKey":
65 return "Unexpected key";
66 case "Forbidden":
67 return "Forbidden operation";
68 case "OneOf":
69 return "Expected exactly one schema member to match";
70 }
71}
72
73function collectSchemaDiagnosticIssues(
74 issue: SchemaIssue.Issue,
75 path: ReadonlyArray<PropertyKey>,
76 diagnostics: Array<SchemaDiagnosticIssue>,
77): number {
78 switch (issue._tag) {
79 case "Encoding":
80 return collectSchemaDiagnosticIssues(issue.issue, path, diagnostics);
81 case "Filter":
82 if (issue.issue._tag !== "InvalidValue") {
83 return collectSchemaDiagnosticIssues(issue.issue, path, diagnostics);
84 }
85 break;
86 case "Pointer":
87 return collectSchemaDiagnosticIssues(issue.issue, [...path, ...issue.path], diagnostics);
88 case "Composite":
89 return issue.issues.reduce(
90 (count, issue) => count + collectSchemaDiagnosticIssues(issue, path, diagnostics),
91 0,
92 );
93 case "AnyOf":
94 if (issue.issues.length > 0) {
95 return issue.issues.reduce(
96 (count, issue) => count + collectSchemaDiagnosticIssues(issue, path, diagnostics),
97 0,
98 );
99 }
100 break;
101 }
102
103 if (diagnostics.length < MAX_SCHEMA_DIAGNOSTIC_ISSUES) {
104 diagnostics.push({ message: schemaDiagnosticMessage(issue), path });
105 }
106 return 1;
107}
108
109export const decodeJsonResult = <S extends Schema.Codec<unknown, unknown, never, never>>(
110 schema: S,
111) => {
112 const decode = Schema.decodeExit(Schema.fromJsonString(schema));
113 return (input: string) => {
114 const result = decode(input);
115 if (Exit.isFailure(result)) {
116 return Result.fail(result.cause);
117 }
118 return Result.succeed(result.value);
119 };
120};
121
122export const formatSchemaError = (cause: Cause.Cause<Schema.SchemaError>) => {
123 const issues: Array<SchemaDiagnosticIssue> = [];
124 let issueCount = 0;
125 let failureCount = 0;
126 let defectCount = 0;
127 let interruptionCount = 0;
128
129 for (const reason of cause.reasons) {
130 switch (reason._tag) {
131 case "Fail":
132 failureCount += 1;
133 if (Schema.isSchemaError(reason.error)) {
134 issueCount += collectSchemaDiagnosticIssues(reason.error.issue, [], issues);
135 }
136 break;
137 case "Die":
138 defectCount += 1;
139 break;
140 case "Interrupt":
141 interruptionCount += 1;
142 break;
143 }
144 }
145
146 if (issues.length === 0) {
147 return `Schema validation failed (failureCount=${failureCount}, defectCount=${defectCount}, interruptionCount=${interruptionCount}).`;
148 }
149
150 const omittedIssueCount = issueCount - issues.length;
151 const formatted = issues.map(formatDiagnosticIssue).join("\n");
152 if (omittedIssueCount === 0) {
153 return truncateDiagnostic(formatted, MAX_SCHEMA_DIAGNOSTIC_LENGTH);
154 }
155 const suffix = `\n... and ${omittedIssueCount} more issue(s)`;
156 return truncateDiagnostic(formatted, MAX_SCHEMA_DIAGNOSTIC_LENGTH - suffix.length) + suffix;
157};
158
159/**
160 * A `Getter` that parses a lenient JSON string (tolerating trailing commas
161 * and JS-style comments) into an unknown value.
162 *
163 * Mirrors `SchemaGetter.parseJson()` but strips JSONC syntax before parsing.
164 */
165const decodeJsonString = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
166
167const parseLenientJsonGetter = SchemaGetter.onSome((input: string) => {
168 // Strip single-line comments - alternation preserves quoted strings.
169 let stripped = input.replace(
170 /("(?:[^"\\]|\\.)*")|\/\/[^\n]*/g,
171 (match, stringLiteral: string | undefined) => (stringLiteral ? match : ""),
172 );
173
174 // Strip multi-line comments.
175 stripped = stripped.replace(
176 /("(?:[^"\\]|\\.)*")|\/\*[\s\S]*?\*\//g,
177 (match, stringLiteral: string | undefined) => (stringLiteral ? match : ""),
178 );
179
180 // Strip trailing commas before `}` or `]`. The alternation preserves quoted
181 // strings so a comma inside a string value (e.g. `{"note":"a,]"}`) is not
182 // mistaken for a trailing comma and removed.
183 stripped = stripped.replace(
184 /("(?:[^"\\]|\\.)*")|,(\s*[}\]])/g,
185 (match, stringLiteral: string | undefined, bracket: string | undefined) =>
186 stringLiteral ? match : (bracket ?? ""),
187 );
188
189 return decodeJsonString(stripped).pipe(
190 Effect.map(Option.some),
191 Effect.mapError((error) => error.issue),
192 );
193});
194
195/**
196 * Schema transformation: lenient JSONC string ↔ unknown.
197 *
198 * Same API as `SchemaTransformation.fromJsonString`, but the decode side
199 * strips trailing commas and JS-style comments before parsing.
200 * Encoding produces strict JSON via `JSON.stringify`.
201 */
202export const fromLenientJsonString = new SchemaTransformation.Transformation(
203 parseLenientJsonGetter,
204 SchemaGetter.stringifyJson(),
205);
206
207export const prettyJsonString = SchemaGetter.parseJson<string>().compose(
208 SchemaGetter.stringifyJson({ space: 2 }),
209);
210
211/**
212 * Build a schema that decodes a lenient JSON string into `A`.
213 *
214 * Drop-in replacement for `Schema.fromJsonString(schema)` that tolerates
215 * trailing commas and comments in the input.
216 */
217export const fromLenientJson = <S extends Schema.Top>(schema: S) =>
218 Schema.String.pipe(Schema.decodeTo(schema, fromLenientJsonString));
219
220export function extractJsonObject(raw: string): string {
221 const trimmed = raw.trim();
222 if (trimmed.length === 0) {
223 return trimmed;
224 }
225
226 const start = trimmed.indexOf("{");
227 if (start < 0) {
228 return trimmed;
229 }
230
231 let depth = 0;
232 let inString = false;
233 let escaping = false;
234 for (let index = start; index < trimmed.length; index += 1) {
235 const char = trimmed[index];
236 if (inString) {
237 if (escaping) {
238 escaping = false;
239 } else if (char === "\\") {
240 escaping = true;
241 } else if (char === '"') {
242 inString = false;
243 }
244 continue;
245 }
246
247 if (char === '"') {
248 inString = true;
249 continue;
250 }
251
252 if (char === "{") {
253 depth += 1;
254 continue;
255 }
256
257 if (char === "}") {
258 depth -= 1;
259 if (depth === 0) {
260 return trimmed.slice(start, index + 1);
261 }
262 }
263 }
264
265 return trimmed.slice(start);
266}
267
268/**
269 * Build a JSON string schema that encodes with stable 2-space formatting.
270 *
271 * Decode behavior matches `Schema.fromJsonString(schema)`. Encode behavior
272 * keeps the transformation schema-based while preserving human-readable JSON.
273 */
274export const fromJsonStringPretty = <S extends Schema.Top>(schema: S) =>
275 Schema.fromJsonString(schema).pipe(
276 Schema.encode({
277 decode: prettyJsonString,
278 encode: prettyJsonString,
279 }),
280 );