Something went wrong. Try again.
Something went wrong. Try again.
1.9 kB · 65 lines
TypeScript
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import { stdin, stdout } from "process";
export async function prompt(question: string): Promise<string> { stdout.write(question); return readLine();}
export async function promptPassword(question: string): Promise<string> { stdout.write(question); const isTty = stdin.isTTY === true; if (isTty) stdin.setRawMode?.(true); let buf = ""; for await (const chunk of stdin as AsyncIterable<Buffer>) { for (const b of chunk) { if (b === 3) { // Ctrl-C if (isTty) stdin.setRawMode?.(false); process.exit(130); } if (b === 13 || b === 10) { if (isTty) stdin.setRawMode?.(false); stdout.write("\n"); return buf; } if (b === 127 || b === 8) { buf = buf.slice(0, -1); continue; } buf += String.fromCharCode(b); } } if (isTty) stdin.setRawMode?.(false); return buf;}
async function readLine(): Promise<string> { let buf = ""; for await (const chunk of stdin as AsyncIterable<Buffer>) { buf += chunk.toString("utf8"); const nl = buf.indexOf("\n"); if (nl !== -1) return buf.slice(0, nl).replace(/\r$/, ""); } return buf.replace(/\r$/, "");}
export async function pickFromList( question: string, options: { label: string; value: string }[], customLabel?: string,): Promise<string> { stdout.write(`${question}\n`); options.forEach((o, i) => stdout.write(` ${i + 1}) ${o.label}\n`)); if (customLabel) stdout.write(` ${options.length + 1}) ${customLabel}\n`); const ans = (await prompt("> ")).trim(); const n = Number(ans); if (Number.isInteger(n) && n >= 1 && n <= options.length) { return options[n - 1]!.value; } if (customLabel && n === options.length + 1) { return (await prompt("Enter value: ")).trim(); } // Allow typing a value directly if (ans.length > 0) return ans; throw new Error("no selection");}