Versions 102 to 318
new file, 86 lines
1+/** Incremental UTF-16 cursor over canonical log chunks. */ 2+export class JsonChunkCursor { 3+ readonly #input: Iterator<string>; 6+ constructor(chunks: Iterable<string>) { 7+ this.#input = chunks[Symbol.iterator](); 9+ peek(): string | undefined { 10+ while (this.#offset === this.#chunk.length) { 11+ const next = this.#input.next(); 12+ if (next.done) return undefined; 13+ if (typeof next.value !== "string" || next.value.length > 600000) throw Error("invalid JSON input chunk"); 14+ this.#chunk = next.value; 17+ return this.#chunk[this.#offset]; 20+ const char = this.peek(); 21+ if (char === undefined) throw Error("truncated JSON input"); 25+ /** Consume one quoted JSON string, yielding bounded decoded text. */ 26+ *stringChunks(): IterableIterator<string> { 27+ if (this.take() !== '"') throw Error("expected JSON string"); 30+ // Copy ordinary text in bounded slices instead of allocating a string 31+ // concatenation for every character of a large canonical field. 33+ const start = this.#offset; 34+ const end = Math.min(this.#chunk.length, start + 16384 - buffer.length); 35+ while (this.#offset < end) { 36+ const code = this.#chunk.charCodeAt(this.#offset); 37+ if (code < 32 || code === 34 || code === 92) break; 40+ if (this.#offset > start) { 41+ buffer += this.#chunk.slice(start, this.#offset); 42+ if (buffer.length === 16384) { 48+ let char = this.take(); 50+ if (buffer) yield buffer; 53+ if (char.charCodeAt(0) < 32) throw Error("unescaped JSON control character"); 55+ const escape = this.take(); 56+ const simple: Record<string, string> = { 66+ if (escape === "u") { 68+ for (let i = 0; i < 4; i++) hex += this.take(); 69+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) throw Error("invalid JSON Unicode escape"); 70+ char = String.fromCharCode(Number.parseInt(hex, 16)); 72+ if (!Object.hasOwn(simple, escape)) throw Error("invalid JSON escape"); 73+ char = simple[escape]!; 77+ if (buffer.length === 16384) { 84+ this.#input.return?.();