rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

Add the prompt#

withPrompt() from @rhythmjs/cli/prompt is a use() middleware that adds ctx.prompt to the commands after it and closes its input when the command finishes. By default it reads answer lines through Bun's async-iterable console, and only when you first ask.

TypeScript
import { RhythmCli } from "@rhythmjs/cli";
import { withPrompt } from "@rhythmjs/cli/prompt";
import { toCliHandler } from "@rhythmjs/cli/run";
import { log } from "@rhythmjs/cli/output";

const cli = new RhythmCli().use(withPrompt()).cmd("init", async (ctx) => {
  const name = await ctx.prompt.text("Project name?", { default: "my-app" });
  const confirmed = await ctx.prompt.confirm("Continue?", { default: true });
  if (confirmed) log(ctx, `Created ${name}`);
});

process.exitCode = await toCliHandler(cli)(Bun.argv.slice(2));

The prompt is request-time state, so it lives on the cli rather than on a host app's startup context. Mounted into a host, the cli keeps its own prompt.

Choose an input type#

  • text(message, { default? }) returns trimmed text.
  • confirm(message, { default? }) accepts yes/no input and retries invalid answers.
  • select(message, choices, { allowCustom? }) asks for one numbered choice.
  • multiSelect(message, choices, { allowCustom? }) accepts comma-separated choice numbers.

Allowing custom values adds an “Other” choice and a follow-up text prompt. Selection results may therefore be arbitrary strings.

Supply custom I/O#

For custom environments or tests, pass a factory to withPrompt(() => io). The I/O object has ask(query), write(text), and an optional close(). createStdioPromptIO() is the default one, wired to Bun's console and process.stdout.

TypeScript
const answers = ["my-app", "y"];
const output: string[] = [];

const cli = new RhythmCli().use(
  withPrompt(() => ({
    ask: async () => answers.shift() ?? "",
    write: (text) => void output.push(text),
  })),
);

createPrompt(io) from the same module is the middleware-free form: it returns { prompt, close }, and you call close() yourself.