(file: string)
| 69 | * past the limit. Returns `bytes: null` for an oversize file. |
| 70 | */ |
| 71 | export async function readBoundedSource(file: string): Promise<BoundedSource> { |
| 72 | const initial = await fsp.stat(file); |
| 73 | assertRegularFile(initial); |
| 74 | if (initial.size > MAX_SOURCE_FILE_SIZE_BYTES) return { stats: initial, bytes: null }; |
| 75 | const handle = await fsp.open(file, 'r'); |
| 76 | try { |
| 77 | let stats = await handle.stat(); |
| 78 | assertRegularFile(stats); |
| 79 | if (stats.size > MAX_SOURCE_FILE_SIZE_BYTES) return { stats, bytes: null }; |
| 80 | const chunks: Buffer[] = []; |
| 81 | let size = 0; |
| 82 | while (size <= MAX_SOURCE_FILE_SIZE_BYTES) { |
| 83 | const chunk = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, MAX_SOURCE_FILE_SIZE_BYTES + 1 - size)); |
| 84 | const { bytesRead } = await handle.read(chunk, 0, chunk.length, size); |
| 85 | if (!bytesRead) break; |
| 86 | chunks.push(chunk.subarray(0, bytesRead)); |
| 87 | size += bytesRead; |
| 88 | } |
| 89 | stats = await handle.stat(); |
| 90 | if (size > MAX_SOURCE_FILE_SIZE_BYTES || stats.size > MAX_SOURCE_FILE_SIZE_BYTES) { |
| 91 | stats.size = Math.max(size, stats.size); |
| 92 | return { stats, bytes: null }; |
| 93 | } |
| 94 | return { stats, bytes: Buffer.concat(chunks, size) }; |
| 95 | } finally { |
| 96 | await handle.close(); |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | /** Synchronous {@link readBoundedSource}. */ |
| 101 | export function readBoundedSourceSync(file: string): BoundedSource { |
no test coverage detected