Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as Exit from "effect/Exit";
3import * as Result from "effect/Result";
4import * as Schema from "effect/Schema";
5import * as SchemaGetter from "effect/SchemaGetter";
6import * as SchemaTransformation from "effect/SchemaTransformation";
7
8export const decodeJsonResult = <S extends Schema.Codec<unknown, unknown, never, never>>(
9 schema: S,
10) => {
11 const decode = Schema.decodeExit(Schema.fromJsonString(schema));
12 return (input: string) => {
13 const result = decode(input);
14 if (Exit.isFailure(result)) {
15 return Result.fail(result.cause);
16 }
17 return Result.succeed(result.value);
18 };
19};
20
21const decodeJsonString = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
22
23const parseLenientJsonGetter = SchemaGetter.transformEffect((input: string) => {
24 const withoutBom = input.startsWith("\uFEFF") ? input.slice(1) : input;
25 // Match comments together so URLs stay inside blocks; whitespace keeps adjacent tokens apart.
26 let stripped = withoutBom.replace(
27 /("(?:[^"\\]|\\.)*")|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g,
28 (match, stringLiteral: string | undefined) => (stringLiteral ? match : " "),
29 );
30
31 // A comma right after an opener trails nothing, so leave it for JSON.parse to reject.
32 stripped = stripped.replace(
33 /("(?:[^"\\]|\\.)*")|([[{]\s*,)|,(\s*[}\]])/g,
34 (
35 match,
36 stringLiteral: string | undefined,
37 leadingComma: string | undefined,
38 bracket: string | undefined,
39 ) => (stringLiteral || leadingComma ? match : (bracket ?? "")),
40 );
41
42 return decodeJsonString(stripped).pipe(Effect.mapError((error) => error.issue));
43});
44
45const fromLenientJsonString = new SchemaTransformation.Transformation(
46 parseLenientJsonGetter,
47 SchemaGetter.stringifyJson(),
48);
49
50const prettyJsonString = SchemaGetter.parseJson<string>().pipe(
51 SchemaGetter.compose(SchemaGetter.stringifyJson({ space: 2 })),
52);
53
54export const fromLenientJson = <S extends Schema.Top>(schema: S) =>
55 Schema.String.pipe(Schema.decodeTo(schema, fromLenientJsonString));
56
57export function extractJsonObject(raw: string): string {
58 const trimmed = raw.trim();
59 if (trimmed.length === 0) {
60 return trimmed;
61 }
62
63 const start = trimmed.indexOf("{");
64 if (start < 0) {
65 return trimmed;
66 }
67
68 let depth = 0;
69 let inString = false;
70 let escaping = false;
71 for (let index = start; index < trimmed.length; index += 1) {
72 const char = trimmed[index];
73 if (inString) {
74 if (escaping) {
75 escaping = false;
76 } else if (char === "\\") {
77 escaping = true;
78 } else if (char === '"') {
79 inString = false;
80 }
81 continue;
82 }
83
84 if (char === '"') {
85 inString = true;
86 continue;
87 }
88
89 if (char === "{") {
90 depth += 1;
91 continue;
92 }
93
94 if (char === "}") {
95 depth -= 1;
96 if (depth === 0) {
97 return trimmed.slice(start, index + 1);
98 }
99 }
100 }
101
102 return trimmed.slice(start);
103}
104
105export const fromJsonStringPretty = <S extends Schema.Top>(schema: S) =>
106 Schema.fromJsonString(schema).pipe(
107 Schema.encode({
108 decode: prettyJsonString,
109 encode: prettyJsonString,
110 }),
111 );