commander 14.0.2 → 15.0.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
@@ -76,7 +76,7 @@ The two most used option types are a boolean option, and an option which takes i
76
76
  Example file: [split.js](./examples/split.js)
77
77
 
78
78
  ```js
79
- const { program } = require('commander');
79
+ import { program } from 'commander';
80
80
 
81
81
  program
82
82
  .option('--first')
@@ -91,10 +91,10 @@ console.log(program.args[0].split(options.separator, limit));
91
91
  ```
92
92
 
93
93
  ```console
94
- $ node split.js -s / --fits a/b/c
94
+ $ node split.js -s - --fits a-b-c
95
95
  error: unknown option '--fits'
96
96
  (Did you mean --first?)
97
- $ node split.js -s / --first a/b/c
97
+ $ node split.js -s - --first a-b-c
98
98
  [ 'a' ]
99
99
  ```
100
100
 
@@ -103,7 +103,7 @@ Here is a more complete program using a subcommand and with descriptions for the
103
103
  Example file: [string-util.js](./examples/string-util.js)
104
104
 
105
105
  ```js
106
- const { Command } = require('commander');
106
+ import { Command } from 'commander';
107
107
  const program = new Command();
108
108
 
109
109
  program
@@ -138,7 +138,7 @@ Options:
138
138
  -s, --separator <char> separator character (default: ",")
139
139
  -h, --help display help for command
140
140
 
141
- $ node string-util.js split --separator=/ a/b/c
141
+ $ node string-util.js split --separator=- a-b-c
142
142
  [ 'a', 'b', 'c' ]
143
143
  ```
144
144
 
