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 // The synchronous tokenizer is exported at runtime in 3.6.0, but omitted
51 // from its bundled types. Unlike parser(), it does not wrap tokens in an
52 // async generator; the file reader already supplies backpressure and UTF-8.
53 const { jsonParser } = StreamJson as typeof StreamJson & {
54 jsonParser: (
55 options: ParserOptions,
56 ) => (input: string | typeof none) => Many<Token> | typeof none;
57 };
58 const tokenize = jsonParser({ packValues: false });
59 const assembler = new Assembler();
60 let key: string | null = null;
61 let value = "";
62 let depth = 0;
63 let complete = false;
64 let malformed = false;
65
66 const assemble = (token: Token) => {
67 reserve(
68 64 + ("value" in token && typeof token.value === "string" ? token.value.length * 2 : 0),
69 );
70 switch (token.name) {
71 case "startString":
72 case "startNumber":
73 value = "";
74 break;
75 case "stringChunk":
76 case "numberChunk":
77 value += token.value;
78 break;
79 case "endString":
80 assembler.consume({ name: "stringValue", value });
81 value = "";
82 break;
83 case "endNumber":
84 assembler.consume({ name: "numberValue", value });
85 value = "";
86 break;
87 default:
88 assembler.consume(token);
89 }
90 };
91 // Forward actual selected keys instead of reconstructing them from path
92 // changes: adjacent duplicate keys have the same path but JSON.parse keeps
93 // the last value. Reconstructing paths can silently retain the first value.
94 const stack: Array<{ path: JsonPath; key: string | number | null; selected: boolean }> = [];
95 let selectedValue = false;
96 const startValue = () => {
97 const parent = stack.at(-1);
98 const path = parent?.selected ? [...parent.path, parent.key] : [];
99 const selected = (parent?.selected ?? true) && selectPath(path);
100 if (selected && typeof parent?.key === "string") {
101 assemble({ name: "keyValue", value: parent.key });
102 }
103 return { path, selected };
104 };
105 const endValue = () => {
106 const parent = stack.at(-1);
107 if (parent && typeof parent.key === "number") parent.key++;
108 };
109 const selectToken = (token: Token | typeof none) => {
110 if (token === none) return;
111 switch (token.name) {
112 case "keyValue": {
113 const parent = stack.at(-1);
114 if (parent) parent.key = token.value;
115 return;
116 }
117 case "startObject":
118 case "startArray": {
119 const frame = startValue();
120 stack.push({ ...frame, key: token.name === "startArray" ? 0 : null });
121 if (frame.selected) assemble(token);
122 return;
123 }
124 case "endObject":
125 case "endArray":
126 if (stack.pop()?.selected) assemble(token);
127 endValue();
128 return;
129 case "startString":
130 case "startNumber":
131 selectedValue = startValue().selected;
132 if (selectedValue) assemble(token);
133 return;
134 case "endString":
135 case "endNumber":
136 if (selectedValue) assemble(token);
137 endValue();
138 return;
139 case "nullValue":
140 case "trueValue":
141 case "falseValue":
142 if (startValue().selected) assemble(token);
143 endValue();
144 return;
145 default:
146 if (selectedValue) assemble(token);
147 }
148 };
149 const consume = (input: string | typeof none) => {
150 if (malformed) return;
151 try {
152 const tokens = tokenize(input);
153 if (tokens === none) return;
154 for (const token of tokens.values) {
155 if (token.name === "startObject" || token.name === "startArray") {
156 if (++depth > (options?.maxDepth ?? 128))
157 throw new TranscriptJsonLimitError("Transcript JSON nesting exceeds the depth limit");
158 } else if (token.name === "endObject" || token.name === "endArray") {
159 if (--depth === 0) complete = true;
160 }
161 if (token.name === "startKey") {
162 key = "";
163 } else if (token.name === "stringChunk" && key !== null) {
164 reserve(token.value.length * 2);
165 key += token.value;
166 } else if (token.name === "endKey") {
167 selectToken({ name: "keyValue", value: key ?? "" });
168 key = null;
169 } else {
170 selectToken(token);
171 }
172 }
173 } catch (cause) {
174 if (cause instanceof Error && cause.message.startsWith("Parser ")) {
175 malformed = true;
176 } else {
177 throw cause;
178 }
179 }
180 };
181 return {
182 write: (chunk: string) => consume(chunk),
183 finish: (): unknown => {
184 consume(none);
185 if (malformed || !complete) return undefined;
186 selectToken(none);
187 return assembler.done ? assembler.current : undefined;
188 },
189 };
190}