xonecas.io
687
Oc

orc-code / files

orc-code / packages / orc-cli / src / prompt.ts

803 bytes
1import { type Interface, createInterface } from "node:readline/promises";
2
3let rl: Interface | null = null;
4let stdinClosed = false;
5
6function getReadline(): Interface | null {
7	if (stdinClosed) return null;
8	if (!rl) {
9		rl = createInterface({
10			input: process.stdin,
11			output: process.stdout,
12		});
13		rl.on("close", () => {
14			rl = null;
15			stdinClosed = true;
16		});
17	}
18	return rl;
19}
20
21/** Read a line from the user. Returns null on EOF (Ctrl+D) or empty input. */
22export async function readPrompt(prefix: string): Promise<string | null> {
23	const readline = getReadline();
24	if (!readline) return null;
25	try {
26		const line = await readline.question(prefix);
27		return line.trim() || null;
28	} catch {
29		return null;
30	}
31}
32
33export function closePrompt(): void {
34	if (rl) {
35		rl.close();
36		rl = null;
37	}
38}