@@ -147,14 +147,13 @@ More samples can be found in the [examples](https://github.com/tj/commander.js/t
147
147
  ## Declaring _program_ variable
148
148
 
149
149
  Commander exports a global object which is convenient for quick programs.
150
- This is used in the examples in this README for brevity.
150
+ This is used in some examples in this README for brevity.
151
151
 
152
152
  ```js
153
- // CommonJS (.cjs)
154
- const { program } = require('commander');
153
+ import { program } from 'commander';
155
154
  ```
156
155
 
157
- For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.
156
+ For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local `Command` object to use.
158
157
 
159
158
  ```js
160
159
  // CommonJS (.cjs)
@@ -176,8 +175,7 @@ const program = new Command();
176
175
 
177
176
  ## Options
178
177
 
179
- Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space or vertical bar ('|'). To allow a wider range of short-ish flags than just
180
- single characters, you may also have two long options. Examples:
178
+ Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma, a space, or a vertical bar (`|`). To allow a wider range of short-ish flags than just single characters, you may also have two long options.
181
179
 
182
180
  ```js
183
181
  program
@@ -188,9 +186,9 @@ program
188
186
 
189
187
  The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler.
190
188
 
191
- Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.
189
+ Multi-word options like `--template-engine` are normalized to camelCase option names, resulting in properties such as `program.opts().templateEngine`.
192
190
 
193
- An option and its option-argument can be separated by a space, or combined into the same argument. The option-argument can follow the short option directly or follow an `=` for a long option.
191
+ An option and its option-argument can be separated by a space, or combined into the same argument. The option-argument can follow the short option directly, or follow an `=` for a long option.
194
192
 
195
193
  ```sh
196
194
  serve -p 80
@@ -245,7 +243,7 @@ pizza details:
245
243
  ```
246
244
 
247
245
  Multiple boolean short options may be combined following the dash, and may be followed by a single short option taking a value.
248
- For example `-d -s -p cheese` may be written as `-ds -p cheese` or even `-dsp cheese`.
246
+ For example, `-d -s -p cheese` may be written as `-ds -p cheese` or even `-dsp cheese`.
249
247
 
250
248
  Options with an expected option-argument are greedy and will consume the following argument whatever the value.
251
249
  So `--id -xyz` reads `-xyz` as the option-argument.
@@ -276,11 +274,8 @@ cheese: stilton
276
274
 
277
275
  ### Other option types, negatable boolean and boolean|value
278
276
 
279
- You can define a boolean option long name with a leading `no-` to set the option value to false when used.
280
- Defined alone this also makes the option true by default.
281
-
282
- If you define `--foo` first, adding `--no-foo` does not change the default value from what it would
283
- otherwise be.
277
+ You can define a boolean option long name with a leading `no-` to set the option value to `false` when used.
278
+ Defined alone without a matching positive option, this also makes the option `true` by default.
284
279
 
285
280
  Example file: [options-negatable.js](./examples/options-negatable.js)
286
281
 
@@ -309,7 +304,7 @@ You ordered a pizza with no sauce and no cheese
309
304
  ```
310
305
 
311
306
  You can specify an option which may be used as a boolean option but may optionally take an option-argument
312
- (declared with square brackets like `--optional [value]`).
307
+ (declared with square brackets, like `--optional [value]`).
313
308
 
314
309
  Example file: [options-boolean-or-value.js](./examples/options-boolean-or-value.js)
315
310
 
@@ -342,7 +337,9 @@ For information about possible ambiguous cases, see [options taking varying argu
342
337
 
343
338
  ### Required option
344
339
 
345
- You may specify a required (mandatory) option using `.requiredOption()`. The option must have a value after parsing, usually specified on the command line, or perhaps from a default value (say from environment). The method is otherwise the same as `.option()` in format, taking flags and description, and optional default value or custom processing.
340
+ You may specify a required (mandatory) option using `.requiredOption()`. The option must have a value after parsing, usually specified on the command line, or perhaps from a default value (e.g., from environment).
341
+
342
+ The method is otherwise the same as `.option()` in format, taking flags and description, and optional default value or custom processing.
346
343
 
347
344
  Example file: [options-required.js](./examples/options-required.js)
348
345
 
@@ -363,7 +360,7 @@ error: required option '-c, --cheese <type>' not specified
363
360
  You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you
364
361
  can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments
365
362
  are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value
366
- is specified in the same argument as the option then no further values are read.
363
+ is specified in the same argument as the option, then no further values are read.
367
364
 
368
365
  Example file: [options-variadic.js](./examples/options-variadic.js)
369
366
 
@@ -394,7 +391,7 @@ For information about possible ambiguous cases, see [options taking varying argu
394
391
 
395
392
  ### Version option
396
393
 
397
- The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits.
394
+ The optional `.version()` method adds handling for displaying the command version. The default option flags are `-V` and `--version`. When used, the command prints the version number and exits.
398
395
 
399
396
  ```js
400
397
  program.version('0.0.1');
@@ -405,8 +402,8 @@ $ ./examples/pizza -V
405
402
  0.0.1
406
403
  ```
407
404
 
408
- You may change the flags and description by passing additional parameters to the `version` method, using
409
- the same syntax for flags as the `option` method.
405
+ You may change the flags and description by passing additional parameters to the `.version()` method, using
406
+ the same syntax for flags as the `.option()` method.
410
407
 
411
408
  ```js
412
409
  program.version('0.0.1', '-v, --vers', 'output the current version');
@@ -453,7 +450,7 @@ $ extra --disable-server --port 8000
453
450
  error: option '--disable-server' cannot be used with option '-p, --port <number>'
454
451
  ```
455
452
 
456
- Specify a required (mandatory) option using the `Option` method `.makeOptionMandatory()`. This matches the `Command` method [.requiredOption()](#required-option).
453
+ Specify a required (mandatory) option using the `Option` method `.makeOptionMandatory()`. This matches the `Command` method [`.requiredOption()`](#required-option).
457
454
 
458
455
  ### Custom option processing
459
456
 
@@ -521,7 +518,9 @@ $ custom --list x,y,z
521
518
 
522
519
  ## Commands
523
520
 
524
- You can specify (sub)commands using `.command()` or `.addCommand()`. There are two ways these can be implemented: using an action handler attached to the command, or as a stand-alone executable file (described in more detail later). The subcommands may be nested ([example](./examples/nestedCommands.js)).
521
+ You can specify (sub)commands using `.command()` or `.addCommand()`. There are two ways these can be implemented: using an `.action()` handler attached to the command; or as a stand-alone executable file. (More detail about this later.)
522
+
523
+ Subcommands may be nested. Example file: [nestedCommands.js](./examples/nestedCommands.js).
525
524
 
526
525
  In the first parameter to `.command()` you specify the command name. You may append the command-arguments after the command name, or specify them separately using `.argument()`. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`.
527
526
 
@@ -553,21 +552,20 @@ program
553
552
 
554
553
  Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will
555
554
  remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other
556
- subcommand is specified ([example](./examples/defaultCommand.js)).
555
+ subcommand is specified. (Example file: [defaultCommand.js](./examples/defaultCommand.js).)
557
556
 
558
- You can add alternative names for a command with `.alias()`. ([example](./examples/alias.js))
557
+ You can add alternative names for a command with `.alias()`. (Example file: [alias.cjs](./examples/alias.cjs).)
559
558
 
560
- `.command()` automatically copies the inherited settings from the parent command to the newly created subcommand. This is only done during creation, any later setting changes to the parent are not inherited.
559
+ `.command()` automatically copies the inherited settings from the parent command to the newly created subcommand. This is only done during creation; any later setting changes to the parent are not inherited.
561
560
 
562
561
  For safety, `.addCommand()` does not automatically copy the inherited settings from the parent command. There is a helper routine `.copyInheritedSettings()` for copying the settings when they are wanted.
563
562
 
564
563
  ### Command-arguments
565
564
 
566
565
  For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This
567
- is the only method usable for subcommands implemented using a stand-alone executable, but for other subcommands
568
- you can instead use the following method.
566
+ is the only method usable for subcommands implemented using a stand-alone executable.
569
567
 
570
- To configure a command, you can use `.argument()` to specify each expected command-argument.
568
+ Alternatively, you can instead use the following method. To configure a command, you can use `.argument()` to specify each expected command-argument.
571
569
  You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.
572
570
  You can specify a default value for an optional command-argument.
573
571
 
@@ -584,8 +582,10 @@ program
584
582
  });
585
583
  ```
586
584
 
587
- The last argument of a command can be variadic, and only the last argument. To make an argument variadic you
588
- append `...` to the argument name. A variadic argument is passed to the action handler as an array. For example:
585
+ The last argument of a command can be variadic, and _only_ the last argument. To make an argument variadic, simply
586
+ append `...` to the argument name.
587
+
588
+ A variadic argument is passed to the action handler as an array.
589
589
 
590
590
  ```js
591
591
  program
@@ -662,7 +662,7 @@ program
662
662
  });
