@bemoje/cli 4.0.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,372 +1,382 @@
1
- # @bemoje/cli
2
-
3
- A type-safe CLI framework for building command-line interfaces with typed arguments, options, subcommands, and auto-generated help - without execution coupling.
4
-
5
- [![TypeScript](https://img.shields.io/badge/TypeScript-5-blue)](https://www.typescriptlang.org/) [![Module](https://img.shields.io/badge/Module-ESM-yellow)](https://nodejs.org/api/esm.html)
6
-
7
- ## Exports
8
-
9
- <!-- EXPORTS_START -->
10
-
11
- - **Command**: a type-safe CLI composer that can parse argv and generate help without execution coupling.
12
- - **Help**: This is a fork of the Help class from the 'commander' npm package. The Help class method names as well as the expected interface of the Command instance to parse, are both similar, but different and not compatible without custom adaptations,
13
- - **findCommand**: Finds subcommand by name or alias
14
- - **findOption**: Finds option by name, short name or long name
15
- - **getCommandAncestors**: Returns all ancestor commands excluding this command
16
- - **getCommandAndAncestors**: Returns command and all ancestor commands in hierarchy
17
- - **parseOptionFlags**: Parses option flags string into its components
18
-
19
- <!-- EXPORTS_END -->
20
-
21
- ## Installation
22
-
23
- ```bash
24
- npm install @bemoje/cli
25
- ```
26
-
27
- ## Features
28
-
29
- - **Full type inference** - Arguments, options, and parsed results are fully typed. The types update as you chain `.addArgument()` and `.addOption()` calls.
30
- - **Declarative, chainable API** - Build commands fluently with method chaining; each call returns a narrowed type.
31
- - **Subcommand hierarchies** - Nest commands arbitrarily deep. Options are inherited by subcommands. Aliases are auto-generated.
32
- - **Auto-generated help** - Colorized, grouped, and wrapped help output from your command definitions. Fully customizable via the `Help` class.
33
- - **Built-in `--help`, `--debug`, and `--version` flags** - Automatically added to root commands.
34
- - **Option hooks** - Register side-effect actions that trigger when specific options are set (e.g., `--help` prints help and sets `process.exitCode`).
35
- - **Parse-only design** - `parseArgv()` returns a result object with `args`, `opts`, `errors`, `hooks`, and an `execute()` method. You control when and whether execution happens.
36
- - **Validation** - Missing required arguments, unknown options, and invalid choices are reported as errors on the result.
37
- - **Variadic arguments and options** - Both arguments and options support variadic (`...`) syntax to collect multiple values into arrays.
38
- - **Environment variable defaults** - Options can fall back to environment variables via the `env` option.
39
- - **Argument and option choices** - Restrict allowed values with `choices` arrays; violations are reported as validation errors.
40
- - **Negatable boolean flags** - Pass `--no-<flag>` to set a boolean option to `false`.
41
- - **kebab-case to camelCase mapping** - Multi-word option names like `--output-dir` are automatically available as `opts.outputDir`.
42
- - **Hidden commands and options** - Exclude items from help output while keeping them functional.
43
- - **Grouped help sections** - Organize options and subcommands into named groups in the help output.
44
-
45
- ## Usage
46
-
47
- ### Basic Command
48
-
49
- ```ts
50
- import { Command } from '@bemoje/cli'
51
-
52
- const cli = new Command('greet')
53
- .setDescription('Greet someone')
54
- .addArgument('<name>')
55
- .addOption('-l, --loud', { description: 'Shout the greeting' })
56
- .setAction((name, opts) => {
57
- const msg = `Hello, ${name}!`
58
- console.log(opts.loud ? msg.toUpperCase() : msg)
59
- })
60
-
61
- cli.parseArgv(process.argv.slice(2))
62
- ```
63
-
64
- ### Arguments
65
-
66
- Arguments are positional values parsed from `argv`. They support required (`<name>`), optional (`[name]`), and variadic (`<name...>`, `[name...]`) forms.
67
-
68
- ```ts
69
- const cmd = new Command('copy')
70
- .addArgument('<source>') // required string
71
- .addArgument('[destination]', { defaultValue: '.' }) // optional with default
72
- .setAction((source, destination, opts) => {
73
- console.log(`Copying ${source} to ${destination}`)
74
- })
75
-
76
- cmd.parseArgv(['file.txt'])
77
- // args: ['file.txt', '.']
78
- ```
79
-
80
- **Variadic arguments** collect all remaining positional values into an array. Only the last argument may be variadic.
81
-
82
- ```ts
83
- const cmd = new Command('concat').addArgument('<files...>').setAction((files, opts) => {
84
- // files is string[]
85
- console.log(`Concatenating: ${files.join(', ')}`)
86
- })
87
-
88
- cmd.parseArgv(['a.txt', 'b.txt', 'c.txt'])
89
- // args: [['a.txt', 'b.txt', 'c.txt']]
90
- ```
91
-
92
- **Choices** can restrict which values are accepted:
93
-
94
- ```ts
95
- const cmd = new Command('deploy').addArgument('<env>', { choices: ['dev', 'staging', 'prod'] })
96
- ```
97
-
98
- **Ordering rules** are enforced at both the type level and at runtime:
99
-
100
- - Required arguments must come before optional ones
101
- - Only the last argument may be variadic
102
- - A command with arguments cannot have subcommands (and vice versa)
103
-
104
- ### Options
105
-
106
- Options are named flags parsed from `argv`. The format is always `-<short>, --<long> [value-syntax]`.
107
-
108
- ```ts
109
- const cmd = new Command('build')
110
- .addOption('-o, --output <dir>', { description: 'Output directory' }) // required string
111
- .addOption('-m, --minify', { description: 'Minify output' }) // boolean flag
112
- .addOption('-w, --watch [mode]', { description: 'Watch mode', defaultValue: 'poll' }) // optional string with default
113
- .setAction((opts) => {
114
- console.log(opts.output) // string
115
- console.log(opts.minify) // boolean | undefined
116
- console.log(opts.watch) // string
117
- })
118
- ```
119
-
120
- **Variadic options** collect multiple values into an array:
121
-
122
- ```ts
123
- const cmd = new Command('lint')
124
- .addOption('-i, --include <patterns...>', { description: 'Include globs' }) // required: string[]
125
- .addOption('-e, --exclude [patterns...]', { description: 'Exclude globs', defaultValue: ['node_modules'] })
126
-
127
- cmd.parseArgv(['-i', 'src', 'lib', '-e', 'test'])
128
- // opts.include: ['src', 'lib']
129
- // opts.exclude: ['test']
130
- ```
131
-
132
- **Option choices** restrict valid values:
133
-
134
- ```ts
135
- const cmd = new Command('format').addOption('-f, --format <type>', {
136
- description: 'Output format',
137
- choices: ['json', 'xml', 'yaml'],
138
- })
139
- ```
140
-
141
- **Environment variable defaults** let options fall back to env vars:
142
-
143
- ```ts
144
- const cmd = new Command('deploy').addOption('-t, --token <value>', {
145
- description: 'Auth token',
146
- env: 'AUTH_TOKEN',
147
- })
148
- // If AUTH_TOKEN is set and --token is not passed, opts.token defaults to process.env.AUTH_TOKEN
149
- ```
150
-
151
- **Hidden options** are excluded from help output:
152
-
153
- ```ts
154
- const cmd = new Command('tool').addOption('-x, --experimental', {
155
- description: 'Experimental feature',
156
- hidden: true,
157
- })
158
- ```
159
-
160
- **Grouped options** appear under custom headings in help:
161
-
162
- ```ts
163
- const cmd = new Command('server')
164
- .addOption('-p, --port <n>', { description: 'Port number', group: 'Network:' })
165
- .addOption('-H, --host [addr]', { description: 'Host address', group: 'Network:' })
166
- .addOption('-v, --verbose', { description: 'Verbose logging', group: 'Logging:' })
167
- ```
168
-
169
- **Negatable flags** - any boolean option can be negated with `--no-<name>`:
170
-
171
- ```ts
172
- const cmd = new Command('build').addOption('-c, --color', { description: 'Colorize output' })
173
-
174
- cmd.parseArgv(['--no-color'])
175
- // opts.color: false
176
- ```
177
-
178
- **kebab-case to camelCase** - multi-word option names are automatically camelCased:
179
-
180
- ```ts
181
- const cmd = new Command('build').addOption('-o, --output-dir <path>', { description: 'Output directory' })
182
-
183
- cmd.parseArgv(['--output-dir', '/tmp'])
184
- // opts.outputDir: '/tmp'
185
- ```
186
-
187
- ### Subcommands
188
-
189
- Use `.command()` to create a subcommand and get it back, or `.addCommand()` to add one via callback and get the parent back for chaining.
190
-
191
- Options defined on the parent are automatically inherited by subcommands. Aliases are auto-generated from subcommand name initials (e.g., `build-project` gets alias `bp`).
192
-
193
- ```ts
194
- const cli = new Command('git')
195
- .setDescription('A version control system')
196
- .addOption('-v, --verbose', { description: 'Verbose output' })
197
-
198
- .addCommand('clone', (sub) =>
199
- sub
200
- .setDescription('Clone a repository')
201
- .addArgument('<url>')
202
- .addOption('-d, --depth <n>', { description: 'Shallow clone depth' })
203
- .setAction((url, opts) => {
204
- // opts.verbose is inherited from parent
205
- console.log(`Cloning ${url} with depth ${opts.depth ?? 'full'}`)
206
- })
207
- )
208
-
209
- .addCommand('status', (sub) =>
210
- sub
211
- .setDescription('Show working tree status')
212
- .addOption('-s, --short', { description: 'Short format output' })
213
- .setAction((opts) => {
214
- console.log('Status:', opts.short ? 'clean' : 'On branch main...')
215
- })
216
- )
217
-
218
- cli.parseArgv(['clone', 'https://github.com/user/repo', '-d', '1'])
219
- ```
220
-
221
- **Aliases** can also be set manually:
222
-
223
- ```ts
224
- const cli = new Command('app')
225
- cli.command('install').setAliases('i', 'add')
226
- ```
227
-
228
- ### Parsing and Execution
229
-
230
- `parseArgv()` does not execute the action - it returns a result object:
231
-
232
- ```ts
233
- const cli = new Command('tool')
234
- .addArgument('<input>')
235
- .addOption('-v, --verbose', { description: 'Verbose' })
236
- .setAction((input, opts) => {
237
- console.log(`Processing ${input}`)
238
- })
239
-
240
- const result = cli.parseArgv(['file.txt', '-v'])
241
-
242
- result.path // string[] - subcommand path segments
243
- result.name // string - command name
244
- result.argv // string[] - the argv that was parsed
245
- result.args // [string] - typed parsed arguments
246
- result.opts // { verbose: true } - typed parsed options
247
- result.errors // string[] | undefined - validation errors
248
- result.hooks // HookDefinition[] - triggered hooks
249
- result.cmd // Command - the matched command instance
250
-
251
- // Execute the action (and any triggered hooks) when you're ready:
252
- await result.execute()
253
- ```
254
-
255
- **Validation errors** are collected, not thrown. Check `result.errors` before executing:
256
-
257
- ```ts
258
- const result = cli.parseArgv([])
259
- if (result.errors) {
260
- console.error(result.errors.join('\n'))
261
- process.exitCode = 1
262
- } else {
263
- await result.execute()
264
- }
265
- ```
266
-
267
- When `execute()` is called, hooks run first (in order). If any hook sets `process.exitCode`, execution stops. Then the main action runs inside a timer that provides a logger.
268
-
269
- ### Option Hooks
270
-
271
- Hooks let you attach side-effect actions that run when a specific option is set. The built-in `--help`, `--debug`, and `--version` flags are all implemented as hooks.
272
-
273
- ```ts
274
- const cli = new Command('tool')
275
- .addOption('-c, --clean', { description: 'Clean before running' })
276
- .addOptionHook('clean', ({ cmd, opts }) => {
277
- console.log('Cleaning build artifacts...')
278
- // Hook runs before the main action
279
- })
280
- .setAction((opts) => {
281
- console.log('Running tool...')
282
- })
283
- ```
284
-
285
- Hooks are evaluated in registration order. If a hook sets `process.exitCode`, subsequent hooks and the main action are skipped.
286
-
287
- ### Help Output
288
-
289
- Help is auto-generated with ANSI color support, word wrapping, and section grouping.
290
-
291
- ```ts
292
- const cli = new Command('my-tool')
293
- .setVersion('1.0.0')
294
- .setDescription('A great CLI tool')
295
- .addArgument('<input>')
296
- .addOption('-v, --verbose', { description: 'Verbose output' })
297
-
298
- // Render help string (with ANSI colors)
299
- console.log(cli.renderHelp())
300
-
301
- // Render plain text (no ANSI)
302
- console.log(cli.renderHelp({ noColor: true }))
303
- ```
304
-
305
- **Customize help rendering** via `.helpConfiguration()`:
306
-
307
- ```ts
308
- cli.helpConfiguration((help) => {
309
- help.sortSubcommands = false
310
- help.sortOptions = false
311
- help.helpWidth = 120
312
- })
313
- ```
314
-
315
- The `Help` class exposes many styleable and overridable methods for full control over the output format:
316
-
317
- | Method | Purpose |
318
- | --------------------------- | --------------------------------------------- |
319
- | `styleTitle(str)` | Style section headings ("Usage:", "Options:") |
320
- | `styleUsage(str)` | Style the usage line |
321
- | `styleOptionTerm(str)` | Style option flags |
322
- | `styleSubcommandTerm(str)` | Style subcommand entries |
323
- | `styleArgumentTerm(str)` | Style argument entries |
324
- | `styleDescriptionText(str)` | Base style for all descriptions |
325
- | `formatItem(term, w, desc)` | Format a term/description pair with padding |
326
- | `boxWrap(str, width)` | Wrap text at whitespace to fit width |
327
-
328
- ### Type Safety
329
-
330
- The `Command` class tracks argument and option types through generics that update with each chained call. This means your action handler receives correctly typed parameters:
331
-
332
- ```ts
333
- const cmd = new Command('example')
334
- .addArgument('<name>') // A = [string]
335
- .addArgument('[count]', { defaultValue: '1' }) // A = [string, string]
336
- .addOption('-v, --verbose', {}) // O = { verbose?: boolean, ... }
337
- .addOption('-f, --format <type>', {}) // O = { verbose?: boolean, format: string, ... }
338
- .setAction((name, count, opts) => {
339
- // name: string, count: string, opts: { verbose?: boolean, format: string, ... }
340
- })
341
- ```
342
-
343
- Invalid argument orderings (e.g., required after optional, anything after variadic) are caught at the **type level** - TypeScript will reject the code before it runs.
344
-
345
- ### Helpers
346
-
347
- ```ts
348
- import {
349
- findCommand,
350
- findOption,
351
- parseOptionFlags,
352
- getCommandAncestors,
353
- getCommandAndAncestors,
354
- } from '@bemoje/cli'
355
-
356
- // Find a subcommand by name or alias
357
- const sub = findCommand(cli, 'clone') // Command | undefined
358
- const sub2 = findCommand(cli, 'c') // also works with aliases
359
-
360
- // Find an option by name, short flag, or long flag
361
- const opt = findOption(cli, 'verbose') // Option | undefined
362
- const opt2 = findOption(cli, '-v') // by short flag
363
- const opt3 = findOption(cli, '--verbose') // by long flag
364
-
365
- // Parse raw flag syntax into components
366
- parseOptionFlags('-o, --output <dir>')
367
- // => { short: 'o', long: 'output', name: 'output', argName: 'dir' }
368
-
369
- // Navigate command hierarchy
370
- getCommandAncestors(sub) // parent commands (excluding self)
371
- getCommandAndAncestors(sub) // [self, parent, grandparent, ...]
372
- ```
1
+ # @bemoje/cli
2
+
3
+ A type-safe CLI framework for building command-line interfaces with typed arguments, options, subcommands, and auto-generated help - without execution coupling.
4
+
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5-blue)](https://www.typescriptlang.org/) [![Module](https://img.shields.io/badge/Module-ESM-yellow)](https://nodejs.org/api/esm.html)
6
+
7
+ ## Exports
8
+
9
+ <!-- EXPORTS_START -->
10
+
11
+ - **Command**: a type-safe CLI composer that can parse argv and generate help without execution coupling.
12
+ - **Help**: This is a fork of the Help class from the 'commander' npm package. The Help class method names as well as the expected interface of the Command instance to parse, are both similar, but different and not compatible without custom adaptations,
13
+ - **findCommand**: Finds subcommand by name or alias
14
+ - **findOption**: Finds option by name, short name or long name
15
+ - **getCommandAncestors**: Returns all ancestor commands excluding this command
16
+ - **getCommandAndAncestors**: Returns command and all ancestor commands in hierarchy
17
+ - **parseOptionFlags**: Parses option flags string into its components
18
+
19
+ <!-- EXPORTS_END -->
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ npm install @bemoje/cli
25
+ ```
26
+
27
+ ## Features
28
+
29
+ - **Full type inference** - Arguments, options, and parsed results are fully typed. The types update as you chain `.addArgument()` and `.addOption()` calls.
30
+ - **Declarative, chainable API** - Build commands fluently with method chaining; each call returns a narrowed type.
31
+ - **Subcommand hierarchies** - Nest commands arbitrarily deep. Options are inherited by subcommands. Aliases are auto-generated.
32
+ - **Auto-generated help** - Colorized, grouped, and wrapped help output from your command definitions. Fully customizable via the `Help` class.
33
+ - **Built-in `--help`, `--debug`, and `--version` flags** - Automatically added to root commands. An option of your own with the same long name replaces one, and one of your own may take its short flag.
34
+ - **Option hooks** - Register side-effect actions that trigger when specific options are set (e.g., `--help` prints help and sets `process.exitCode`).
35
+ - **Parse-only design** - `parseArgv()` returns a result object with `args`, `opts`, `errors`, `hooks`, and an `execute()` method. You control when and whether execution happens.
36
+ - **Validation** - Missing required arguments and options, options given without their value, unknown options and subcommands, arguments no definition takes, and invalid choices are reported as errors on the result.
37
+ - **Variadic arguments and options** - Both arguments and options support variadic (`...`) syntax to collect multiple values into arrays.
38
+ - **Environment variable defaults** - Options can fall back to environment variables via the `env` option.
39
+ - **Argument and option choices** - Restrict allowed values with `choices` arrays; violations are reported as validation errors.
40
+ - **Negatable boolean flags** - Pass `--no-<flag>` to set a boolean option to `false`.
41
+ - **kebab-case to camelCase mapping** - Multi-word option names like `--output-dir` are automatically available as `opts.outputDir`.
42
+ - **Hidden commands and options** - Exclude items from help output while keeping them functional.
43
+ - **Grouped help sections** - Organize options and subcommands into named groups in the help output.
44
+
45
+ ## Usage
46
+
47
+ ### Basic Command
48
+
49
+ ```ts
50
+ import { Command } from '@bemoje/cli'
51
+
52
+ const cli = new Command('greet')
53
+ .setDescription('Greet someone')
54
+ .addArgument('<name>')
55
+ .addOption('-l, --loud', { description: 'Shout the greeting' })
56
+ .setAction((name, opts) => {
57
+ const msg = `Hello, ${name}!`
58
+ console.log(opts.loud ? msg.toUpperCase() : msg)
59
+ })
60
+
61
+ cli.parseArgv(process.argv.slice(2))
62
+ ```
63
+
64
+ ### Arguments
65
+
66
+ Arguments are positional values parsed from `argv`. They support required (`<name>`), optional (`[name]`), and variadic (`<name...>`, `[name...]`) forms.
67
+
68
+ ```ts
69
+ const cmd = new Command('copy')
70
+ .addArgument('<source>') // required string
71
+ .addArgument('[destination]', { defaultValue: '.' }) // optional with default
72
+ .setAction((source, destination, opts) => {
73
+ console.log(`Copying ${source} to ${destination}`)
74
+ })
75
+
76
+ cmd.parseArgv(['file.txt'])
77
+ // args: ['file.txt', '.']
78
+ ```
79
+
80
+ **Variadic arguments** collect all remaining positional values into an array. Only the last argument may be variadic.
81
+
82
+ ```ts
83
+ const cmd = new Command('concat').addArgument('<files...>').setAction((files, opts) => {
84
+ // files is string[]
85
+ console.log(`Concatenating: ${files.join(', ')}`)
86
+ })
87
+
88
+ cmd.parseArgv(['a.txt', 'b.txt', 'c.txt'])
89
+ // args: [['a.txt', 'b.txt', 'c.txt']]
90
+ ```
91
+
92
+ **Choices** can restrict which values are accepted:
93
+
94
+ ```ts
95
+ const cmd = new Command('deploy').addArgument('<env>', { choices: ['dev', 'staging', 'prod'] })
96
+ ```
97
+
98
+ **Ordering rules** are enforced at both the type level and at runtime:
99
+
100
+ - Required arguments must come before optional ones
101
+ - Only the last argument may be variadic
102
+ - A command with arguments cannot have subcommands (and vice versa)
103
+
104
+ ### Options
105
+
106
+ Options are named flags parsed from `argv`. The format is always `-<short>, --<long> [value-syntax]`.
107
+
108
+ An option written with `<value>` is required: when it is not given and has no `defaultValue` and no `env` value, `parseArgv()` reports `Missing option ...` in `errors`. Write it `[value]` when it may be left out. Either way, an option that takes a value must be given one: `--output` at the end of argv, or followed by another option, is the error `Option --output requires a value`. A value is given as `--output dist`, `--output=dist`, `-o dist`, `-odist` or `-o=dist`; a negative number or a lone `-` is taken as a value, and any value that starts with `-` can be given with `=` (`--output=-x`).
109
+
110
+ ```ts
111
+ const cmd = new Command('build')
112
+ .addOption('-o, --output <dir>', { description: 'Output directory' }) // required string
113
+ .addOption('-m, --minify', { description: 'Minify output' }) // boolean flag
114
+ .addOption('-w, --watch [mode]', { description: 'Watch mode', defaultValue: 'poll' }) // optional string with default
115
+ .setAction((opts) => {
116
+ console.log(opts.output) // string
117
+ console.log(opts.minify) // boolean | undefined
118
+ console.log(opts.watch) // string
119
+ })
120
+ ```
121
+
122
+ **Variadic options** collect multiple values into an array, up to the next option or `--`. Given more than once, they keep the values of every time. An optional one (`[patterns...]`) given with no value is `[]`:
123
+
124
+ ```ts
125
+ const cmd = new Command('lint')
126
+ .addOption('-i, --include <patterns...>', { description: 'Include globs' }) // required: string[]
127
+ .addOption('-e, --exclude [patterns...]', { description: 'Exclude globs', defaultValue: ['node_modules'] })
128
+
129
+ cmd.parseArgv(['-i', 'src', 'lib', '-e', 'test'])
130
+ // opts.include: ['src', 'lib']
131
+ // opts.exclude: ['test']
132
+ ```
133
+
134
+ **Option choices** restrict valid values:
135
+
136
+ ```ts
137
+ const cmd = new Command('format').addOption('-f, --format <type>', {
138
+ description: 'Output format',
139
+ choices: ['json', 'xml', 'yaml'],
140
+ })
141
+ ```
142
+
143
+ **Environment variable defaults** let options fall back to env vars:
144
+
145
+ ```ts
146
+ const cmd = new Command('deploy').addOption('-t, --token <value>', {
147
+ description: 'Auth token',
148
+ env: 'AUTH_TOKEN',
149
+ })
150
+ // If AUTH_TOKEN is set and --token is not passed, opts.token defaults to process.env.AUTH_TOKEN
151
+ ```
152
+
153
+ **Hidden options** are excluded from help output:
154
+
155
+ ```ts
156
+ const cmd = new Command('tool').addOption('-x, --experimental', {
157
+ description: 'Experimental feature',
158
+ hidden: true,
159
+ })
160
+ ```
161
+
162
+ **Grouped options** appear under custom headings in help:
163
+
164
+ ```ts
165
+ const cmd = new Command('server')
166
+ .addOption('-p, --port <n>', { description: 'Port number', group: 'Network:' })
167
+ .addOption('-H, --host [addr]', { description: 'Host address', group: 'Network:' })
168
+ .addOption('-v, --verbose', { description: 'Verbose logging', group: 'Logging:' })
169
+ ```
170
+
171
+ **Negatable flags** - any boolean option can be negated with `--no-<name>` (an option that takes a value cannot, and a boolean flag takes no value: `--color=false` is an error):
172
+
173
+ ```ts
174
+ const cmd = new Command('build').addOption('-c, --color', { description: 'Colorize output' })
175
+
176
+ cmd.parseArgv(['--no-color'])
177
+ // opts.color: false
178
+ ```
179
+
180
+ **kebab-case to camelCase** - multi-word option names are automatically camelCased:
181
+
182
+ ```ts
183
+ const cmd = new Command('build').addOption('-o, --output-dir <path>', { description: 'Output directory' })
184
+
185
+ cmd.parseArgv(['--output-dir', '/tmp'])
186
+ // opts.outputDir: '/tmp'
187
+ ```
188
+
189
+ ### Subcommands
190
+
191
+ Use `.command()` to create a subcommand and get it back, or `.addCommand()` to add one via callback and get the parent back for chaining.
192
+
193
+ Options defined on the parent are automatically inherited by subcommands, and may be given before the subcommand's name (`git -v clone url`). An unknown subcommand name is reported as ``Unknown command `name` `` in `errors`. Aliases are auto-generated from subcommand name initials (e.g., `build-project` gets alias `bp`).
194
+
195
+ ```ts
196
+ const cli = new Command('git')
197
+ .setDescription('A version control system')
198
+ .addOption('-v, --verbose', { description: 'Verbose output' })
199
+
200
+ .addCommand('clone', (sub) =>
201
+ sub
202
+ .setDescription('Clone a repository')
203
+ .addArgument('<url>')
204
+ .addOption('-d, --depth <n>', { description: 'Shallow clone depth' })
205
+ .setAction((url, opts) => {
206
+ // opts.verbose is inherited from parent
207
+ console.log(`Cloning ${url} with depth ${opts.depth ?? 'full'}`)
208
+ })
209
+ )
210
+
211
+ .addCommand('status', (sub) =>
212
+ sub
213
+ .setDescription('Show working tree status')
214
+ .addOption('-s, --short', { description: 'Short format output' })
215
+ .setAction((opts) => {
216
+ console.log('Status:', opts.short ? 'clean' : 'On branch main...')
217
+ })
218
+ )
219
+
220
+ cli.parseArgv(['clone', 'https://github.com/user/repo', '-d', '1'])
221
+ ```
222
+
223
+ **Aliases** can also be set manually:
224
+
225
+ ```ts
226
+ const cli = new Command('app')
227
+ cli.command('install').setAliases('i', 'add')
228
+ ```
229
+
230
+ ### Parsing and Execution
231
+
232
+ `parseArgv()` does not execute the action - it returns a result object:
233
+
234
+ ```ts
235
+ const cli = new Command('tool')
236
+ .addArgument('<input>')
237
+ .addOption('-v, --verbose', { description: 'Verbose' })
238
+ .setAction((input, opts) => {
239
+ console.log(`Processing ${input}`)
240
+ })
241
+
242
+ const result = cli.parseArgv(['file.txt', '-v'])
243
+
244
+ result.path // string[] - subcommand path segments
245
+ result.name // string - command name
246
+ result.argv // string[] - the argv that was parsed
247
+ result.args // [string] - typed parsed arguments
248
+ result.opts // { verbose: true } - typed parsed options
249
+ result.errors // string[] | undefined - validation errors
250
+ result.hooks // HookDefinition[] - triggered hooks
251
+ result.cmd // Command - the matched command instance
252
+
253
+ // Execute the action (and any triggered hooks) when you're ready:
254
+ await result.execute()
255
+ ```
256
+
257
+ **Validation errors** are collected, not thrown. Check `result.errors` before executing:
258
+
259
+ ```ts
260
+ const result = cli.parseArgv([])
261
+ if (result.errors) {
262
+ console.error(result.errors.join('\n'))
263
+ process.exitCode = 1
264
+ } else {
265
+ await result.execute()
266
+ }
267
+ ```
268
+
269
+ When `execute()` is called, hooks run first (in order). If any hook sets `process.exitCode`, execution stops. Then the main action runs inside a timer that provides a logger.
270
+
271
+ ### Option Hooks
272
+
273
+ Hooks let you attach side-effect actions that run when a specific option is set. The built-in `--help`, `--debug`, and `--version` flags are all implemented as hooks.
274
+
275
+ ```ts
276
+ const cli = new Command('tool')
277
+ .addOption('-c, --clean', { description: 'Clean before running' })
278
+ .addOptionHook('clean', ({ cmd, opts }) => {
279
+ console.log('Cleaning build artifacts...')
280
+ // Hook runs before the main action
281
+ })
282
+ .setAction((opts) => {
283
+ console.log('Running tool...')
284
+ })
285
+ ```
286
+
287
+ Hooks are evaluated in registration order. If a hook sets `process.exitCode`, subsequent hooks and the main action are skipped.
288
+
289
+ **Replacing a built-in** - an option of your own with the long name of a built-in (`--help`, `--debug`, `--version`) replaces it, its hook included, and its type replaces the built-in's. An option of your own may also take a built-in's short flag; the built-in then keeps only its long name:
290
+
291
+ ```ts
292
+ const cli = new Command('server')
293
+ .addOption('-d, --debug', { description: 'Run in debug mode' }) // replaces -D, --debug
294
+ .addOption('-h, --host <addr>', { defaultValue: 'localhost' }) // --help keeps working, without -h
295
+ ```
296
+
297
+ ### Help Output
298
+
299
+ Help is auto-generated with ANSI color support, word wrapping, and section grouping.
300
+
301
+ ```ts
302
+ const cli = new Command('my-tool')
303
+ .setVersion('1.0.0')
304
+ .setDescription('A great CLI tool')
305
+ .addArgument('<input>')
306
+ .addOption('-v, --verbose', { description: 'Verbose output' })
307
+
308
+ // Render help string (with ANSI colors)
309
+ console.log(cli.renderHelp())
310
+
311
+ // Render plain text (no ANSI)
312
+ console.log(cli.renderHelp({ noColor: true }))
313
+ ```
314
+
315
+ **Customize help rendering** via `.helpConfiguration()`:
316
+
317
+ ```ts
318
+ cli.helpConfiguration((help) => {
319
+ help.sortSubcommands = false
320
+ help.sortOptions = false
321
+ help.helpWidth = 120
322
+ })
323
+ ```
324
+
325
+ The `Help` class exposes many styleable and overridable methods for full control over the output format:
326
+
327
+ | Method | Purpose |
328
+ | --------------------------- | --------------------------------------------- |
329
+ | `styleTitle(str)` | Style section headings ("Usage:", "Options:") |
330
+ | `styleUsage(str)` | Style the usage line |
331
+ | `styleOptionTerm(str)` | Style option flags |
332
+ | `styleSubcommandTerm(str)` | Style subcommand entries |
333
+ | `styleArgumentTerm(str)` | Style argument entries |
334
+ | `styleDescriptionText(str)` | Base style for all descriptions |
335
+ | `formatItem(term, w, desc)` | Format a term/description pair with padding |
336
+ | `boxWrap(str, width)` | Wrap text at whitespace to fit width |
337
+
338
+ ### Type Safety
339
+
340
+ The `Command` class tracks argument and option types through generics that update with each chained call. This means your action handler receives correctly typed parameters:
341
+
342
+ ```ts
343
+ const cmd = new Command('example')
344
+ .addArgument('<name>') // A = [string]
345
+ .addArgument('[count]', { defaultValue: '1' }) // A = [string, string]
346
+ .addOption('-v, --verbose', {}) // O = { verbose?: boolean, ... }
347
+ .addOption('-f, --format <type>', {}) // O = { verbose?: boolean, format: string, ... }
348
+ .setAction((name, count, opts) => {
349
+ // name: string, count: string, opts: { verbose?: boolean, format: string, ... }
350
+ })
351
+ ```
352
+
353
+ Invalid argument orderings (e.g., required after optional, anything after variadic) are caught at the **type level** - TypeScript will reject the code before it runs.
354
+
355
+ ### Helpers
356
+
357
+ ```ts
358
+ import {
359
+ findCommand,
360
+ findOption,
361
+ parseOptionFlags,
362
+ getCommandAncestors,
363
+ getCommandAndAncestors,
364
+ } from '@bemoje/cli'
365
+
366
+ // Find a subcommand by name or alias
367
+ const sub = findCommand(cli, 'clone') // Command | undefined
368
+ const sub2 = findCommand(cli, 'c') // also works with aliases
369
+
370
+ // Find an option by name, short flag, or long flag
371
+ const opt = findOption(cli, 'verbose') // Option | undefined
372
+ const opt2 = findOption(cli, '-v') // by short flag
373
+ const opt3 = findOption(cli, '--verbose') // by long flag
374
+
375
+ // Parse raw flag syntax into components
376
+ parseOptionFlags('-o, --output <dir>')
377
+ // => { short: 'o', long: 'output', name: 'output', argName: 'dir' }
378
+
379
+ // Navigate command hierarchy
380
+ getCommandAncestors(sub) // parent commands (excluding self)
381
+ getCommandAndAncestors(sub) // [self, parent, grandparent, ...]
382
+ ```