(file: string)
| 124 | * past the limit. Returns `bytes: null` for an oversize file. |
| 125 | */ |
| 126 | export async function readBoundedSource(file: string): Promise<BoundedSource> { |
| 127 | const initial = await fsp.stat(file); |
| 128 | assertRegularFile(initial); |
| 129 | if (initial.size > MAX_SOURCE_FILE_SIZE_BYTES) return { stats: initial, bytes: null }; |
| 130 | const handle = await fsp.open(file, 'r'); |
| 131 | try { |
| 132 | let stats = await handle.stat(); |
| 133 | assertRegularFile(stats); |
| 134 | if (stats.size > MAX_SOURCE_FILE_SIZE_BYTES) return { stats, bytes: null }; |
| 135 | const chunks: Buffer[] = []; |
| 136 | let size = 0; |
| 137 | while (size <= MAX_SOURCE_FILE_SIZE_BYTES) { |
| 138 | const chunk = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, MAX_SOURCE_FILE_SIZE_BYTES + 1 - size)); |
| 139 | const { bytesRead } = await handle.read(chunk, 0, chunk.length, size); |
| 140 | if (!bytesRead) break; |
| 141 | chunks.push(chunk.subarray(0, bytesRead)); |
| 142 | size += bytesRead; |
| 143 | } |
| 144 | stats = await handle.stat(); |
| 145 | if (size > MAX_SOURCE_FILE_SIZE_BYTES || stats.size > MAX_SOURCE_FILE_SIZE_BYTES) { |
| 146 | stats.size = Math.max(size, stats.size); |
| 147 | return { stats, bytes: null }; |
| 148 | } |
| 149 | return { stats, bytes: Buffer.concat(chunks, size) }; |
| 150 | } finally { |
| 151 | await handle.close(); |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | /** Synchronous {@link readBoundedSource}. */ |
| 156 | export function readBoundedSourceSync(file: string): BoundedSource { |
no test coverage detected