How-to › Ship a CLI or REPL

How to build an oclif CLI with one topic per API resource#

Scaffold an oclif CLI from flags, give each API resource a topic directory, build the client in a base command, and fix the topic separator before release.

Audience
API producer
Level
intermediate
Topic
Build a CLI over an API
Languages
TypeScript
Verified

Read first: Derive a noun-verb command tree from an OpenAPI document

Your CLI over the Pantry API started as one file of commander calls. At forty commands, finding where items create is declared takes a search. Every command builds its own client and reads the token its own way. A shell script written against pantry items list breaks the day a contributor switches the syntax to items:list.

What you get

You will end up with an oclif CLI whose resources are topics, whose commands share one base class that builds the generated client, and whose topic separator is fixed and tested. This is for you if a TypeScript CLI over your API has outgrown one file.

Short answer

Scaffold with oclif generate, answering every prompt with a flag. Put each command at src/commands/<resource>/<verb>.ts so each resource is a topic, describe the topics under oclif.topics in package.json, and keep topicSeparator a space. Build the generated client in a base command every command extends, on first use, so help never constructs it. Then run bin/dev.js items list against the API.

You will need

Node 20 or later and an OpenAPI 3 document. Verified 2026-11-22 against Node 22.23.5, oclif 6.0.15, @oclif/core 4.14.0, openapi-fetch 0.17.0, NSwag 14.8.0, and @voxgig/sdkgen 4.44.3. The document, api.json, describes four operations on two resources, items and shelves, behind a bearer token. The command names follow Derive a noun-verb command tree from an OpenAPI document. Every command runs against server.mjs, a local stand-in that refuses whatever the document does not allow.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
commanderA dozen commands in one file, and start-up time mattersCommands declared in code, or as one executable file per command, and no plug-in systemThe tree grows past what one file can hold
NSwagThe team already generates its C# clients with NSwagNeeds a .NET runtime to generate, ignores the security scheme, and defaults to window for fetchNo .NET in the build, or you want auth generated
openapi-typescript and openapi-fetchYou want typed calls with one small runtime dependencyCalls are paths and methods, and no retries, auth, or id checks come with itCallers should get entity methods and shared features
sdkgen TypeScript targetThe API owner already ships an sdkgen SDK the CLI can shareA 245 KB CommonJS tree per API, untyped entity calls, and a generation step to runYou want path-typed calls and nothing to scaffold
yargsRicher parsing: coercion, middleware, and strict mode, with a module per command if you wantEach topic needs a builder that calls commandDir() again, and there is no plug-in systemUsers should add plug-ins to the CLI they installed

Voxgig maintains sdkgen. It is one of five options in that table, and the one this sample defaults to, so read its cost cell as closely as the others.

The table mixes two decisions: which framework parses the commands, and which client they call. commander started faster than every oclif variant in every round measured below, and yargs faster than oclif without a manifest. yargs loads a directory of command modules through commandDir(), but neither it nor commander has oclif’s plug-in system. openapi-fetch is the lightest client and leaves auth and id checks to you, while NSwag and sdkgen each need a generation run whose output you commit.

Scaffold the CLI and give each resource a topic

Every question oclif generate asks has a flag, and --yes takes the defaults for the rest, as its generator page documents. record.sh runs it once with every answer given.

(cd "$WORK" && npx --yes oclif@6.0.15 generate pantry --author "Pantry maintainers" --bin pantry \
  --description "Read and stock the Pantry API" --license MIT --module-type ESM --name pantry-cli \
  --owner example --repository pantry-cli --package-manager npm --yes > generate.txt 2>&1)

