Parse a `Range: bytes=start-end` header against the file size. Returns * undefined for a missing / malformed / unsatisfiable range, in which case the * caller serves the whole file with 200 (browsers accept that response).
(header: string | undefined, size: number)
| 331 | * undefined for a missing / malformed / unsatisfiable range, in which case the |
| 332 | * caller serves the whole file with 200 (browsers accept that response). */ |
| 333 | function parseRange(header: string | undefined, size: number): ByteRange | undefined { |
| 334 | if (!header || size <= 0) return undefined; |
| 335 | const m = /^bytes=(\d*)-(\d*)$/i.exec(header.trim()); |
| 336 | if (!m) return undefined; |
| 337 | const startStr = m[1]!; |
| 338 | const endStr = m[2]!; |
| 339 | if (startStr === '' && endStr === '') return undefined; |
| 340 | |
| 341 | let start: number; |
| 342 | let end: number; |
| 343 | if (startStr === '') { |
| 344 | // Suffix range: `bytes=-N` → the last N bytes. |
| 345 | const suffix = Number(endStr); |
| 346 | if (!Number.isFinite(suffix) || suffix <= 0) return undefined; |
| 347 | start = Math.max(size - suffix, 0); |
| 348 | end = size - 1; |
| 349 | } else { |
| 350 | start = Number(startStr); |
| 351 | if (!Number.isFinite(start) || start < 0 || start >= size) return undefined; |
| 352 | end = endStr === '' ? size - 1 : Number(endStr); |
| 353 | if (!Number.isFinite(end) || end < 0) return undefined; |
| 354 | } |
| 355 | if (start > end) return undefined; |
| 356 | return { start, end: Math.min(end, size - 1) }; |
| 357 | } |
no test coverage detected