663
663
  ```
664
664
 
665
- If you prefer, you can work with the command directly and skip declaring the parameters for the action handler. The `this` keyword is set to the running command and can be used from a function expression (but not from an arrow function).
665
+ If you prefer, you can work with the command directly and skip declaring the parameters for the action handler. If you use a function expression (but not an arrow function), the `this` keyword is set to the running command.
666
666
 
667
667
  Example file: [action-this.js](./examples/action-this.js)
668
668
 
@@ -676,7 +676,7 @@ program
676
676
  });
677
677
  ```
678
678
 
679
- You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`.
679
+ You may supply an `async` action handler, in which case you call `.parseAsync()` rather than `.parse()`.
680
680
 
681
681
  ```js
682
682
  async function run() { /* code goes here */ }
@@ -689,12 +689,14 @@ async function main() {
689
689
  }
690
690
  ```
691
691
 
692
- A command's options and arguments on the command line are validated when the command is used. Any unknown options or missing arguments or excess arguments will be reported as an error. You can suppress the unknown option check with `.allowUnknownOption()`. You can suppress the excess arguments check with `.allowExcessArguments()`.
692
+ A command's options and arguments on the command line are validated when the command is used. Any unknown options, missing arguments, or excess arguments will be reported as an error.
693
+
694
+ You can suppress the unknown option check with `.allowUnknownOption()`. You can suppress the excess arguments check with `.allowExcessArguments()`.
693
695
 
694
696
  ### Stand-alone executable (sub)commands
695
697
 
696
698
  When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands.
697
- Commander will search the files in the directory of the entry script for a file with the name combination `command-subcommand`, like `pm-install` or `pm-search` in the example below. The search includes trying common file extensions, like `.js`.
699
+ Commander will search the files in the directory of the entry script for a file with the name combination `command-subcommand` (like `pm-install` or `pm-search` in the example below). The search includes trying common file extensions, like `.js`.
698
700
  You may specify a custom name (and path) with the `executableFile` configuration option.
699
701
  You may specify a custom search directory for subcommands with `.executableDir()`.
700
702
 
@@ -734,7 +736,7 @@ program
734
736
  });
735
737
  ```
736
738
 
737
- The callback hook can be `async`, in which case you call `.parseAsync` rather than `.parse`. You can add multiple hooks per event.
739
+ The callback hook can be `async`, in which case you call `.parseAsync()` rather than `.parse()`. You can add multiple hooks per event.
738
740
 
739
741
  The supported events are:
740
742
 
@@ -743,7 +745,7 @@ The supported events are:
743
745
  | `preAction`, `postAction` | before/after action handler for this command and its nested subcommands | `(thisCommand, actionCommand)` |
744
746
  | `preSubcommand` | before parsing direct subcommand | `(thisCommand, subcommand)` |
745
747
 
746
- For an overview of the life cycle events see [parsing life cycle and hooks](./docs/parsing-and-hooks.md).
748
+ For an overview of the life cycle events, see [parsing life cycle and hooks](./docs/parsing-and-hooks.md).
747
749
 
748
750
  ## Automated help
749
751
 
@@ -818,8 +820,8 @@ The positions "beforeAll" and "afterAll" apply to the command and all its subcom
818
820
 
819
821
  The second parameter can be a string, or a function returning a string. The function is passed a context object for your convenience. The properties are:
820
822
 
821
- - error: a boolean for whether the help is being displayed due to a usage error
822
- - command: the Command which is displaying the help
823
+ - `error`: a boolean for whether the help is being displayed due to a usage error
824
+ - `command`: the `Command` which is displaying the help
823
825
 
824
826
  ### Display help after errors
825
827
 
@@ -863,7 +865,7 @@ error: unknown option '--hepl'
863
865
 
864
866
  The command name appears in the help, and is also used for locating stand-alone executable subcommands.
865
867
 
866
- You may specify the program name using `.name()` or in the Command constructor. For the program, Commander will
868
+ You may specify the program name using `.name()` or in the `Command` constructor. For the program, Commander will
867
869
  fall back to using the script name from the full arguments passed into `.parse()`. However, the script name varies
868
870
  depending on how your program is launched, so you may wish to specify it explicitly.
869
871
 
@@ -873,7 +875,7 @@ const pm = new Command('pm');
873
875
  ```
874
876
 
875
877
  Subcommands get a name when specified using `.command()`. If you create the subcommand yourself to use with `.addCommand()`,
876
- then set the name using `.name()` or in the Command constructor.
878
+ then set the name using `.name()` or in the `Command` constructor.
877
879
 
878
880
  ### .usage
879
881
 
@@ -907,18 +909,18 @@ This may require additional disk space.
907
909
 
908
910
  ### .helpOption(flags, description)
909
911
 
910
- By default, every command has a help option. You may change the default help flags and description. Pass false to disable the built-in help option.
912
+ By default, every command has a help option. You may change the default help flags and description. Pass `false` to disable the built-in help option.
911
913
 
912
914
  ```js
913
915
  program
914
916
  .helpOption('-e, --HELP', 'read more information');
915
917
  ```
916
918
 
917
- (Or use `.addHelpOption()` to add an option you construct yourself.)
919
+ Alternatively, use `.addHelpOption()` to add an option you construct yourself.
918
920
 
919
921
  ### .helpCommand()
920
922
 
921
- A help command is added by default if your command has subcommands. You can explicitly turn on or off the implicit help command with `.helpCommand(true)` and `.helpCommand(false)`.
923
+ A help command is added by default if your command has subcommands. You can explicitly turn the implicit help command on or off with `.helpCommand(true)` and `.helpCommand(false)`.
922
924
 
923
925
  You can both turn on and customise the help command by supplying the name and description:
924
926
 
@@ -926,28 +928,30 @@ You can both turn on and customise the help command by supplying the name and de
926
928
  program.helpCommand('assist [command]', 'show assistance');
927
929
  ```
