| 330 | // has more output to produce (availOut === 0), then resolves the |
| 331 | // promise when all output for this input chunk is collected. |
| 332 | function onWriteComplete() { |
| 333 | const availOut = writeState[0]; |
| 334 | const availInAfter = writeState[1]; |
| 335 | const have = writeAvailOutBefore - availOut; |
| 336 | const bufferExhausted = availOut === 0 || outOffset + have >= chunkSize; |
| 337 | |
| 338 | if (have > 0) { |
| 339 | if (bufferExhausted && outOffset === 0) { |
| 340 | // Entire buffer filled from start - yield directly, no copy. |
| 341 | ArrayPrototypePush(pending, outBuf); |
| 342 | } else if (bufferExhausted) { |
| 343 | // Tail of buffer filled and buffer is being replaced - |
| 344 | // subarray is safe since outBuf reference is overwritten below. |
| 345 | ArrayPrototypePush(pending, |
| 346 | outBuf.subarray(outOffset, outOffset + have)); |
| 347 | } else { |
| 348 | // Partial fill, buffer will be reused - must copy. |
| 349 | ArrayPrototypePush(pending, |
| 350 | TypedArrayPrototypeSlice(outBuf, |
| 351 | outOffset, |
| 352 | outOffset + have)); |
| 353 | } |
| 354 | pendingBytes += have; |
| 355 | outOffset += have; |
| 356 | } |
| 357 | |
| 358 | // Reallocate output buffer if exhausted. |
| 359 | if (bufferExhausted) { |
| 360 | outBuf = Buffer.allocUnsafe(chunkSize); |
| 361 | outOffset = 0; |
| 362 | } |
| 363 | |
| 364 | if (availOut === 0) { |
| 365 | // Engine has more output - but if aborted, don't loop. |
| 366 | if (!resolveWrite) return; |
| 367 | |
| 368 | const consumed = writeAvailIn - availInAfter; |
| 369 | writeInOff += consumed; |
| 370 | writeAvailIn = availInAfter; |
| 371 | writeAvailOutBefore = chunkSize - outOffset; |
| 372 | |
| 373 | handle.write(writeFlush, |
| 374 | writeInput, writeInOff, writeAvailIn, |
| 375 | outBuf, outOffset, writeAvailOutBefore); |
| 376 | return; // Will call onWriteComplete again. |
| 377 | } |
| 378 | |
| 379 | // All input consumed and output collected. |
| 380 | handle.buffer = null; |
| 381 | const resolve = resolveWrite; |
| 382 | resolveWrite = undefined; |
| 383 | rejectWrite = undefined; |
| 384 | if (resolve) resolve(); |
| 385 | } |
| 386 | |
| 387 | // onError: called by C++ when the engine encounters an error. |
| 388 | // Fires instead of onWriteComplete - reject the promise. |