(prompt: string, options: QuestionOptions = {})
| 18 | * Returns `null` when stdin reaches EOF (e.g. Ctrl-D on an empty line). |
| 19 | */ |
| 20 | export function question(prompt: string, options: QuestionOptions = {}): Promise<string | null> { |
| 21 | const enableHistory = options.enableHistory ?? false; |
| 22 | const task = chain.then(() => askQuestion(prompt, enableHistory)); |
| 23 | chain = task.catch(() => undefined); |
| 24 | return task; |
| 25 | } |
| 26 | |
| 27 | /** |
| 28 | * Prompt once, recreating the readline interface after job-control resume (Ctrl-Z / fg). |
| 29 | * Suspending clobbers TTY settings; Node's readline does not recover unless the interface |
| 30 | * is restarted on SIGCONT. |
| 31 | */ |
| 32 | async function askQuestion(prompt: string, enableHistory: boolean): Promise<string | null> { |
| 33 | while (true) { |
| 34 | const rl = readline.createInterface({ |
| 35 | input: process.stdin, |
| 36 | output: process.stdout, |
| 37 | ...(enableHistory ? { history: [...history], historySize } : {}), |
| 38 | }); |
| 39 | |
| 40 | const sigcontAbortController = new AbortController(); |
| 41 | |
| 42 | rl.on('SIGCONT', () => { |
| 43 | sigcontAbortController.abort(); |
| 44 | rl.close(); |
| 45 | }); |
| 46 | |
| 47 | const eof = new Promise<null>((resolve) => { |
| 48 | rl.once('close', () => { |
| 49 | if (!sigcontAbortController.signal.aborted) { |
| 50 | resolve(null); |
| 51 | } |
| 52 | }); |
| 53 | }); |
| 54 | |
| 55 | try { |
| 56 | const answer = await Promise.race([rl.question(prompt, { signal: sigcontAbortController.signal }), eof]); |
| 57 | |
| 58 | if (answer === null) { |
| 59 | return null; |
| 60 | } |
| 61 | |
| 62 | if (enableHistory) { |
| 63 | syncHistory(rl, answer); |
| 64 | } |
| 65 | return answer; |
| 66 | } catch (error: unknown) { |
no test coverage detected