928
930
 
929
- (Or use `.addHelpCommand()` to add a command you construct yourself.)
931
+ Alternatively, use `.addHelpCommand()` to add a command you construct yourself.
930
932
 
931
933
  ### Help Groups
932
934
 
933
935
  The help by default lists options under the the heading `Options:` and commands under `Commands:`. You can create your own groups
934
- with different headings. The high-level way is to set the desired group heading while adding the options and commands,
935
- using `.optionsGroup()` and `.commandsGroup()`. The low-level way is using `.helpGroup()` on an individual `Option` or `Command`
936
+ with different headings.
937
+
938
+ - The high-level way is to set the desired group heading while adding the options and commands, using `.optionsGroup()` and `.commandsGroup()`.
939
+ - The low-level way is using `.helpGroup()` on an individual `Option` or `Command`.
936
940
 
937
941
  Example file: [help-groups.js](./examples/help-groups.js)
938
942
 
939
943
  ### More configuration
940
944
 
941
- The built-in help is formatted using the Help class.
942
- You can configure the help by modifying data properties and methods using `.configureHelp()`, or by subclassing Help using `.createHelp()` .
945
+ The built-in help is formatted using the `Help` class.
946
+ You can configure the help by modifying data properties and methods using `.configureHelp()`, or by subclassing `Help` using `.createHelp()` .
943
947
 
944
- Simple properties include `sortSubcommands`, `sortOptions`, and `showGlobalOptions`. You can add color using the style methods like `styleTitle()`.
948
+ Simple properties include `sortSubcommands`, `sortOptions`, and `showGlobalOptions`. You can add color using the style methods like `.styleTitle()`.
945
949
 
946
- For more detail and examples of changing the displayed text, color, and layout see [help in depth](./docs/help-in-depth.md).
950
+ For more detail and examples of changing the displayed text, color, and layout, see: [Help in Depth](./docs/help-in-depth.md).
947
951
 
948
952
  ## Custom event listeners
949
953
 
950
- You can execute custom actions by listening to command and option events.
954
+ You can execute custom actions by listening to `command` and `option` events.
951
955
 
952
956
  ```js
953
957
  program.on('option:verbose', function () {
@@ -961,7 +965,7 @@ program.on('option:verbose', function () {
961
965
 
962
966
  Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
963
967
 
964
- Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
968
+ Or, call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
965
969
 
966
970
  - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
967
971
  - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
@@ -975,7 +979,7 @@ program.parse(process.argv); // assume argv[0] is app and argv[1] is script
975
979
  program.parse(['--port', '80'], { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
976
980
  ```
977
981
 
978
- Use parseAsync instead of parse if any of your action handlers are async.
982
+ Use `.parseAsync()` instead of `.parse()` if any of your action handlers are async.
979
983
 
980
984
  ### Parsing Configuration
981
985
 
@@ -1010,13 +1014,15 @@ program arg --port=80
1010
1014
  By default, the option processing shows an error for an unknown option. To have an unknown option treated as an ordinary command-argument and continue looking for options, use `.allowUnknownOption()`. This lets you mix known and unknown options.
1011
1015
 
1012
1016
  By default, the argument processing displays an error for more command-arguments than expected.
1013
- To suppress the error for excess arguments, use`.allowExcessArguments()`.
1017
+ To suppress the error for excess arguments, use `.allowExcessArguments()`.
1014
1018
 
1015
1019
  ### Legacy options as properties
1016
1020
 
1017
1021
  Before Commander 7, the option values were stored as properties on the command.
1018
1022
  This was convenient to code, but the downside was possible clashes with
1019
- existing properties of `Command`. You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`.
1023
+ existing properties of `Command`.
1024
+
1025
+ You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`.
1020
1026
 
1021
1027
  ```js
1022
1028
  program
@@ -1031,15 +1037,15 @@ program
1031
1037
 
1032
1038
  ### TypeScript
1033
1039
 
1034
- extra-typings: There is an optional project to infer extra type information from the option and argument definitions.
1040
+ **extra-typings:** There is an optional project to infer extra type information from the option and argument definitions.
1035
1041
  This adds strong typing to the options returned by `.opts()` and the parameters to `.action()`.
1036
- See [commander-js/extra-typings](https://github.com/commander-js/extra-typings) for more.
1042
+ For more, see the repo: [commander-js/extra-typings](https://github.com/commander-js/extra-typings).
1037
1043
 
1038
- ```
1044
+ ```ts
1039
1045
  import { Command } from '@commander-js/extra-typings';
1040
1046
  ```
1041
1047
 
1042
- ts-node: If you use `ts-node` and stand-alone executable subcommands written as `.ts` files, you need to call your program through node to get the subcommands called correctly. e.g.
1048
+ **ts-node:** If you use `ts-node` and stand-alone executable subcommands written as `.ts` files, you need to call your program through node to get the subcommands called correctly, e.g.:
1043
1049
 
1044
1050
  ```sh
1045
1051
  node -r ts-node/register pm.ts
@@ -1050,19 +1056,19 @@ node -r ts-node/register pm.ts
1050
1056
  This factory function creates a new command. It is exported and may be used instead of using `new`, like:
1051
1057
 
1052
1058
  ```js
