MCPcopy
hub / github.com/codeaashu/claude-code / drainStdin

Function drainStdin

src/ink/ink.tsx:1664–1718  ·  view source on GitHub ↗
(stdin: NodeJS.ReadStream = process.stdin)

Source from the content-addressed store, hash-verified

1662 */
1663/* eslint-disable custom-rules/no-sync-fs -- must be sync; called from signal handler / unmount */
1664export function drainStdin(stdin: NodeJS.ReadStream = process.stdin): void {
1665 if (!stdin.isTTY) return;
1666 // Drain Node's stream buffer (bytes libuv already pulled in). read()
1667 // returns null when empty — never blocks.
1668 try {
1669 while (stdin.read() !== null) {
1670 /* discard */
1671 }
1672 } catch {
1673 /* stream may be destroyed */
1674 }
1675 // No /dev/tty on Windows; CONIN$ doesn't support O_NONBLOCK semantics.
1676 // Windows Terminal also doesn't buffer mouse reports the same way.
1677 if (process.platform === 'win32') return;
1678 // termios is per-device: flip stdin to raw so canonical-mode line
1679 // buffering doesn't hide partial input from the non-blocking read.
1680 // Restored in the finally block.
1681 const tty = stdin as NodeJS.ReadStream & {
1682 isRaw?: boolean;
1683 setRawMode?: (raw: boolean) => void;
1684 };
1685 const wasRaw = tty.isRaw === true;
1686 // Drain the kernel TTY buffer via a fresh O_NONBLOCK fd. Bounded at 64
1687 // reads (64KB) — a real mouse burst is a few hundred bytes; the cap
1688 // guards against a terminal that ignores O_NONBLOCK.
1689 let fd = -1;
1690 try {
1691 // setRawMode inside try: on revoked TTY (SIGHUP/SSH disconnect) the
1692 // ioctl throws EBADF — same recovery path as openSync/readSync below.
1693 if (!wasRaw) tty.setRawMode?.(true);
1694 fd = openSync('/dev/tty', fsConstants.O_RDONLY | fsConstants.O_NONBLOCK);
1695 const buf = Buffer.alloc(1024);
1696 for (let i = 0; i < 64; i++) {
1697 if (readSync(fd, buf, 0, buf.length, null) <= 0) break;
1698 }
1699 } catch {
1700 // EAGAIN (buffer empty — expected), ENXIO/ENOENT (no controlling tty),
1701 // EBADF/EIO (TTY revoked — SIGHUP, SSH disconnect)
1702 } finally {
1703 if (fd >= 0) {
1704 try {
1705 closeSync(fd);
1706 } catch {
1707 /* ignore */
1708 }
1709 }
1710 if (!wasRaw) {
1711 try {
1712 tty.setRawMode?.(false);
1713 } catch {
1714 /* TTY may be gone */
1715 }
1716 }
1717 }
1718}
1719/* eslint-enable custom-rules/no-sync-fs */
1720
1721const CONSOLE_STDOUT_METHODS = ['log', 'info', 'debug', 'dir', 'dirxml', 'count', 'countReset', 'group', 'groupCollapsed', 'groupEnd', 'table', 'time', 'timeEnd', 'timeLog'] as const;

Callers 1

drainStdinMethod · 0.85

Calls 2

readSyncFunction · 0.90
readMethod · 0.65

Tested by

no test coverage detected