Repository Public
1/** Single byte range of an HTTP Range header. null: no range (serve everything); "invalid": answer 416. */2export function parseRange(header: string | null, size: number): { start: number; end: number } | null | "invalid" {3 if (!header) return null;4 const m = header.trim().match(/^bytes=(\d*)-(\d*)$/);5 if (!m) return header.trim().startsWith("bytes=") && header.includes(",") ? null : "invalid"; // multi-range: whole file6 const [, a, b] = m;7 if (a === "" && b === "") return "invalid";8 if (size === 0) return "invalid";9 if (a === "") { // suffix: last N bytes10 const n = Number(b);11 if (!Number.isSafeInteger(n) || n === 0) return "invalid";12 return { start: Math.max(0, size - n), end: size - 1 };13 }14 const start = Number(a);15 const end = b === "" ? size - 1 : Math.min(Number(b), size - 1);16 if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start >= size || end < start) return "invalid";17 return { start, end };18}19