1053
- const { createCommand } = require('commander');
1059
+ import { createCommand } from 'commander';
1054
1060
  const program = createCommand();
1055
1061
  ```
1056
1062
 
1057
- `createCommand` is also a method of the Command object, and creates a new command rather than a subcommand. This gets used internally
1063
+ `createCommand()` is also a method of the `Command` object, and creates a new command rather than a subcommand. This gets used internally
1058
1064
  when creating subcommands using `.command()`, and you may override it to
1059
- customise the new subcommand (example file [custom-command-class.js](./examples/custom-command-class.js)).
1065
+ customise the new subcommand. Example file: [custom-command-class.js](./examples/custom-command-class.js).
1060
1066
 
1061
1067
  ### Node options such as `--harmony`
1062
1068
 
1063
1069
  You can enable `--harmony` option in two ways:
1064
1070
 
1065
- - Use `#! /usr/bin/env node --harmony` in the subcommands scripts. (Note Windows does not support this pattern.)
1071
+ - Use `#! /usr/bin/env node --harmony` in the subcommands scripts. (Note: Windows does not support this pattern.)
1066
1072
  - Use the `--harmony` option when calling the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning subcommand processes.
1067
1073
 
1068
1074
  ### Debugging stand-alone executable subcommands
@@ -1072,14 +1078,14 @@ An executable subcommand is launched as a separate child process.
1072
1078
  If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) executable subcommands using `node --inspect` et al.,
1073
1079
  the inspector port is incremented by 1 for the spawned subcommand.
1074
1080
 
1075
- If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your launch.json configuration.
1081
+ If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your `launch.json` configuration.
1076
1082
 
1077
1083
  ### npm run-script
1078
1084
 
1079
- By default, when you call your program using run-script, `npm` will parse any options on the command-line and they will not reach your program. Use
1085
+ By default, when you call your program using `run-script`, `npm` will parse any options on the command-line and they will not reach your program. Use
1080
1086
  `--` to stop the npm option parsing and pass through all the arguments.
1081
1087
 
