# 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.

Source: https://voxgig.com/howto/build-an-oclif-cli-with-topics-per-resource

- Audience: api-producer
- Level: intermediate
- Languages: typescript
- Verified: 2026-11-22
- Published: 2026-11-22

## 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](/howto/derive-a-command-tree-from-operation-ids).
Every command runs against `server.mjs`, a local stand-in that refuses whatever the document does
not allow.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [commander](https://github.com/tj/commander.js) | A dozen commands in one file, and start-up time matters | Commands declared in code, or as one executable file per command, and no plug-in system | The tree grows past what one file can hold |
| [NSwag](https://github.com/RicoSuter/NSwag/wiki/TypeScriptClientGenerator) | The team already generates its C# clients with NSwag | Needs a .NET runtime to generate, ignores the security scheme, and defaults to `window` for fetch | No .NET in the build, or you want auth generated |
| [openapi-typescript and openapi-fetch](https://openapi-ts.dev/openapi-fetch/) | You want typed calls with one small runtime dependency | Calls are paths and methods, and no retries, auth, or id checks come with it | Callers should get entity methods and shared features |
| [sdkgen TypeScript target](https://github.com/voxgig/sdkgen) | The API owner already ships an sdkgen SDK the CLI can share | A 245 KB CommonJS tree per API, untyped entity calls, and a generation step to run | You want path-typed calls and nothing to scaffold |
| [`yargs`](https://yargs.js.org/docs/) | Richer parsing: coercion, middleware, and strict mode, with a module per command if you want | Each topic needs a builder that calls `commandDir()` again, and there is no plug-in system | Users 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()`](https://github.com/yargs/yargs/blob/main/docs/advanced.md), 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](https://oclif.io/docs/generator_commands/) documents. `record.sh`
runs it once with every answer given.

```bash title="record.sh"
(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](https://oclif.io/docs/topics/). 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.

```json title="package.json"
  "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."
      }
    }
```

```bash
node run.mjs items --help
```

```text output
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](https://oclif.io/docs/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`.

```ts title="src/base.ts"
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.

```bash
node run.mjs items list
```

```text output
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](https://openapi-ts.dev/openapi-fetch/api) lists. Calls name a path and a method.

```ts title="src/clients/openapi-fetch.ts"
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`:

```ts title="src/generated/nswag-client.ts"
    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](https://github.com/RicoSuter/NSwag/wiki/TypeScriptClientGenerator)
documents the other route, a `clientBaseClass` with `useTransformOptionsMethod`, for teams that
regenerate from an `nswag.json`.

```ts title="src/clients/nswag.ts"
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})
    },
  }
```

```bash
node run.mjs items create --name Lentils --quantity 2 --shelf B2 --client nswag
```

```text output
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](https://oclif.io/docs/performance/) flags, and timed
`items list --help` in five CLIs, twice, on one machine on one day.[^1]

```text title="records/startup.txt"
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.

```bash
node --test clients.test.mjs
```

```text output
# tests 17
# suites 1
# pass 17
# fail 0
```

```bash
node --test test.mjs
```

```text output
# 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.

```bash
node pitfall.mjs
```

```text output
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](https://url.spec.whatwg.org/) 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.

## Related how-tos

- [Derive a noun-verb command tree from an OpenAPI document](/howto/derive-a-command-tree-from-operation-ids)

- [Map API parameters to CLI arguments and flags](/howto/map-api-parameters-to-cli-flags-and-arguments)

- [Build a Typer CLI that reuses a generated Python SDK](/howto/typer-cli-over-a-generated-python-sdk)

- [Choose Restish, a generated CLI, or a hand-written one](/howto/choose-restish-generated-or-hand-written-cli)

- [Let an agent drive a CLI instead of tool schemas](/howto/let-an-agent-drive-a-generated-cli)

## 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.

[^1]: The [performance page](https://oclif.io/docs/performance/)'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.

[^2]: The rule is older than `fetch`. [RFC 3986 section
5.2.4](https://www.rfc-editor.org/rfc/rfc3986.html#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.