// READING A BIG JSON FILE BY ITS ENDS (lane L5). `metadata.info.json` runs to // 600 KB+ (yt-dlp's formats), `transcript.cues.json` to megabytes; the // ingredient page needs a handful of top-level fields of each, and how far the // last cue reaches. So a file is read by its HEAD (the first bytes, scanned as // the top-level object's members until the buffer ends or a named key is met) // and its TAIL (the last bytes, searched for the last `"end"`), never whole. // // Plain ESM; the CLI runs it under bare node. import { open } from "node:fs/promises"; export const HEAD_BYTES = 64 * 1024; export const TAIL_BYTES = 4 * 1024; async function readRange(file, start, length) { let fh; try { fh = await open(file, "r"); const st = await fh.stat(); const from = start < 0 ? Math.max(0, st.size + start) : start; const n = Math.max(0, Math.min(length, st.size - from)); const buf = Buffer.alloc(n); const { bytesRead } = await fh.read(buf, 0, n, from); return { text: buf.subarray(0, bytesRead).toString("utf8"), size: st.size }; } catch { return null; } finally { await fh?.close().catch(() => {}); } } /** * The top-level PRIMITIVE members of a JSON object, from the start of its text * (a truncated text is fine: what was complete is returned). An object or * array member is skipped (its key is listed in `nested`); scanning stops at * `stopKey`. * @param {string} text * @param {{ stopKey?: string | null }} [o] * @returns {{ fields: Record, nested: string[], complete: boolean }} */ export function scanHead(text, { stopKey = null } = {}) { const fields = {}; const nested = []; let i = 0; const n = text.length; const ws = () => { while (i < n && /\s/.test(text[i])) i += 1; }; const str = () => { // at a quote; returns the decoded string, or null when it runs off the end const s = i; i += 1; while (i < n) { const c = text[i]; if (c === "\\") i += 2; else if (c === '"') { i += 1; try { return JSON.parse(text.slice(s, i)); } catch { return null; } } else i += 1; } return null; }; const skipNested = () => { let depth = 0; while (i < n) { const c = text[i]; if (c === '"') { if (str() === null) return false; continue; } if (c === "{" || c === "[") depth += 1; else if (c === "}" || c === "]") { depth -= 1; if (depth === 0) { i += 1; return true; } } i += 1; } return false; }; ws(); if (text[i] !== "{") return { fields, nested, complete: false }; i += 1; for (;;) { ws(); if (i >= n) return { fields, nested, complete: false }; if (text[i] === "}") return { fields, nested, complete: true }; if (text[i] === ",") { i += 1; continue; } if (text[i] !== '"') return { fields, nested, complete: false }; const key = str(); if (key === null) return { fields, nested, complete: false }; ws(); if (text[i] !== ":") return { fields, nested, complete: false }; i += 1; ws(); if (stopKey && key === stopKey) return { fields, nested: [...nested, key], complete: false }; const c = text[i]; if (c === '"') { const v = str(); if (v === null) return { fields, nested, complete: false }; fields[key] = v; } else if (c === "{" || c === "[") { nested.push(key); if (!skipNested()) return { fields, nested, complete: false }; } else { const m = /^(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)/.exec(text.slice(i, i + 40)); if (!m) return { fields, nested, complete: false }; // A number at the very end of a truncated text may be cut short: only a terminated one counts. if (i + m[0].length >= n) return { fields, nested, complete: false }; fields[key] = JSON.parse(m[0]); i += m[0].length; } } } /** * A JSON file's head: its top-level primitive members (scanHead), and its size. * @param {string} file * @param {{ bytes?: number, stopKey?: string | null }} [o] * @returns {Promise<{ fields: Record, nested: string[], size: number } | null>} */ export async function readJsonHead(file, { bytes = HEAD_BYTES, stopKey = null } = {}) { const r = await readRange(file, 0, bytes); if (!r) return null; const { fields, nested } = scanHead(r.text, { stopKey }); return { fields, nested, size: r.size }; } /** * The largest `"end": ` in a file's last bytes: how far a cue file's * last cue reaches, without reading the cues. * @param {string} file * @returns {Promise} */ export async function lastEndOf(file, { bytes = TAIL_BYTES } = {}) { const r = await readRange(file, -bytes, bytes); if (!r) return null; let best = null; for (const m of r.text.matchAll(/"end"\s*:\s*(-?\d+(?:\.\d+)?)/g)) { const v = Number(m[1]); if (Number.isFinite(v) && (best === null || v > best)) best = v; } return best; }