rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

Define a command#

RhythmCli is a pipeline, like Rhythm and RhythmRouter: it has request-time use() middleware and commands, but no startup phase. Register commands with cmd(command, ...handlers). A command is space-separated words: literal words must match, and words starting with : are params captured into ctx.params. Matching uses the words before the first flag, so deploy staging --force matches deploy :env.

toCliHandler from @rhythmjs/cli/run runs a cli (or a Rhythm host that mounts one) on Bun and returns the exit code.

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

const cli = new RhythmCli({ name: "tool" }).cmd("deploy :environment", (ctx) => {
  log(ctx, `Deploying to ${ctx.params.environment}`);
});

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

Params are typed from the command string: :name is string, :name? is string | undefined (absent when not given), and reading a name that is not in the command is a compile error. :name+, :name* and **:name capture the remaining words as a string[]; a bare * or ** lands in params["0"]. Order is required, then optional, then at most one catch-all; anything else throws when the command is registered. Values are URI-decoded.

An unknown command is reported for you as error: unknown command 'x' with exit code 2 (or no command given). Register cmd("", handler) to handle the no-argument case yourself.

Use it with a host app#

To run startup work around the cli, mount it into a Rhythm app. The host adds long-lived values with register, and mount(cli) widens the host's input so toCliHandler can still run it.

TypeScript
import { Rhythm, decorate, mount } from "@rhythmjs/rhythm";

const app = new Rhythm({ name: "tool" })
  .register(decorate(async () => ({ config: await loadConfig() })))
  .use(mount(cli));

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

A cli that reads ctx.config declares it in its type, new RhythmCli<{ config: Config }>(), and the host supplies it. Errors thrown inside the mounted cli are wrapped as mounted cli "tool" failed with the original as cause.

Read flags and positionals#

Nothing is added to the context unless you ask for it. withParsedArgv() from @rhythmjs/cli/argv adds ctx.flags and ctx.positionals.

TypeScript
import { withParsedArgv } from "@rhythmjs/cli/argv";
import { log } from "@rhythmjs/cli/output";

const cli = new RhythmCli().use(withParsedArgv()).cmd("greet :name?", (ctx) => {
  const message = `hello ${ctx.params.name ?? "world"}`;
  log(ctx, ctx.flags.shout ? message.toUpperCase() : message);
});

ctx.flags holds string or boolean values. --verbose is true when no value follows; --target=prod and --target prod supply a string. A following non-flag token becomes a value, so --verbose deploy consumes deploy. -abc is a single flag named abc, not three short flags. -- ends flag parsing. No schema validation or numeric coercion is performed.

Group commands#

There is no prefix option: write the full words on each command. Group related commands in one cli by sharing the leading words, and mount several clis into a host.

TypeScript
const remote = new RhythmCli({ name: "remote" })
  .cmd("remote add :name :url", (ctx) => log(ctx, `Added ${ctx.params.name}: ${ctx.params.url}`))
  .cmd("remote remove :name", (ctx) => log(ctx, `Removed ${ctx.params.name}`));

const app = new Rhythm().use(mount(cli)).use(mount(remote));

Write output and set the exit code#

The context carries argv, stdout, stderr and exitCode. Output goes through plain functions from @rhythmjs/cli/output: log(ctx, ...) (stdout), error(ctx, ...) (stderr) and fail(ctx, message, code = 1), which prints error: message to stderr and sets the exit code. ctx.exitCode is also writable directly. toCliHandler returns the exit code (zero by default), and a thrown error becomes an error line with exit code 1.

fail() sets a value; it does not terminate the process or stop middleware. Return without calling next() to stop downstream execution, as in this guard:

TypeScript
const cli = new RhythmCli().cmd(
  "deploy :env",
  (ctx, next) => {
    if (!["staging", "production"].includes(ctx.params.env)) return fail(ctx, `unknown environment '${ctx.params.env}'`);
    return next();
  },
  (ctx) => log(ctx, `deployed to ${ctx.params.env}`),
);

cli.use(middleware) wraps every command of that cli and runs only when a command matched, so a guard never answers an unknown command. A derive() as use() argument, or as the first handler of one command, widens the context type. Pass { stdout, stderr } as the second argument of toCliHandler to capture output, for example in tests.

Add --help#

The cli has no help output of its own. @rhythmjs/climax adds --help, -h and help <command> from the commands you registered, with a documentation middleware for each command and flag.