Versions 89 to 318
new file, 79 lines
1+import { JsonChunkCursor } from "./json-chunk-cursor.ts"; 3+export type JsonEvent = 4+ | { kind: "object" | "array" | "end" | "string" | "string-end" } 5+ | { kind: "key" | "text"; value: string } 6+ | { kind: "value"; value: number | boolean | null }; 8+/** Structural JSON decoding. Retains nesting and one bounded string fragment, not a decoded tree. */ 9+export function* jsonEvents( 10+ chunks: Iterable<string>, 11+ options: { finiteNumbers?: boolean } = {}, 12+): IterableIterator<JsonEvent> { 13+ const cursor = new JsonChunkCursor(chunks); 14+ const whitespace = () => { 15+ while (cursor.peek() !== undefined && /[ \t\n\r]/.test(cursor.peek()!)) cursor.take(); 17+ function* value(depth: number): IterableIterator<JsonEvent> { 18+ if (depth > 128) throw Error("JSON nesting exceeds bound"); 20+ const first = cursor.peek(); 22+ yield { kind: "string" }; 23+ for (const text of cursor.stringChunks()) yield { kind: "text", value: text }; 24+ yield { kind: "string-end" }; 27+ if (first === "{" || first === "[") { 28+ const object = cursor.take() === "{"; 29+ const close = object ? "}" : "]"; 30+ yield { kind: object ? "object" : "array" }; 32+ if (cursor.peek() === close) { 34+ yield { kind: "end" }; 41+ for (const text of cursor.stringChunks()) { 43+ if (key.length > 4096) throw Error("JSON key exceeds bound"); 45+ yield { kind: "key", value: key }; 47+ if (cursor.take() !== ":") throw Error("expected JSON colon"); 49+ yield* value(depth + 1); 51+ const separator = cursor.take(); 52+ if (separator === close) break; 53+ if (separator !== ",") throw Error("expected JSON separator"); 55+ yield { kind: "end" }; 59+ while (cursor.peek() !== undefined && !/[ \t\n\r,\]}]/.test(cursor.peek()!)) { 60+ token += cursor.take(); 61+ if (token.length > 256) throw Error("JSON scalar exceeds bound"); 63+ if (token === "true" || token === "false" || token === "null") { 64+ yield { kind: "value", value: token === "null" ? null : token === "true" }; 66+ if (!/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(token)) throw Error("invalid JSON scalar"); 67+ const number = Number(token); 68+ if (options.finiteNumbers && !Number.isFinite(number)) throw Error("non-finite JSON number"); 69+ yield { kind: "value", value: number }; 75+ if (cursor.peek() !== undefined) throw Error("trailing JSON input");