import type { JNode } from './ast'; import { parse, serialize } from './ast'; let worker: Worker | null = null; let seq = 0; const pending = new Map void>(); /** Parses large JSON off the main thread so a 50 MB body does not freeze the UI. */ export function parseJson(text: string): Promise<{ tree: JNode | null; pretty: string; error?: string }> { if (text.length < 512 * 1024) { try { const tree = parse(text); return Promise.resolve({ tree, pretty: serialize(tree, ' ') }); } catch (e) { return Promise.resolve({ tree: null, pretty: text, error: String((e as Error).message) }); } } worker ??= new Worker(new URL('./parse.worker.ts', import.meta.url), { type: 'module' }); worker.onmessage = (e) => { const cb = pending.get(e.data.id); pending.delete(e.data.id); cb?.(e.data); }; const id = ++seq; return new Promise((resolve) => { pending.set(id, (r) => resolve({ tree: r.tree ?? null, pretty: r.pretty ?? text, error: r.error })); worker!.postMessage({ id, text }); }); }