1082
- The synopsis for [npm run-script](https://docs.npmjs.com/cli/v9/commands/npm-run-script) explicitly shows the `--` for this reason:
1088
+ The synopsis for [`npm run-script`](https://docs.npmjs.com/cli/v9/commands/npm-run-script) explicitly shows the `--` for this reason:
1083
1089
 
1084
1090
  ```console
1085
1091
  npm run-script <command> [-- <args>]
@@ -1089,7 +1095,7 @@ npm run-script <command> [-- <args>]
1089
1095
 
1090
1096
  This routine is available to invoke the Commander error handling for your own error conditions. (See also the next section about exit handling.)
1091
1097
 
1092
- As well as the error message, you can optionally specify the `exitCode` (used with `process.exit`)
1098
+ As well as the error message, you can optionally specify the `exitCode` (used with `process.exit()`)
1093
1099
  and `code` (used with `CommanderError`).
1094
1100
 
1095
1101
  ```js
@@ -1099,12 +1105,16 @@ program.error('Custom processing has failed', { exitCode: 2, code: 'my.custom.er
1099
1105
 
1100
1106
  ### Override exit and output handling
1101
1107
 
1102
- By default, Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override
1108
+ By default, Commander calls `process.exit()` when it detects errors, or after displaying the help or version. You can override
1103
1109
  this behaviour and optionally supply a callback. The default override throws a `CommanderError`.
1104
1110
 
1105
- The override callback is passed a `CommanderError` with properties `exitCode` number, `code` string, and `message`.
1106
- Commander expects the callback to terminate the normal program flow, and will call `process.exit` if the callback returns.
1107
- The normal display of error messages or version or help is not affected by the override which is called after the display.
1111
+ The override callback is passed a `CommanderError` with the properties:
1112
+ - `exitCode`: number
1113
+ - `code`: string
1114
+ - `message`: string
1115
+
1116
+ Commander expects the callback to terminate the normal program flow, and will call `process.exit()` if the callback returns.
1117
+ The normal display of error messages or version or help is not affected by the override, which is called after the display.
1108
1118
 
1109
1119
  ```js
1110
1120
  program.exitOverride();
@@ -1142,13 +1152,16 @@ program
1142
1152
  There is more information available about:
1143
1153
 
1144
1154
  - [deprecated](./docs/deprecated.md) features still supported for backwards compatibility
1155
+ - [Help in Depth](./docs/help-in-depth.md) configuring help output
1145
1156
  - [options taking varying arguments](./docs/options-in-depth.md)
1146
1157
  - [parsing life cycle and hooks](./docs/parsing-and-hooks.md)
1158
+ - [Release Policy](./docs/release-policy.md)
1147
1159
 
1148
1160
  ## Support
1149
1161
 
1150
- The current version of Commander is fully supported on Long Term Support versions of Node.js, and requires at least v20.
1151
- (For older versions of Node.js, use an older version of Commander.)
1162
+ The current version of Commander is fully supported on Long Term Support versions of Node.js, and requires at least v22.12.0.
1163
+
1164
+ Older major versions of Commander receive security updates for 12 months. For more see: [Release Policy](./docs/release-policy.md).
1152
1165
 
1153
1166
  The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub.
1154
1167
 
package/index.js CHANGED
@@ -1,24 +1,21 @@
1
- const { Argument } = require('./lib/argument.js');
2
- const { Command } = require('./lib/command.js');
3
- const { CommanderError, InvalidArgumentError } = require('./lib/error.js');
4
- const { Help } = require('./lib/help.js');
5
- const { Option } = require('./lib/option.js');
1
+ import { Argument } from './lib/argument.js';
2
+ import { Command } from './lib/command.js';
3
+ import { CommanderError, InvalidArgumentError } from './lib/error.js';
4
+ import { Help } from './lib/help.js';
5
+ import { Option } from './lib/option.js';
6
6
 
7
- exports.program = new Command();
7
+ export const program = new Command();
8
8
 
9
- exports.createCommand = (name) => new Command(name);
10
- exports.createOption = (flags, description) => new Option(flags, description);
11
- exports.createArgument = (name, description) => new Argument(name, description);
9
+ export const createCommand = (name) => new Command(name);
10
+ export const createOption = (flags, description) =>
11
+ new Option(flags, description);
12
+ export const createArgument = (name, description) =>
13
+ new Argument(name, description);
12
14
 
13
15
  /**
14
16
  * Expose classes
15
17
  */
16
18
 
17
- exports.Command = Command;
18
- exports.Option = Option;
19
- exports.Argument = Argument;
20
- exports.Help = Help;
21
-
22
- exports.CommanderError = CommanderError;
23
- exports.InvalidArgumentError = InvalidArgumentError;
24
- exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated
19
+ export { Command, Option, Argument, Help };
20
+ export { CommanderError, InvalidArgumentError };
21
+ export { InvalidArgumentError as InvalidOptionArgumentError }; // Deprecated
package/lib/argument.js CHANGED
@@ -1,6 +1,6 @@
1
- const { InvalidArgumentError } = require('./error.js');
1
+ import { InvalidArgumentError } from './error.js';
2
2
 
3
- class Argument {
3
+ export class Argument {
4
4
  /**
5
5
  * Initialize a new command argument with the given name and description.
6
6
  * The default is that the argument is required, and you can explicitly
@@ -140,11 +140,8 @@ class Argument {
140
140
  * @private
141
141
  */
142
142
 
143
- function humanReadableArgName(arg) {
143
+ export function humanReadableArgName(arg) {
144
144
  const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');
145
145
 
146
146
  return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';
147
147
  }
148
-
149
- exports.Argument = Argument;
150
- exports.humanReadableArgName = humanReadableArgName;
package/lib/command.js CHANGED
@@ -1,16 +1,16 @@
1
- const EventEmitter = require('node:events').EventEmitter;
2
- const childProcess = require('node:child_process');
3
- const path = require('node:path');
4
- const fs = require('node:fs');
5
- const process = require('node:process');
1
+ import { EventEmitter } from 'node:events';
2
+ import childProcess from 'node:child_process';
3
+ import path from 'node:path';
4
+ import fs from 'node:fs';
5
+ import process from 'node:process';
6
6
 
7
- const { Argument, humanReadableArgName } = require('./argument.js');
8
- const { CommanderError } = require('./error.js');
9
- const { Help, stripColor } = require('./help.js');
10
- const { Option, DualOptions } = require('./option.js');
11
- const { suggestSimilar } = require('./suggestSimilar');
7
+ import { Argument, humanReadableArgName } from './argument.js';
8
+ import { CommanderError } from './error.js';
9
+ import { Help, stripColor } from './help.js';
10
+ import { Option, DualOptions } from './option.js';
11
+ import { suggestSimilar } from './suggestSimilar.js';
12
12
 
13
- class Command extends EventEmitter {
13
+ export class Command extends EventEmitter {
14
14
  /**
15
15
  * Initialize a new `Command`.
16
16
  *
@@ -674,17 +674,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
674
674
  const name = option.attributeName();
675
675
 
676
676
  // store default value
677
- if (option.negate) {
678
- // --no-foo is special and defaults foo to true, unless a --foo option is already defined
679
- const positiveLongFlag = option.long.replace(/^--no-/, '--');
680
- if (!this._findOption(positiveLongFlag)) {
681
- this.setOptionValueWithSource(
682
- name,
683
- option.defaultValue === undefined ? true : option.defaultValue,
684
- 'default',
685
- );
686
- }
687
- } else if (option.defaultValue !== undefined) {
677
+ if (option.defaultValue !== undefined) {
688
678
  this.setOptionValueWithSource(name, option.defaultValue, 'default');
689
679
  }
690
680
 
@@ -1125,7 +1115,29 @@ Expecting one of '${allowedValues.join("', '")}'`);
1125
1115
  }
1126
1116
 
1127
1117
  _prepareForParse() {
1118
+ // Save the state the first time, then restore the state before each subsequent parse.
1128
1119
  if (this._savedState === null) {
1120
+ // Do the special default of lone negated option to true, now that we have all the options.
1121
+ // Filter for negated options that have not been processed already.
1122
+ this.options
1123
+ .filter(
1124
+ (option) =>
1125
+ option.negate &&
1126
+ option.defaultValue === undefined &&
1127
+ this.getOptionValue(option.attributeName()) === undefined,
1128
+ )
1129
+ .forEach((option) => {
1130
+ // check for lone negated option: --no-foo without a --foo option
1131
+ const positiveLongFlag = option.long.replace(/^--no-/, '--');
1132
+ if (!this._findOption(positiveLongFlag)) {
1133
+ this.setOptionValueWithSource(
1134
+ option.attributeName(),
1135
+ true,
1136
+ 'default',
1137
+ );
1138
+ }
1139
+ });
1140
+
1129
1141
  this.saveStateBeforeParse();
1130
1142
  } else {
1131
1143
  this.restoreStateBeforeParse();
@@ -2148,8 +2160,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
2148
2160
 
2149
2161
  const expected = this.registeredArguments.length;
2150
2162
  const s = expected === 1 ? '' : 's';
2163
+ const received = receivedArgs.length;
2151
2164
  const forSubcommand = this.parent ? ` for '${this.name()}'` : '';
2152
- const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2165
+ const details = receivedArgs.join(', ');
2166
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;
2153
2167
  this.error(message, { code: 'commander.excessArguments' });
2154
2168
  }
2155
2169
 
@@ -2405,12 +2419,12 @@ Expecting one of '${allowedValues.join("', '")}'`);
2405
2419
 
2406
2420
  /**
2407
2421
  * Set the name of the command from script filename, such as process.argv[1],
2408
- * or require.main.filename, or __filename.
2422
+ * or import.meta.filename.
2409
2423
  *
2410
2424
  * (Used internally and public although not documented in README.)
2411
2425
  *
2412
2426
  * @example
2413
- * program.nameFromFilename(require.main.filename);
2427
+ * program.nameFromFilename(import.meta.filename);
2414
2428
  *
2415
2429
  * @param {string} filename
2416
2430
  * @return {Command}
@@ -2426,7 +2440,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2426
2440
  * Get or set the directory for searching for executable subcommands of this command.
2427
2441
  *
2428
2442
  * @example
2429
- * program.executableDir(__dirname);
2443
+ * program.executableDir(import.meta.dirname);
2430
2444
  * // or
2431
2445
  * program.executableDir('subcommands');
2432
2446
  *
@@ -2746,10 +2760,12 @@ function incrementNodeInspectorPort(args) {
2746
2760
  }
2747
2761
 
2748
2762
  /**
2763
+ * Exported for using from tests, not otherwise used outside this file.
2764
+ *
2749
2765
  * @returns {boolean | undefined}
2750
2766
  * @package
2751
2767
  */
2752
- function useColor() {
2768
+ export function useColor() {
2753
2769
  // Test for common conventions.
2754
2770
  // NB: the observed behaviour is in combination with how author adds color! For example:
2755
2771
  // - we do not test NODE_DISABLE_COLORS, but util:styletext does
@@ -2772,6 +2788,3 @@ function useColor() {
2772
2788
  return true;
2773
2789
  return undefined;
2774
2790
  }
2775
-
2776
- exports.Command = Command;
2777
- exports.useColor = useColor; // exporting for tests
package/lib/error.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * CommanderError class
3
3
  */
4
- class CommanderError extends Error {
4
+ export class CommanderError extends Error {
5
5
  /**
6
6
  * Constructs the CommanderError class
7
7
  * @param {number} exitCode suggested exit code which could be used with process.exit
@@ -22,7 +22,7 @@ class CommanderError extends Error {
22
22
  /**
23
23
  * InvalidArgumentError class
24
24
  */
25
- class InvalidArgumentError extends CommanderError {
25
+ export class InvalidArgumentError extends CommanderError {
26
26
  /**
27
27
  * Constructs the InvalidArgumentError class
28
28
  * @param {string} [message] explanation of why argument is invalid
@@ -34,6 +34,3 @@ class InvalidArgumentError extends CommanderError {
34
34
  this.name = this.constructor.name;
35
35
  }
36
36
  }
37
-
38
- exports.CommanderError = CommanderError;
39
- exports.InvalidArgumentError = InvalidArgumentError;
package/lib/help.js CHANGED
@@ -1,4 +1,4 @@
1
- const { humanReadableArgName } = require('./argument.js');
1
+ import { humanReadableArgName } from './argument.js';
2
2
 
3
3
  /**
4
4
  * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
@@ -9,7 +9,7 @@ const { humanReadableArgName } = require('./argument.js');
9
9
  */
10
10
 
11
11
  // Although this is a class, methods are static in style to allow override using subclass or just functions.
12
- class Help {
12
+ export class Help {
13
13
  constructor() {
14
14
  this.helpWidth = undefined;
15
15
  this.minWidthToWrap = 40;
@@ -737,11 +737,8 @@ class Help {
737
737
  * @package
738
738
  */
739
739
 
740
- function stripColor(str) {
740
+ export function stripColor(str) {
741
741
  // eslint-disable-next-line no-control-regex
742
742
  const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
743
743
  return str.replace(sgrPattern, '');
744
744
  }
745
-
746
- exports.Help = Help;
747
- exports.stripColor = stripColor;
package/lib/option.js CHANGED
@@ -1,6 +1,6 @@
1
- const { InvalidArgumentError } = require('./error.js');
1
+ import { InvalidArgumentError } from './error.js';
2
2
 
3
- class Option {
3
+ export class Option {
4
4
  /**
5
5
  * Initialize a new `Option` with the given `flags` and `description`.
6
6
  *
@@ -265,7 +265,7 @@ class Option {
265
265
  * use cases, but is tricky for others where we want separate behaviours despite
266
266
  * the single shared option value.
267
267
  */
268
- class DualOptions {
268
+ export class DualOptions {
269
269
  /**
270
270
  * @param {Option[]} options
271
271
  */
@@ -375,6 +375,3 @@ function splitOptionFlags(flags) {
375
375
 
376
376
  return { shortFlag, longFlag };
377
377
  }
378
-
379
- exports.Option = Option;
380
- exports.DualOptions = DualOptions;
@@ -53,7 +53,7 @@ function editDistance(a, b) {
53
53
  * @returns {string}
54
54
  */
55
55
 
56
- function suggestSimilar(word, candidates) {
56
+ export function suggestSimilar(word, candidates) {
57
57
  if (!candidates || candidates.length === 0) return '';
58
58
  // remove possible duplicates
59
59
  candidates = Array.from(new Set(candidates));
@@ -97,5 +97,3 @@ function suggestSimilar(word, candidates) {
97
97
  }
98
98
  return '';
99
99
  }
100
-
101
- exports.suggestSimilar = suggestSimilar;
@@ -9,7 +9,10 @@
9
9
  "type": "time-permitting"
10
10
  },
11
11
  "backing": {
12
- "npm-funding": true
12
+ "donations": [
13
+ "https://github.com/sponsors/abetomo",
14
+ "https://github.com/sponsors/shadowspawn"
15
+ ]
13
16
  }
14
17
  }
15
18
  ]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "commander",
3
- "version": "14.0.2",
3
+ "version": "15.0.0-0",
4
4
  "description": "the complete solution for node.js command-line programs",
5
5
  "keywords": [
6
6
  "commander",
@@ -28,55 +28,37 @@
28
28
  "fix": "npm run fix:lint && npm run fix:format",
29
29
  "fix:format": "prettier --write .",
30
30
  "fix:lint": "eslint --fix .",
31
- "test": "jest && npm run check:type:ts",
32
- "test-all": "jest && npm run test-esm && npm run check",
33
- "test-esm": "node ./tests/esm-imports-test.mjs"
31
+ "test": "node --test && npm run check:type:ts",
32
+ "test-all": "node --test && npm run check"
34
33
  },
35
34
  "files": [
36
35
  "index.js",
37
36
  "lib/*.js",
38
- "esm.mjs",
39
37
  "typings/index.d.ts",
40
- "typings/esm.d.mts",
41
38
  "package-support.json"
42
39
  ],
43
- "type": "commonjs",
40
+ "type": "module",
44
41
  "main": "./index.js",
45
42
  "exports": {
46
43
  ".": {
47
- "require": {
48
- "types": "./typings/index.d.ts",
49
- "default": "./index.js"
50
- },
51
- "import": {
52
- "types": "./typings/esm.d.mts",
53
- "default": "./esm.mjs"
54
- },
44
+ "types": "./typings/index.d.ts",
55
45
  "default": "./index.js"
56
- },
57
- "./esm.mjs": {
58
- "types": "./typings/esm.d.mts",
59
- "import": "./esm.mjs"
60
46
  }
61
47
  },
62
48
  "devDependencies": {
63
49
  "@eslint/js": "^9.4.0",
64
- "@types/jest": "^30.0.0",
65
50
  "@types/node": "^22.7.4",
66
51
  "eslint": "^9.17.0",
67
52
  "eslint-config-prettier": "^10.0.1",
68
- "eslint-plugin-jest": "^29.0.1",
69
53
  "globals": "^16.0.0",
70
- "jest": "^30.0.3",
71
54
  "prettier": "^3.2.5",
72
- "ts-jest": "^29.0.3",
73
- "tsd": "^0.33.0",
55
+ "tsd": "^0.31.0",
74
56
  "typescript": "^5.0.4",
75
57
  "typescript-eslint": "^8.12.2"
76
58
  },
77
59
  "types": "typings/index.d.ts",
78
60
  "engines": {
79
- "node": ">=20"
61
+ "node": ">=22.12.0"
80
62
  },
81
63
  "support": true
82
64
  }
@@ -958,13 +958,13 @@ export class Command {
958
958
 
959
959
  /**
960
960
  * Set the name of the command from script filename, such as process.argv[1],
961
- * or require.main.filename, or __filename.
961
+ * or import.meta.filename.
962
962
  *
963
963
  * (Used internally and public although not documented in README.)
964
964
  *
965
965
  * @example
966
966
  * ```ts
967
- * program.nameFromFilename(require.main.filename);
967
+ * program.nameFromFilename(import.meta.filename);
968
968
  * ```
969
969
  *
970
970
  * @returns `this` command for chaining
@@ -976,7 +976,7 @@ export class Command {
976
976
  *
977
977
  * @example
978
978
  * ```ts
979
- * program.executableDir(__dirname);
979
+ * program.executableDir(import.meta.dirname);
980
980
  * // or
981
981
  * program.executableDir('subcommands');
982
982
  * ```
package/esm.mjs DELETED
@@ -1,16 +0,0 @@
1
- import commander from './index.js';
2
-
3
- // wrapper to provide named exports for ESM.
4
- export const {
5
- program,
6
- createCommand,
7
- createArgument,
8
- createOption,
9
- CommanderError,
10
- InvalidArgumentError,
11
- InvalidOptionArgumentError, // deprecated old name
12
- Command,
13
- Argument,
14
- Option,
15
- Help,
16
- } = commander;
package/typings/esm.d.mts DELETED
@@ -1,3 +0,0 @@
1
- // Just reexport the types from cjs
2
- // This is a bit indirect. There is not an index.js, but TypeScript will look for index.d.ts for types.
3
- export * from './index.js';