The scaffold wrote topicSeparator: " " already, with a hello topic. A topic is a directory under src/commands, and its description comes from the oclif.topics key. This sample replaces hello with one directory per resource, items/{list,get,create}.ts and shelves/list.ts. It keeps the scaffold’s dependencies and drops its lint, test and packaging tools, oclif itself among them, so a real project still needs oclif manifest from somewhere; records/scaffold-package.json is what the scaffold wrote.

  "oclif": {
    "bin": "pantry",
    "dirname": "pantry",
    "commands": "./dist/commands",
    "plugins": [
      "@oclif/plugin-help",
      "@oclif/plugin-plugins"
    ],
    "topicSeparator": " ",
    "topics": {
      "items": {
        "description": "Items on the shelves: list, read and add them."
      },
      "shelves": {
        "description": "The shelves items sit on."
      }
    }
node run.mjs items --help
Items on the shelves: list, read and add them.

USAGE
  $ pantry items COMMAND

COMMANDS
  items create  Put an item on a shelf.
  items get     Read one item.
  items list    List items, on every shelf or on one.

The oclif command, which the scaffold also adds as a development dependency, carries an update check, @oclif/plugin-warn-if-update-available, which asks the npm registry for a newer version. record.sh turns it off with OCLIF_SKIP_NEW_VERSION_CHECK=true. The pantry CLI carries no such plugin, and under strace its items list opened no network connection except the one to the stand-in (records/connects.txt).

Build the client once in a base command

The custom base class declares the flags every command shares under baseFlags, and each command extends it. This one also builds the client, on first use, from the --client flag and PANTRY_TOKEN.

export abstract class PantryCommand<T extends typeof Command> extends Command {
  static baseFlags = {
    'base-url': Flags.string({
      default: 'https://api.example.com/v1',
      helpGroup: 'GLOBAL',
      summary: "The API's base URL, /v1 included.",
    }),
    client: Flags.option({
      default: 'sdkgen' as ClientName,
      helpGroup: 'GLOBAL',
      options: CLIENTS,
      summary: 'The generated client the command calls through.',
    })(),
  }

  protected args!: Args<T>
  protected flags!: Flags<T>
  private client?: PantryApi

  /** The client, built on first use, so --help and a flag error never construct one. */
  protected get api(): PantryApi {
    if (!this.client) {
      const token = process.env.PANTRY_TOKEN
      if (!token) this.error('no token: set PANTRY_TOKEN', {exit: 2})
      this.client = MAKERS[this.flags.client](this.flags['base-url'], token)
    }

    return this.client
  }

A command then holds its flags and one call. The default client is the sdkgen TypeScript target, which generate.sh scaffolded, generated and compiled, and which reads the bearer scheme from the document. run.mjs starts the stand-in and runs bin/dev.js with the token set.

node run.mjs items list
itm_1  Rolled oats    12   A1
itm_2  Basmati rice   4    A1
itm_3  Chickpeas      30   B2
request: GET /v1/items

Wire the same commands to openapi-fetch and NSwag

openapi-typescript wrote src/generated/schema.d.ts, types only, and openapi-fetch’s createClient takes the base URL, the headers, and a fetch of your own, as its API page lists. Calls name a path and a method.

export function makeOpenapiFetch(base: string, token: string): PantryApi {
  const client = createClient<paths>({
    baseUrl: base,
    fetch: reach(base),
    headers: {Authorization: `Bearer ${token}`},
  })

NSwag’s Fetch template wrote one class with a method per operation and an ApiException for failures. It wrote no auth from the document’s bearerAuth scheme, and its constructor falls back to the browser’s window:

    constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
        this.http = http ? http : window as any;
        this.baseUrl = baseUrl ?? "https://api.example.com/v1";
    }

So a CLI passes an http object whose fetch adds the token. The TypeScript generator wiki documents the other route, a clientBaseClass with useTransformOptionsMethod, for teams that regenerate from an nswag.json.

export function makeNswag(base: string, token: string): PantryApi {
  const send = reach(base)
  const http = {
    fetch(url: RequestInfo, init?: RequestInit) {
      const headers = new Headers(init?.headers)
      headers.set('Authorization', `Bearer ${token}`)
      return send(url, {...init, headers})
    },
  }
node run.mjs items create --name Lentils --quantity 2 --shelf B2 --client nswag
itm_4  Lentils        2    B2
request: POST /v1/items

Measure what oclif costs at start-up

record.sh compiled the CLI with tsc, wrote a manifest with oclif manifest, whose absence the trace on oclif’s performance page flags, and timed items list --help in five CLIs, twice, on one machine on one day.1

one machine: linux x64, 4 CPUs, Intel(R) Xeon(R) Processor @ 2.10GHz
node 22.23.5; 5 rounds of 7 runs each of `items list --help`, interleaved
median per round, in ms:
  commander                       57    70    51    52    49
  yargs                          156   118   124   109   106
  oclif bin/run.js               159   164   159   159   159
  oclif bin/run.js + manifest    134   176   144   157   166
  oclif bin/dev.js              3197  3270  2844  2909  2689
faster in every round:
  commander < yargs
  commander < oclif bin/run.js
  commander < oclif bin/run.js + manifest
  commander < oclif bin/dev.js
  yargs < oclif bin/run.js
  yargs < oclif bin/dev.js
  oclif bin/run.js < oclif bin/dev.js
  oclif bin/run.js + manifest < oclif bin/dev.js

A second run is in records/startup-2.txt, and in both, commander started first in every round. The manifest beat plain bin/run.js in every round of the second run and not of the first, so on four commands it settled nothing. bin/dev.js type-checks through ts-node on each run, so it suits development and never a user’s shell.

Check it worked

clients.test.mjs runs every command through all three clients. test.mjs covers the failures, the records, and the topic check.

node --test clients.test.mjs
# tests 17
# suites 1
# pass 17
# fail 0
node --test test.mjs
# tests 30
# suites 6
# pass 30
# fail 0

topics.mjs compares the directories under src/commands with oclif.topics, and a test feeds it a removed topic, an extra one, a blank description, and empty input. Another test type-checks every source file with tsc --noEmit, and the client tests check the Accept and Content-Type of each GET, which differ by client, so a --client flag that went ignored fails them.

When it goes wrong

The separator changes after a release, and scripts print help text. With ":", pantry items list shows the items topic help, exits 0 and sends no request, so a script that checks the exit code reads success. items has no index.ts command of its own in this sample. pitfall.mjs runs both forms under both separators.

node pitfall.mjs
topicSeparator " "
  pantry items list exit 0, requests 1, first line: itm_1  Rolled oats    12   A1
  pantry items:list exit 0, requests 1, first line: itm_1  Rolled oats    12   A1
topicSeparator ":"
  pantry items list exit 0, requests 0, first line: Items on the shelves: list, read and add them.
  pantry items:list exit 0, requests 1, first line: itm_1  Rolled oats    12   A1
getItem with the guard bypassed
  sdkgen          "."   no request         PantrySDK: load: URL path parameter id cannot be ".".
  sdkgen          ".."  no request         PantrySDK: load: URL path parameter id cannot be "..".
  openapi-fetch   "."   GET /v1/items/     the API answered 404
  openapi-fetch   ".."  GET /v1/           the API answered 404
  nswag           "."   GET /v1/items/     the API answered 404
  nswag           ".."  GET /v1/           the API answered 404
  nswag with no http object: ReferenceError: window is not defined

A space accepts the colon form too, so going from ":" to " " broke nothing here. Decide before the first tag anyway, because the help and every example change.

pantry items get .. lists something else. openapi-fetch and NSwag escape the id, and fetch then removes the dot segment, as the URL Standard parses it.2 The itemId parser in src/base.ts refuses "", . and .. with exit 2. sdkgen refuses the two dot ids itself and sends an empty one as /v1/items/ on 4.44.3 and 4.45.0, which generated/EMPTY-ID records.

When not to do this

Do not adopt oclif for a CLI of five commands. The scaffold’s lockfile held 835 entries before a line of your code, and commander answered --help faster in every round.

Do not ship bin/dev.js to users. It runs ts-node and took seconds where the compiled bin/run.js took a fraction of one.

Do not put the sdkgen target under the CLI only to get a typed client. Its entity calls take plain objects, its tree is 245 KB, and openapi-fetch gives path-typed calls for one dependency. It pays when the API owner publishes that SDK and the CLI should share its behavior.

Pick NSwag when the team already generates C# clients with it, so one nswag.json produces both. openapi-fetch suits a CLI that wants the smallest dependency and is willing to own auth and id checks.

Last verified

Verified 2026-11-22 against Node 22.23.5, oclif 6.0.15, @oclif/core 4.14.0, commander 15.1.0, yargs 18.2.0, openapi-typescript 7.13.0, openapi-fetch 0.17.0, NSwag 14.8.0 on the .NET 10.0.15 runtime, @voxgig/create-sdkgen 0.31.9, @voxgig/sdkgen 4.44.3, and @voxgig/apidef 8.32.4. Every output block is what the command preceding it printed. The three generators and oclif generate ran once, in generate.sh and record.sh, and their output is committed. NSwag needs .NET, which the page’s commands never call.

Footnotes

  1. The performance page’s own sample is a debug trace of the Salesforce CLI’s sf version, listing its plugins one by one, most of them at ten to twenty milliseconds each. One entry, oclif-hello-world, took 239 ms, and the trace marks it as the one plugin with no manifest. That line is the page’s only mention of a manifest. ↩︎ Back to text

  2. The rule is older than fetch. RFC 3986 section 5.2.4 defines remove_dot_segments, which drops . and folds .. into its parent, and the URL Standard applies the same treatment to the single-dot and double-dot path segments it recognizes, %2e spellings included. An id has to reach the path already escaped as something a parser will not read as a direction. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.