(file: string)
| 172 | * past the limit. Returns `bytes: null` for an oversize file. |
| 173 | */ |
| 174 | export async function readBoundedSource(file: string): Promise<BoundedSource> { |
| 175 | const initial = await fsp.stat(file); |
| 176 | assertRegularFile(initial); |
| 177 | if (initial.size > MAX_SOURCE_FILE_SIZE_BYTES) return { stats: initial, bytes: null }; |
| 178 | const handle = await fsp.open(file, 'r'); |
| 179 | try { |
| 180 | let stats = await handle.stat(); |
| 181 | assertRegularFile(stats); |
| 182 | if (stats.size > MAX_SOURCE_FILE_SIZE_BYTES) return { stats, bytes: null }; |
| 183 | const chunks: Buffer[] = []; |
| 184 | let size = 0; |
| 185 | while (size <= MAX_SOURCE_FILE_SIZE_BYTES) { |
| 186 | const chunk = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, MAX_SOURCE_FILE_SIZE_BYTES + 1 - size)); |
| 187 | const { bytesRead } = await handle.read(chunk, 0, chunk.length, size); |
| 188 | if (!bytesRead) break; |
| 189 | chunks.push(chunk.subarray(0, bytesRead)); |
| 190 | size += bytesRead; |
| 191 | } |
| 192 | stats = await handle.stat(); |
| 193 | if (size > MAX_SOURCE_FILE_SIZE_BYTES || stats.size > MAX_SOURCE_FILE_SIZE_BYTES) { |
| 194 | stats.size = Math.max(size, stats.size); |
| 195 | return { stats, bytes: null }; |
| 196 | } |
| 197 | return { stats, bytes: Buffer.concat(chunks, size) }; |
| 198 | } finally { |
| 199 | await handle.close(); |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | /** Synchronous {@link readBoundedSource}. */ |
| 204 | export function readBoundedSourceSync(file: string): BoundedSource { |
no test coverage detected