Open History to see the last commit
1import * as SchemaAST from "effect/SchemaAST";
2import { none, type Many } from "stream-chain/defs.js";
3import { Assembler } from "stream-json/core/assembler.js";
4import * as StreamJson from "stream-json/core/parser.js";
5import type { ParserOptions, Token } from "stream-json/core/parser.js";
6
7type JsonPath = ReadonlyArray<string | number | null>;
8
9export function createTranscriptJsonSelector(schema: { readonly ast: SchemaAST.AST }) {
10 const ast = SchemaAST.toEncoded(schema.ast);
11 const includes = (node: SchemaAST.AST, path: JsonPath, index: number): boolean => {
12 if (index === path.length) return true;
13 switch (node._tag) {
14 case "Objects":
15 if (node.indexSignatures.length > 0) return true;
16 return node.propertySignatures.some(
17 (property) =>
18 String(property.name) === path[index] && includes(property.type, path, index + 1),
19 );
20 case "Arrays": {
21 const key = path[index];
22 if (typeof key !== "number") return true;
23 const element = node.elements[key];
24 if (element) return includes(element, path, index + 1);
25 return node.rest.length === 0 || node.rest.some((item) => includes(item, path, index + 1));
26 }
27 case "Union":
28 return node.types.some((type) => includes(type, path, index));
29 case "Suspend":
30 return includes(node.thunk(), path, index);
31 case "Unknown":
32 case "Any":
33 case "ObjectKeyword":
34 case "Declaration":
35 return true;
36 default:
37 return false;
38 }
39 };
40 return (path: JsonPath) => includes(ast, path, 0);
41}
42
43export class TranscriptJsonLimitError extends Error {}
44
45export function createTranscriptJsonReader(
46 reserve: (bytes: number) => void,
47 selectPath: (path: JsonPath) => boolean,
48 options?: { readonly maxDepth?: number },
49) {
50 // 3.6.0 omits the synchronous tokenizer from types; parser() adds an unnecessary async generator.
51 const { jsonParser } = StreamJson as typeof StreamJson & {
52 jsonParser: (
53 options: ParserOptions,
54 ) => (input: string | typeof none) => Many<Token> | typeof none;
55 };
56 const tokenize = jsonParser({ packValues: false });
57 const assembler = new Assembler();
58 let key: string | null = null;
59 let value = "";
60 let depth = 0;
61 let complete = false;
62 let malformed = false;
63
64 const assemble = (token: Token) => {
65 reserve(
66 64 + ("value" in token && typeof token.value === "string" ? token.value.length * 2 : 0),
67 );
68 switch (token.name) {
69 case "startString":
70 case "startNumber":
71 value = "";
72 break;
73 case "stringChunk":
74 case "numberChunk":
75 value += token.value;
76 break;
77 case "endString":
78 assembler.consume({ name: "stringValue", value });
79 value = "";
80 break;
81 case "endNumber":
82 assembler.consume({ name: "numberValue", value });
83 value = "";
84 break;
85 default:
86 assembler.consume(token);
87 }
88 };
89 // Preserve actual keys; adjacent duplicates share a path, but JSON.parse keeps the last value.
90 const stack: Array<{ path: JsonPath; key: string | number | null; selected: boolean }> = [];
91 let selectedValue = false;
92 const startValue = () => {
93 const parent = stack.at(-1);
94 const path = parent?.selected ? [...parent.path, parent.key] : [];
95 const selected = (parent?.selected ?? true) && selectPath(path);
96 if (selected && typeof parent?.key === "string") {
97 assemble({ name: "keyValue", value: parent.key });
98 }
99 return { path, selected };
100 };
101 const endValue = () => {
102 const parent = stack.at(-1);
103 if (parent && typeof parent.key === "number") parent.key++;
104 };
105 const selectToken = (token: Token | typeof none) => {
106 if (token === none) return;
107 switch (token.name) {
108 case "keyValue": {
109 const parent = stack.at(-1);
110 if (parent) parent.key = token.value;
111 return;
112 }
113 case "startObject":
114 case "startArray": {
115 const frame = startValue();
116 stack.push({ ...frame, key: token.name === "startArray" ? 0 : null });
117 if (frame.selected) assemble(token);
118 return;
119 }
120 case "endObject":
121 case "endArray":
122 if (stack.pop()?.selected) assemble(token);
123 endValue();
124 return;
125 case "startString":
126 case "startNumber":
127 selectedValue = startValue().selected;
128 if (selectedValue) assemble(token);
129 return;
130 case "endString":
131 case "endNumber":
132 if (selectedValue) assemble(token);
133 endValue();
134 return;
135 case "nullValue":
136 case "trueValue":
137 case "falseValue":
138 if (startValue().selected) assemble(token);
139 endValue();
140 return;
141 default:
142 if (selectedValue) assemble(token);
143 }
144 };
145 const consume = (input: string | typeof none) => {
146 if (malformed) return;
147 try {
148 const tokens = tokenize(input);
149 if (tokens === none) return;
150 for (const token of tokens.values) {
151 if (token.name === "startObject" || token.name === "startArray") {
152 if (++depth > (options?.maxDepth ?? 128))
153 throw new TranscriptJsonLimitError("Transcript JSON nesting exceeds the depth limit");
154 } else if (token.name === "endObject" || token.name === "endArray") {
155 if (--depth === 0) complete = true;
156 }
157 if (token.name === "startKey") {
158 key = "";
159 } else if (token.name === "stringChunk" && key !== null) {
160 reserve(token.value.length * 2);
161 key += token.value;
162 } else if (token.name === "endKey") {
163 selectToken({ name: "keyValue", value: key ?? "" });
164 key = null;
165 } else {
166 selectToken(token);
167 }
168 }
169 } catch (cause) {
170 if (cause instanceof Error && cause.message.startsWith("Parser ")) {
171 malformed = true;
172 } else {
173 throw cause;
174 }
175 }
176 };
177 return {
178 write: (chunk: string) => consume(chunk),
179 finish: (): unknown => {
180 consume(none);
181 if (malformed || !complete) return undefined;
182 selectToken(none);
183 return assembler.done ? assembler.current : undefined;
184 },
185 };
186}