The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { Readable, Writable } from "node:stream" |
| 2 | |
| 3 | // Keep teardown errors handled after removing the consumer's lifecycle listeners. |
| 4 | // Node emits the destruction error (if any) only once _destroy has completed. |
| 5 | // When `onDestroyed` is given, it is called once destruction has settled and |
| 6 | // the wait keeps the event loop alive. |
| 7 | export const destroyStream = ( |
| 8 | stream: Readable | Writable, |
| 9 | cleanup: () => void, |
| 10 | onDestroyed?: () => void |
| 11 | ): void => { |
| 12 | if (!("closed" in stream)) { |
| 13 | cleanup() |
| 14 | onDestroyed?.() |
| 15 | return |
| 16 | } |
| 17 | const onDone = () => { |
| 18 | clearImmediate(immediate) |
| 19 | stream.off("error", onDone) |
| 20 | stream.off("close", onDone) |
| 21 | onDestroyed?.() |
| 22 | } |
| 23 | // With emitClose: false, successful destruction emits no event. Check the |
| 24 | // public closed flag on a later turn, after any queued destruction error. |
| 25 | // This also protects streams already closed but with an error still queued. |
| 26 | const onClosed = () => { |
| 27 | if (stream.closed) { |
| 28 | onDone() |
| 29 | } else { |
| 30 | immediate = setImmediate(onClosed) |
| 31 | if (!onDestroyed) immediate.unref() |
| 32 | } |
| 33 | } |
| 34 | let immediate = setImmediate(onClosed) |
| 35 | if (!onDestroyed) immediate.unref() |
| 36 | stream.once("error", onDone) |
| 37 | stream.once("close", onDone) |
| 38 | cleanup() |
| 39 | if (!stream.closed) { |
| 40 | stream.destroy() |
| 41 | } |
| 42 | } |