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

schemaJson.ts

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