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

schemaJson.ts

246 lines7.1 KB

1import * as Cause from "effect/Cause";
2import * as Effect from "effect/Effect";
3import * as Exit from "effect/Exit";
4import * as Result from "effect/Result";
5import * as Schema from "effect/Schema";
6import * as SchemaGetter from "effect/SchemaGetter";
7import * as SchemaIssue from "effect/SchemaIssue";
8import * as SchemaTransformation from "effect/SchemaTransformation";
9​
10const MAX_SCHEMA_DIAGNOSTIC_ISSUES = 8;
11const MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENTS = 16;
12const MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENT_LENGTH = 64;
13const MAX_SCHEMA_DIAGNOSTIC_LENGTH = 2_048;
14​
15interface SchemaDiagnosticIssue {
16 readonly message: string;
17 readonly path: ReadonlyArray<PropertyKey>;
19​
20// Schema's default formatter includes actual values. These diagnostics cross
21// process and UI boundaries, so retain only issue kinds and bounded paths.
22​
23function truncateDiagnostic(value: string, maxLength: number): string {
24 return value.length <= maxLength ? value : `${value.slice(0, maxLength - 3)}...`;
26​
27function formatDiagnosticPathSegment(key: PropertyKey): string {
28 if (typeof key === "number") {
29 return `[${key}]`;
30 }
31 const value = truncateDiagnostic(
32 typeof key === "symbol" ? String(key) : key,
33 MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENT_LENGTH,
34 );
35 return `[${JSON.stringify(value)}]`;
37​
38function formatDiagnosticIssue(issue: SchemaDiagnosticIssue): string {
39 if (issue.path.length === 0) {
40 return issue.message;
41 }
42 const path = issue.path
43 .slice(0, MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENTS)
44 .map(formatDiagnosticPathSegment)
45 .join("");
46 const suffix = issue.path.length > MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENTS ? "[...]" : "";
47 return `${issue.message}\n at ${path}${suffix}`;
49​
50function schemaDiagnosticMessage(issue: SchemaIssue.Issue): string {
51 switch (issue._tag) {
52 case "InvalidType":
53 return "Invalid type";
54 case "InvalidValue":
55 case "Filter":
56 case "AnyOf":
57 case "Encoding":
58 case "Pointer":
59 case "Composite":
60 return "Invalid value";
61 case "MissingKey":
62 return "Missing key";
63 case "UnexpectedKey":
64 return "Unexpected key";
65 case "Forbidden":
66 return "Forbidden operation";
67 case "OneOf":
68 return "Expected exactly one schema member to match";
69 }
71​
72function collectSchemaDiagnosticIssues(
73 issue: SchemaIssue.Issue,
74 path: ReadonlyArray<PropertyKey>,
75 diagnostics: Array<SchemaDiagnosticIssue>,
76): number {
77 switch (issue._tag) {
78 case "Encoding":
79 return collectSchemaDiagnosticIssues(issue.issue, path, diagnostics);
80 case "Filter":
81 if (issue.issue._tag !== "InvalidValue") {
82 return collectSchemaDiagnosticIssues(issue.issue, path, diagnostics);
83 }
84 break;
85 case "Pointer":
86 return collectSchemaDiagnosticIssues(issue.issue, [...path, ...issue.path], diagnostics);
87 case "Composite":
88 return issue.issues.reduce(
89 (count, issue) => count + collectSchemaDiagnosticIssues(issue, path, diagnostics),
90 0,
91 );
92 case "AnyOf":
93 if (issue.issues.length > 0) {
94 return issue.issues.reduce(
95 (count, issue) => count + collectSchemaDiagnosticIssues(issue, path, diagnostics),
96 0,
97 );
98 }
99 break;
100 }
101​
102 if (diagnostics.length < MAX_SCHEMA_DIAGNOSTIC_ISSUES) {
103 diagnostics.push({ message: schemaDiagnosticMessage(issue), path });
104 }
105 return 1;
107​
108export const decodeJsonResult = <S extends Schema.Codec<unknown, unknown, never, never>>(
109 schema: S,
110) => {
111 const decode = Schema.decodeExit(Schema.fromJsonString(schema));
112 return (input: string) => {
113 const result = decode(input);
114 if (Exit.isFailure(result)) {
115 return Result.fail(result.cause);
116 }
117 return Result.succeed(result.value);
118 };
119};
120​
121export const formatSchemaError = (cause: Cause.Cause<Schema.SchemaError>) => {
122 const issues: Array<SchemaDiagnosticIssue> = [];
123 let issueCount = 0;
124 let failureCount = 0;
125 let defectCount = 0;
126 let interruptionCount = 0;
127​
128 for (const reason of cause.reasons) {
129 switch (reason._tag) {
130 case "Fail":
131 failureCount += 1;
132 if (Schema.isSchemaError(reason.error)) {
133 issueCount += collectSchemaDiagnosticIssues(reason.error.issue, [], issues);
134 }
135 break;
136 case "Die":
137 defectCount += 1;
138 break;
139 case "Interrupt":
140 interruptionCount += 1;
141 break;
142 }
143 }
144​
145 if (issues.length === 0) {
146 return `Schema validation failed (failureCount=${failureCount}, defectCount=${defectCount}, interruptionCount=${interruptionCount}).`;
147 }
148​
149 const omittedIssueCount = issueCount - issues.length;
150 const formatted = issues.map(formatDiagnosticIssue).join("\n");
151 if (omittedIssueCount === 0) {
152 return truncateDiagnostic(formatted, MAX_SCHEMA_DIAGNOSTIC_LENGTH);
153 }
154 const suffix = `\n... and ${omittedIssueCount} more issue(s)`;
155 return truncateDiagnostic(formatted, MAX_SCHEMA_DIAGNOSTIC_LENGTH - suffix.length) + suffix;
156};
157​
158const decodeJsonString = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
159​
160const parseLenientJsonGetter = SchemaGetter.transformEffect((input: string) => {
161 let stripped = input.replace(
162 /("(?:[^"\\]|\\.)*")|\/\/[^\n]*/g,
163 (match, stringLiteral: string | undefined) => (stringLiteral ? match : ""),
164 );
165​
166 stripped = stripped.replace(
167 /("(?:[^"\\]|\\.)*")|\/\*[\s\S]*?\*\//g,
168 (match, stringLiteral: string | undefined) => (stringLiteral ? match : ""),
169 );
170​
171 stripped = stripped.replace(
172 /("(?:[^"\\]|\\.)*")|,(\s*[}\]])/g,
173 (match, stringLiteral: string | undefined, bracket: string | undefined) =>
174 stringLiteral ? match : (bracket ?? ""),
175 );
176​
177 return decodeJsonString(stripped).pipe(Effect.mapError((error) => error.issue));
178});
179​
180const fromLenientJsonString = new SchemaTransformation.Transformation(
181 parseLenientJsonGetter,
182 SchemaGetter.stringifyJson(),
183);
184​
185const prettyJsonString = SchemaGetter.parseJson<string>().pipe(
186 SchemaGetter.compose(SchemaGetter.stringifyJson({ space: 2 })),
187);
188​
189export const fromLenientJson = <S extends Schema.Top>(schema: S) =>
190 Schema.String.pipe(Schema.decodeTo(schema, fromLenientJsonString));
191​
192export function extractJsonObject(raw: string): string {
193 const trimmed = raw.trim();
194 if (trimmed.length === 0) {
195 return trimmed;
196 }
197​
198 const start = trimmed.indexOf("{");
199 if (start < 0) {
200 return trimmed;
201 }
202​
203 let depth = 0;
204 let inString = false;
205 let escaping = false;
206 for (let index = start; index < trimmed.length; index += 1) {
207 const char = trimmed[index];
208 if (inString) {
209 if (escaping) {
210 escaping = false;
211 } else if (char === "\\") {
212 escaping = true;
213 } else if (char === '"') {
214 inString = false;
215 }
216 continue;
217 }
218​
219 if (char === '"') {
220 inString = true;
221 continue;
222 }
223​
224 if (char === "{") {
225 depth += 1;
226 continue;
227 }
228​
229 if (char === "}") {
230 depth -= 1;
231 if (depth === 0) {
232 return trimmed.slice(start, index + 1);
233 }
234 }
235 }
236​
237 return trimmed.slice(start);
239​
240export const fromJsonStringPretty = <S extends Schema.Top>(schema: S) =>
241 Schema.fromJsonString(schema).pipe(
242 Schema.encode({
243 decode: prettyJsonString,
244 encode: prettyJsonString,
245 }),
246 );