@bemoje/cli 4.0.1 → 5.0.1
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 +382 -372
- package/lib/index.cjs +419 -243
- package/lib/index.d.cts +40 -29
- package/lib/index.d.ts +40 -29
- package/lib/index.js +1139 -1004
- package/package.json +4 -2
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
|
-
[](https://www.typescriptlang.org/) [](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
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
.addOption('-
|
|
113
|
-
.
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
console.log(opts.
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
.addOption('-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
cmd.
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
cmd.
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
.
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
.
|
|
203
|
-
.
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
.
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
.
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
result
|
|
243
|
-
|
|
244
|
-
result.
|
|
245
|
-
result.
|
|
246
|
-
result.
|
|
247
|
-
result.
|
|
248
|
-
result.
|
|
249
|
-
result.
|
|
250
|
-
|
|
251
|
-
//
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
```ts
|
|
292
|
-
const cli = new Command('
|
|
293
|
-
.
|
|
294
|
-
.
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
})
|
|
313
|
-
```
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
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
|
+
[](https://www.typescriptlang.org/) [](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
|
+
```
|