# tj/commander.js # tj/commander.js What this repository is for is not stated in prose this page can quote, so it cannot be established from this repository alone. - **Terms of use** — MIT [package.json:16]. - **Version** — `15.0.0` [package.json:3]. - **Editions** — whether this repository is the whole product or one edition of it cannot be established from this repository alone. - **Running it** — no run path was found in the parsed corpus, so how to start it cannot be established from this repository alone. ## What is in here Each part names what it holds before how much of it there is. The counts are read from the evidence census computed for this snapshot, one per part at most. - **Docs** — no symbol kind this page can name. A file to open: `deprecated.md` [docs/deprecated.md:1]. 117 entities under `docs` [census]. - **Zh CN** — no symbol kind this page can name. 68 entities under `docs/zh-CN` [census]. - **Lib** — classes and functions. A file to open: `argument.js` [lib/argument.js:3]. 10 entities under `lib` [census]. - **.github** — no symbol kind this page can name. A file to open: `PULL_REQUEST_TEMPLATE.md` [.github/PULL_REQUEST_TEMPLATE.md:1]. 4 entities under `.github` [census]. - **Repository root and unclaimed files** — constant and functions. A file to open: `CHANGELOG.md` [CHANGELOG.md:1]. 660 entities in files no part claims [census]. ## What this repository carries One row per capability lane, scoped to where the evidence for it sits. A lane marked as not found means nothing in the parsed corpus matched it — which is a fact about this parse, and the honest place to start looking rather than the end of the question. | Capability | In this repository | Where | |---|---|---| | Database models | not found | — | | HTTP endpoints | not found | — | | Controllers | not found | — | | Configuration | not found | — | | Automated tests | yes | — | | Written documentation | yes | `.github/PULL_REQUEST_TEMPLATE.md`, `CHANGELOG.md` | | Licence | yes | `LICENSE` | ## Where next Five ways in. Each one names pages that exist in this documentation, or says what the repository holds instead. - **Deploying it** — no deployment descriptor and no deployment page were found; how this is deployed cannot be established from this repository alone. - **Understanding the architecture** — [System Overview](system-overview), `Docs`, `Zh CN` and `Lib`. - **Contributing a change** — [Documentation health](documentation-health) and [CONTRIBUTING.md:1]. - **Reviewing security** — no symbol name or path in the parsed corpus matched a security topic, so this page has nothing to hand a reviewer. - **Extending it** — `Docs` and `Zh CN`. ## How this page was assembled Every count above is read from the evidence census computed for this snapshot; every other claim points at a file and a line you can open. The census covers 859 entities and 846 relationships across 5 parts [census], and it passed its own independent recount [census]. # Help **Kind:** Class **Source:** [`lib/help.js`](https://github.com/tj/commander.js/blob/main/lib/help.js#L13) TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS` https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types `Help` prepares command metadata for help output, including visible commands, options, global options, and arguments. It also creates display terms and comparison data so command help can be ordered and aligned consistently. ## Methods | Method | Signature | Returns | |---|---|---| | `prepareContext` | `prepareContext(contextOptions: undefined)` | `void` | | `visibleCommands` | `visibleCommands(cmd: undefined)` | `void` | | `compareOptions` | `compareOptions(a: undefined, b: undefined)` | `void` | | `visibleOptions` | `visibleOptions(cmd: undefined)` | `void` | | `visibleGlobalOptions` | `visibleGlobalOptions(cmd: undefined)` | `void` | | `visibleArguments` | `visibleArguments(cmd: undefined)` | `void` | | `subcommandTerm` | `subcommandTerm(cmd: undefined)` | `void` | | `optionTerm` | `optionTerm(option: undefined)` | `void` | | `argumentTerm` | `argumentTerm(argument: undefined)` | `void` | | `longestSubcommandTermLength` | `longestSubcommandTermLength(cmd: undefined, helper: undefined)` | `void` | | `longestOptionTermLength` | `longestOptionTermLength(cmd: undefined, helper: undefined)` | `void` | | `longestGlobalOptionTermLength` | `longestGlobalOptionTermLength(cmd: undefined, helper: undefined)` | `void` | | `longestArgumentTermLength` | `longestArgumentTermLength(cmd: undefined, helper: undefined)` | `void` | | `commandUsage` | `commandUsage(cmd: undefined)` | `void` | | `commandDescription` | `commandDescription(cmd: undefined)` | `void` | | `subcommandDescription` | `subcommandDescription(cmd: undefined)` | `void` | | `optionDescription` | `optionDescription(option: undefined)` | `void` | | `argumentDescription` | `argumentDescription(argument: undefined)` | `void` | | `formatItemList` | `formatItemList(heading: undefined, items: undefined, helper: undefined)` | `void` | | `groupItems` | `groupItems(unsortedItems: undefined, visibleItems: undefined, getGroup: undefined)` | `void` | | `formatHelp` | `formatHelp(cmd: undefined, helper: undefined)` | `void` | | `displayWidth` | `displayWidth(str: undefined)` | `void` | | `styleTitle` | `styleTitle(str: undefined)` | `void` | | `styleUsage` | `styleUsage(str: undefined)` | `void` | | `styleCommandDescription` | `styleCommandDescription(str: undefined)` | `void` | | `styleOptionDescription` | `styleOptionDescription(str: undefined)` | `void` | | `styleSubcommandDescription` | `styleSubcommandDescription(str: undefined)` | `void` | | `styleArgumentDescription` | `styleArgumentDescription(str: undefined)` | `void` | | `styleDescriptionText` | `styleDescriptionText(str: undefined)` | `void` | | `styleOptionTerm` | `styleOptionTerm(str: undefined)` | `void` | | `styleSubcommandTerm` | `styleSubcommandTerm(str: undefined)` | `void` | | `styleArgumentTerm` | `styleArgumentTerm(str: undefined)` | `void` | | `styleOptionText` | `styleOptionText(str: undefined)` | `void` | | `styleArgumentText` | `styleArgumentText(str: undefined)` | `void` | | `styleSubcommandText` | `styleSubcommandText(str: undefined)` | `void` | | `styleCommandText` | `styleCommandText(str: undefined)` | `void` | | `padWidth` | `padWidth(cmd: undefined, helper: undefined)` | `void` | | `preformatted` | `preformatted(str: undefined)` | `void` | | `formatItem` | `formatItem(term: undefined, termWidth: undefined, description: undefined, helper: undefined)` | `void` | | `boxWrap` | `boxWrap(str: undefined, width: undefined)` | `void` | ## Where it refuses work - `Help` stops the work with an early return when `word === '[options]'`, in 2 places. - `Help` stops the work with an early return when `word[0] === '[' || word[0] === '<'`, in 2 places. - `Help` stops the work with an early return when `!this.showGlobalOptions`. - `Help` stops the work with an early return when `cmd.registeredArguments.find((argument) => argument.description)`. - `Help` stops the work with an early return when `option.description`. - `Help` stops the work with an early return when `argument.description`. ## Diagram ```mermaid graph LR Command[Command definition] --> Help[Help] Help --> Context[Prepared context] Context --> Commands[Visible commands] Context --> Options[Visible options] Context --> Arguments[Visible arguments] Options --> Terms[Option terms] Commands --> Terms Arguments --> Terms Terms --> HelpOutput[Help output] ``` ## Usage ```js import { Command, Help } from 'commander'; const program = new Command() .name('deploy') .description('Deploy an application') .argument('', 'target environment') .option('-d, --dry-run', 'show changes without deploying'); const help = new Help(); help.prepareContext(); const optionTerms = help .visibleOptions(program) .map((option) => help.optionTerm(option)); const argumentTerms = help .visibleArguments(program) .map((argument) => help.argumentTerm(argument)); console.log({ options: optionTerms, arguments: argumentTerms, }); ``` ## AI Coding Instructions - Call `prepareContext()` before reading visible commands, options, or arguments when generating help content. - Use `visibleOptions()`, `visibleGlobalOptions()`, and `visibleCommands()` instead of reading command collections directly so hidden entries are excluded. - Build displayed labels through `subcommandTerm()`, `optionTerm()`, and `argumentTerm()` rather than duplicating formatting logic. - Use `compareOptions()` when sorting option lists to keep help output ordering consistent. - Use `longestSubcommandTermLength()` when calculating padding for aligned subcommand output. ## Relationships - IMPORTS → `humanReadableArgName` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `program` — `index.js`:7 - `Command` — `lib/command.js`:14 # humanReadableArgName **Kind:** Function **Source:** [`lib/argument.js`](https://github.com/tj/commander.js/blob/main/lib/argument.js#L143) Takes an argument and returns its human readable equivalent for help usage. `humanReadableArgName` converts an `Argument` instance into the text shown in command help. It reads the argument name, required state, and variadic state to preserve CLI syntax such as angle brackets, square brackets, and trailing ellipses. ## Signature ```ts function humanReadableArgName(arg) ``` ## Parameters | Name | Type | |---|---| | `arg` | `any` | ## Diagram ```mermaid graph LR A[Argument instance] --> B[name()] A --> C[required and variadic flags] B --> D[humanReadableArgName] C --> D D --> E[Help usage label] ``` ## Usage ```js import { Argument, humanReadableArgName } from './lib/argument.js'; const requiredArgument = new Argument(''); const optionalVariadicArgument = new Argument('[files...]'); console.log(humanReadableArgName(requiredArgument)); // console.log(humanReadableArgName(optionalVariadicArgument)); // [files...] ``` ## AI Coding Instructions - Pass an `Argument` object with `name()`, `required`, and `variadic` values; do not pass a raw string. - Keep output formatting aligned with command syntax: required arguments use `<...>` and optional arguments use `[...]`. - Preserve the `...` suffix for variadic arguments so help output matches parser behavior. - Call this function during help or usage rendering, not during argument parsing or validation. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `Command` — `lib/command.js`:14 - `Help` — `lib/help.js`:13 # program **Kind:** Constant **Source:** [`index.js`](https://github.com/tj/commander.js/blob/main/index.js#L7) ## Definition ```ts new Command() ``` ## Value ```ts new Command() ``` ## Relationships - IMPORTS → `Argument` - IMPORTS → `Command` - IMPORTS → `CommanderError` - IMPORTS → `InvalidArgumentError` - IMPORTS → `Help` - IMPORTS → `Option` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `createTestCommand` — `tests/testHelpers.js`:12 # tj/commander.js ## Overview Auto-generated technical documentation for **tj/commander.js** — 859 entities (829 doc comments, 16 markdown docs, 7 classs, 6 functions). ## Key Components _The most-referenced entities — start here._ - **InvalidArgumentError** (class) — referenced 3× - **Argument** (class) — referenced 2× - **CommanderError** (class) — referenced 2× - **Help** (class) — referenced 2× - **Option** (class) — referenced 2× - **humanReadableArgName** (function) — referenced 2× - **Command** (class) — referenced 1× - **DualOptions** (class) — referenced 1× - **suggestSimilar** (function) — referenced 1× - **program** (constant) — referenced 1× ## How this code is named These conventions cover most of the codebase. Learning them is faster than reading an index — each one lets you find any member of its family without looking it up. | Pattern | Where | Count | Examples | |---|---|---|---| | `create*` | exported symbols | 7 | `createOption`, `createCommand`, `createArgument`, `createCommand()` | # Documentation health 14 symbols have a reference page in this documentation. This page says how each of them came to be described, because "documented" covers four situations a reader should not have to treat alike. ## Where the descriptions come from | | Symbols | What it means for a reader | |---|---:|---| | Written by the author | 7 of 14 | A doc comment in the source. Nothing generated improves on this. | | Generated, with citations | 0 of 14 | Points at specific `file:line` ranges you can open and check. | | Generated, without citations | 3 of 14 | Often right, but nothing anchors it. Treat as a starting point. | | Not described | 4 of 14 | The page shows structure only — signature, members, references. | **7 of 14 descriptions can be checked against source** — 7 because the author wrote them next to the code, 0 because the generator cited the lines it read. The rest are shown, and marked, for what they are. ## Why there is no coverage percentage A percentage counts whether a comment exists, so the cheapest way to raise it is to add empty ones. SonarQube withdrew its comment-density metric over this; studies of "covered" API documentation classify 43–51% of it as carrying no information; and a missing-comment warning has been measured producing 1,774 junk comments in a single codebase. The counts above cannot be moved that way — a doc comment that only restates the symbol name is not counted as one. ## Where the gaps are Undescribed symbols by the part of the system they sit in — worst first, so the next unit of documentation effort has an address. This is the table to bring to planning. | Area | Undescribed | Of | Share | |---|---:|---:|---:| | `index.js` | 4 | 4 | 100% | ## What can be checked A claim on these pages is anchored when it points at something a reader can open: a `file:line` range in the source, or a `[census]` tag naming the arithmetic behind a number. Anything else is prose you would have to take on trust. These counts say which is which. They do not say the anchored claims are right — only that they can be checked. | | Count | What it means | |---|---:|---| | Pages read by this audit | 17 [census] | Every page in the set as it stood before this section was written. This section's own claims are not counted below. | | Pages carrying an anchored claim | 1 of 17 [census] | The page points at source or at a census at least once. | | Anchored claims | 14 [census] | One per `file:line` reference and per census tag. Brackets inside code samples are code, and are not counted. | | … pointing at source | 7 of 14 [census] | A path and a line you can open. | | … pointing at a census | 7 of 14 [census] | A number computed before anything was written. | Whether those citations land in files that exist was NOT CHECKED for this build: the audit was given no way to look a path up. The count above is of citations made, not of citations verified — and reporting them as sound on that basis would be the invention this page exists to catch. Every count in this section and the two below is arithmetic over these pages, redone on each build; `[census]` marks a figure read from that arithmetic rather than written by hand. ## Where the docs and the code disagree One lint reads every page for a single pattern: a sentence stating runtime behaviour — what listens, what validates, what retries — whose only evidence is a prose document. A README saying the server listens on a port is testimony ABOUT the code, not the behaviour itself, and a sentence citing it for the behaviour has quietly turned one into the other. The honest forms either cite the source that listens, or keep the attribution in the sentence. No page states runtime behaviour on the authority of a prose document alone. That is an absence of the pattern rather than proof the pages and the code agree: the lint reads verbs and file extensions, and it misses what it was not taught to see. ## What we have not written yet The evidence census lists, for each part of this repository, the reader-topics that part's contents warrant: a part holding database models owes its readers a data model however few models it holds. This section holds that list against the headings the pages for each part actually carry. 6 of 10 reader-topics, across 5 parts of this repository, have no page carrying a heading that answers for them [census]. | Part | Topics no heading answers for | Pages for this part | |---|---|---:| | `docs` | overview, wiring — no page in this set covers this part at all | 0 [census] | | `docs-zh-cn` | overview, wiring — no page in this set covers this part at all | 0 [census] | | `github` | overview, wiring — no page in this set covers this part at all | 0 [census] | A topic counts as written when any page for its part carries a heading naming it — "Fields" answers for a data model, "Endpoint" for an API surface, "Dependencies" for wiring. The match is deliberately loose in that direction: a topic covered under a heading nobody predicted must not be reported as missing, so the error this makes is silence, never a false accusation of absence. 3 pages name no source path [census], so they were matched to no part and can cover no topic above — the pages about this documentation itself are among them. # Option **Kind:** Class **Source:** [`lib/option.js`](https://github.com/tj/commander.js/blob/main/lib/option.js#L3) `Option` defines a command-line option, including its flags, default value, environment variable mapping, validation rules, and parsing behavior. It is added to a command and supplies metadata used while parsing arguments and building help output. ## Methods | Method | Signature | Returns | |---|---|---| | `default` | `default(value: undefined, description: undefined)` | `void` | | `preset` | `preset(arg: undefined)` | `void` | | `conflicts` | `conflicts(names: undefined)` | `void` | | `implies` | `implies(impliedOptionValues: undefined)` | `void` | | `env` | `env(name: undefined)` | `void` | | `argParser` | `argParser(fn: undefined)` | `void` | | `makeOptionMandatory` | `makeOptionMandatory(mandatory: undefined)` | `void` | | `hideHelp` | `hideHelp(hide: undefined)` | `void` | | `_collectValue` | `_collectValue(value: undefined, previous: undefined)` | `void` | | `choices` | `choices(values: undefined)` | `void` | | `name` | `name()` | `void` | | `attributeName` | `attributeName()` | `void` | | `helpGroup` | `helpGroup(heading: undefined)` | `void` | | `is` | `is(arg: undefined)` | `void` | | `isBoolean` | `isBoolean()` | `void` | ## Where it refuses work - `Option` stops the work with `InvalidArgumentError` when `!this.argChoices.includes(arg)`. - `Option` stops the work with an early return when `previous === this.defaultValue || !Array.isArray(previous)`. - `Option` stops the work with an early return when `this.variadic`. - `Option` stops the work with an early return when `this.long`. - `Option` stops the work with an early return when `this.negate`. ## Diagram ```mermaid graph LR Command[Command] -->|addOption| Option[Option] Environment[Environment variable] -->|env| Option Option -->|flags, defaults, rules| Parser[Argument parser] Parser -->|stores parsed value| CommandOptions[command.opts()] ``` ## Usage ```js const { Command, Option } = require('commander'); const program = new Command(); const formatOption = new Option( '-f, --format ', 'select output format' ) .choices(['text', 'json']) .default('text') .env('OUTPUT_FORMAT'); const quietOption = new Option('-q, --quiet', 'suppress output') .conflicts('verbose'); program .addOption(formatOption) .addOption(quietOption); program.parse(); const options = program.opts(); console.log(options.format); ``` ## AI Coding Instructions - Create options with `new Option(flags, description)` before adding them to a `Command`. - Use `choices()` for accepted argument values and `argParser()` when values need custom conversion. - Use `conflicts()` and `implies()` to describe relationships between option names, not flag strings. - Set `env()` when an option may read its value from an environment variable. - Use `hideHelp()` only for options that should still parse but should not appear in generated help. ## How it works I’ll inspect the option-token parsing branch to document the actual preconditions for required, optional, variadic, boolean, and negated flags. ## Relationships - IMPORTS → `InvalidArgumentError` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `program` — `index.js`:7 - `Command` — `lib/command.js`:14 # suggestSimilar **Kind:** Function **Source:** [`lib/suggestSimilar.js`](https://github.com/tj/commander.js/blob/main/lib/suggestSimilar.js#L56) Find close matches, restricted to same number of edits. `suggestSimilar` finds candidate values that closely match a given input while limiting results to candidates with the same edit distance. It supports suggestion flows where nearby alternatives should be returned without mixing candidates from different edit-distance groups. ## Signature ```ts function suggestSimilar(word, candidates) ``` ## Parameters | Name | Type | |---|---| | `word` | `any` | | `candidates` | `any` | ## Diagram ```mermaid graph LR Input[Input value] --> Suggest[suggestSimilar] Candidates[Candidate values] --> Suggest Suggest --> Filter[Filter by matching edit distance] Filter --> Matches[Similar matches] ``` ## Usage ```js const suggestSimilar = require('./lib/suggestSimilar'); const input = 'colour'; const candidates = ['color', 'collar', 'column']; const matches = suggestSimilar(input, candidates); console.log(matches); ``` ## AI Coding Instructions - Keep candidate values in the format expected by existing callers before passing them to `suggestSimilar`. - Preserve the edit-distance restriction when changing matching behavior; do not combine results from different distance groups. - Check existing tests and call sites before changing the function’s return shape or ordering. - Use `suggestSimilar` for suggestion output rather than duplicating edit-distance filtering in callers. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `Command` — `lib/command.js`:14 # Argument **Kind:** Class **Source:** [`lib/argument.js`](https://github.com/tj/commander.js/blob/main/lib/argument.js#L3) `Argument` defines a positional argument for a Commander command. It stores argument metadata such as the name, default value, parser, allowed choices, and whether the argument is required or optional. ## Methods | Method | Signature | Returns | |---|---|---| | `name` | `name()` | `void` | | `_collectValue` | `_collectValue(value: undefined, previous: undefined)` | `void` | | `default` | `default(value: undefined, description: undefined)` | `void` | | `argParser` | `argParser(fn: undefined)` | `void` | | `choices` | `choices(values: undefined)` | `void` | | `argRequired` | `argRequired()` | `void` | | `argOptional` | `argOptional()` | `void` | ## Where it refuses work - `Argument` stops the work with `InvalidArgumentError` when `!this.argChoices.includes(arg)`. - `Argument` stops the work with an early return when `previous === this.defaultValue || !Array.isArray(previous)`. - `Argument` stops the work with an early return when `this.variadic`. ## Diagram ```mermaid graph LR Command[Command] --> Argument[Argument] Argument --> Name[name()] Argument --> Default[default()] Argument --> Parser[argParser()] Argument --> Choices[choices()] Argument --> Required[argRequired()] Argument --> Optional[argOptional()] Parser --> Action[Command action] Choices --> Action ``` ## Usage ```js import { Argument, Command } from 'commander'; const mode = new Argument('mode') .choices(['development', 'production']) .argRequired(); const label = new Argument('label') .default('local') .argOptional(); const program = new Command(); program .name('deploy') .addArgument(mode) .addArgument(label) .action((selectedMode, selectedLabel) => { console.log(`Deploying ${selectedLabel} in ${selectedMode} mode`); }); program.parse(); ``` ## AI Coding Instructions - Create `Argument` instances and register them with a `Command` using `addArgument()`. - Use `argRequired()` or `argOptional()` to set positional argument behavior when it is not defined by the argument syntax. - Use `choices()` for fixed string values; it sets the argument parsing behavior for choice validation. - Use `argParser()` when an argument needs value conversion or custom validation, and return the parsed value. - Treat `_collectValue()` as internal behavior for collecting repeated values rather than calling it from command code. ## Relationships - IMPORTS → `InvalidArgumentError` ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `program` — `index.js`:7 - `Command` — `lib/command.js`:14 # createArgument **Kind:** Function **Source:** [`index.js`](https://github.com/tj/commander.js/blob/main/index.js#L12) ## Signature ```ts function createArgument(name, description) ``` ## Parameters | Name | Type | |---|---| | `name` | `any` | | `description` | `any` | # Command **Kind:** Class **Source:** [`lib/command.js`](https://github.com/tj/commander.js/blob/main/lib/command.js#L14) `Command` represents a CLI command and manages its child-command hierarchy, inherited settings, help output, and error behavior. It creates commands and help instances, applies output configuration, and controls help or suggestion display after errors. **Extends:** `EventEmitter` ## Methods | Method | Signature | Returns | |---|---|---| | `copyInheritedSettings` | `copyInheritedSettings(sourceCommand: undefined)` | `void` | | `_getCommandAndAncestors` | `_getCommandAndAncestors()` | `void` | | `command` | `command(nameAndArgs: undefined, actionOptsOrExecDesc: undefined, execOpts: undefined)` | `void` | | `createCommand` | `createCommand(name: undefined)` | `void` | | `createHelp` | `createHelp()` | `void` | | `configureHelp` | `configureHelp(configuration: undefined)` | `void` | | `configureOutput` | `configureOutput(configuration: undefined)` | `void` | | `showHelpAfterError` | `showHelpAfterError(displayHelp: undefined)` | `void` | | `showSuggestionAfterError` | `showSuggestionAfterError(displaySuggestion: undefined)` | `void` | | `addCommand` | `addCommand(cmd: undefined, opts: undefined)` | `void` | | `createArgument` | `createArgument(name: undefined, description: undefined)` | `void` | | `argument` | `argument(name: undefined, description: undefined, parseArg: undefined, defaultValue: undefined)` | `void` | | `arguments` | `arguments(names: undefined)` | `void` | | `addArgument` | `addArgument(argument: undefined)` | `void` | | `helpCommand` | `helpCommand(enableOrNameAndArgs: undefined, description: undefined)` | `void` | | `addHelpCommand` | `addHelpCommand(helpCommand: undefined, deprecatedDescription: undefined)` | `void` | | `_getHelpCommand` | `_getHelpCommand()` | `void` | | `hook` | `hook(event: undefined, listener: undefined)` | `void` | | `exitOverride` | `exitOverride(fn: undefined)` | `void` | | `_exit` | `_exit(exitCode: undefined, code: undefined, message: undefined)` | `void` | | `action` | `action(fn: undefined)` | `void` | | `createOption` | `createOption(flags: undefined, description: undefined)` | `void` | | `_callParseArg` | `_callParseArg(target: undefined, value: undefined, previous: undefined, invalidArgumentMessage: undefined)` | `void` | | `_registerOption` | `_registerOption(option: undefined)` | `void` | | `_registerCommand` | `_registerCommand(command: undefined)` | `void` | | `addOption` | `addOption(option: undefined)` | `void` | | `_optionEx` | `_optionEx(config: undefined, flags: undefined, description: undefined, fn: undefined, defaultValue: undefined)` | `void` | | `option` | `option(flags: undefined, description: undefined, parseArg: undefined, defaultValue: undefined)` | `void` | | `requiredOption` | `requiredOption(flags: undefined, description: undefined, parseArg: undefined, defaultValue: undefined)` | `void` | | `combineFlagAndOptionalValue` | `combineFlagAndOptionalValue(combine: undefined)` | `void` | | `allowUnknownOption` | `allowUnknownOption(allowUnknown: undefined)` | `void` | | `allowExcessArguments` | `allowExcessArguments(allowExcess: undefined)` | `void` | | `enablePositionalOptions` | `enablePositionalOptions(positional: undefined)` | `void` | | `passThroughOptions` | `passThroughOptions(passThrough: undefined)` | `void` | | `_checkForBrokenPassThrough` | `_checkForBrokenPassThrough()` | `void` | | `storeOptionsAsProperties` | `storeOptionsAsProperties(storeAsProperties: undefined)` | `void` | | `getOptionValue` | `getOptionValue(key: undefined)` | `void` | | `setOptionValue` | `setOptionValue(key: undefined, value: undefined)` | `void` | | `setOptionValueWithSource` | `setOptionValueWithSource(key: undefined, value: undefined, source: undefined)` | `void` | | `getOptionValueSource` | `getOptionValueSource(key: undefined)` | `void` | | `getOptionValueSourceWithGlobals` | `getOptionValueSourceWithGlobals(key: undefined)` | `void` | | `_prepareUserArgs` | `_prepareUserArgs(argv: undefined, parseOptions: undefined)` | `void` | | `parse` | `parse(argv: undefined, parseOptions: undefined)` | `void` | | `parseAsync` | `parseAsync(argv: undefined, parseOptions: undefined)` | `void` | | `_prepareForParse` | `_prepareForParse()` | `void` | | `saveStateBeforeParse` | `saveStateBeforeParse()` | `void` | | `restoreStateBeforeParse` | `restoreStateBeforeParse()` | `void` | | `_checkForMissingExecutable` | `_checkForMissingExecutable(executableFile: undefined, executableDir: undefined, subcommandName: undefined)` | `void` | | `_executeSubCommand` | `_executeSubCommand(subcommand: undefined, args: undefined)` | `void` | | `_dispatchSubcommand` | `_dispatchSubcommand(commandName: undefined, operands: undefined, unknown: undefined)` | `void` | ## Where it refuses work - `Command` stops the work with `Error` when `!cmd._name`. - `Command` stops the work with `Error` when `previousArgument?.variadic`. - `Command` stops the work with `Error` when `argument.required && argument.defaultValue !== undefined && argument.parseArg === undefin…`. - `Command` stops the work with `Error` when `!allowedValues.includes(event)`. - `Command` stops the work with `Error` when `typeof flags === 'object' && flags instanceof Option` — “To add an Option object use addOption() instead of option() or requiredOption()”. - `Command` stops the work with `Error` when `this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions`. ## When something fails - `Command` handles failure in 2 places: it logs it and continues in 1, and lets it reach the caller in 1. ## Diagram ```mermaid graph LR Command -->|command() / addCommand()| ChildCommand Command -->|createCommand()| NewCommand Command -->|createHelp()| Help Command -->|configureHelp()| HelpSettings Command -->|configureOutput()| OutputSettings Command -->|copyInheritedSettings()| InheritedSettings Command -->|showHelpAfterError()| ErrorHelp Command -->|showSuggestionAfterError()| ErrorSuggestion ChildCommand -->|_getCommandAndAncestors()| CommandHierarchy ``` ## Usage ```js import { Command } from 'commander'; const program = new Command(); program .name('tool') .description('Example command-line tool') .configureHelp({ sortSubcommands: true, }) .configureOutput({ writeErr: (message) => process.stderr.write(message), }) .showHelpAfterError() .showSuggestionAfterError(); program .command('serve') .description('Start the service') .action(() => { console.log('Service started'); }); program.parse(); ``` ## AI Coding Instructions - Add subcommands through `command()` or `addCommand()` so they are attached to the command hierarchy. - Override `createCommand()` when a subclass needs to create a custom command type for child commands. - Configure help and output behavior before adding child commands when child commands should inherit those settings. - Treat `_getCommandAndAncestors()` as an internal helper for hierarchy traversal; avoid calling it from application code. - Keep `showHelpAfterError()` and `showSuggestionAfterError()` aligned with configured output handlers so error messages reach the expected stream. ## Relationships - IMPORTS → `Argument` - IMPORTS → `humanReadableArgName` - IMPORTS → `CommanderError` - IMPORTS → `Help` - IMPORTS → `Option` - IMPORTS → `DualOptions` - IMPORTS → `suggestSimilar` ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `program` — `index.js`:7 # createOption **Kind:** Function **Source:** [`index.js`](https://github.com/tj/commander.js/blob/main/index.js#L10) ## Signature ```ts function createOption(flags, description) ``` ## Parameters | Name | Type | |---|---| | `flags` | `any` | | `description` | `any` | # InvalidArgumentError **Kind:** Class **Source:** [`lib/error.js`](https://github.com/tj/commander.js/blob/main/lib/error.js#L25) InvalidArgumentError class `InvalidArgumentError` represents an error raised when a caller passes an argument that does not meet an API's expected requirements. It lets validation code communicate argument-related failures distinctly from other error types. **Extends:** `CommanderError` ## Diagram ```mermaid graph LR A[Caller input] --> B[Argument validation] B -->|Invalid argument| C[InvalidArgumentError] C --> D[Caller handles error] ``` ## Usage ```js import { InvalidArgumentError } from './lib/error.js'; function setTimeoutDelay(delay) { if (typeof delay !== 'number' || delay < 0) { throw new InvalidArgumentError('delay must be a non-negative number'); } return delay; } try { setTimeoutDelay(-1); } catch (error) { if (error instanceof InvalidArgumentError) { console.error(error.message); } else { throw error; } } ``` ## AI Coding Instructions - Throw `InvalidArgumentError` when validation fails because of an invalid caller-supplied argument. - Include an error message that identifies the invalid argument and the expected constraint. - Check for this class with `instanceof InvalidArgumentError` when callers need argument-specific handling. - Keep argument validation close to the public API boundary before processing the input. ## Used by 3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (3) - `program` — `index.js`:7 - `Argument` — `lib/argument.js`:3 - `Option` — `lib/option.js`:3 # useColor **Kind:** Function **Source:** [`lib/command.js`](https://github.com/tj/commander.js/blob/main/lib/command.js#L2768) Exported for using from tests, not otherwise used outside this file. `useColor` is a helper exported from `lib/command.js` for test code. It exposes the command module's color-selection behavior without being used elsewhere outside that file. ## Diagram ```mermaid graph LR Environment[Runtime environment] --> UseColor[useColor] UseColor --> ColorDecision[Color decision] ColorDecision --> Tests[Test assertions] ``` ## Usage ```js import { useColor } from './lib/command.js'; const colorEnabled = useColor(); if (colorEnabled) { console.log('Color output is enabled'); } ``` ## AI Coding Instructions - Keep `useColor` exported so tests can access the same color behavior as `lib/command.js`. - Test color-related behavior through `useColor` rather than duplicating its decision logic in test files. - Avoid adding production call sites outside `lib/command.js` unless the module boundary is intentionally changed. - Account for runtime environment settings that may affect whether color output is enabled. # CommanderError **Kind:** Class **Source:** [`lib/error.js`](https://github.com/tj/commander.js/blob/main/lib/error.js#L4) CommanderError class `CommanderError` represents a command-processing failure with an associated exit code, error code, and message. It is thrown by command handling code so callers can report the failure and set the process exit status consistently. **Extends:** `Error` ## Diagram ```mermaid graph LR Command[Command processing] --> Validation[Validation or action failure] Validation --> Error[CommanderError] Error --> Code[code] Error --> Message[message] Error --> ExitCode[exitCode] Error --> Handler[Error handler] Handler --> ProcessExit[Process exit status] ``` ## Usage ```ts import { CommanderError } from './lib/error.js'; function abortCommand(exitCode: number, message: string): never { throw new CommanderError( exitCode, 'commander.invalidArgument', message, ); } try { abortCommand(process.exitCode, 'A required argument is missing.'); } catch (error) { if (error instanceof CommanderError) { console.error(error.message); process.exitCode = error.exitCode; } else { throw error; } } ``` ## AI Coding Instructions - Create `CommanderError` instances when command execution needs a known exit code and machine-readable error code. - Preserve `code`, `exitCode`, and `message` when rethrowing or handling command errors. - Check for `error instanceof CommanderError` before reading Commander-specific properties. - Set `process.exitCode` from `error.exitCode` in top-level error handling rather than discarding the error status. - Keep any original failure attached through `nestedError` when wrapping another error. ## Used by 2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (2) - `program` — `index.js`:7 - `Command` — `lib/command.js`:14 # createCommand **Kind:** Function **Source:** [`index.js`](https://github.com/tj/commander.js/blob/main/index.js#L9) ## Signature ```ts function createCommand(name) ``` ## Parameters | Name | Type | |---|---| | `name` | `any` | # DualOptions **Kind:** Class **Source:** [`lib/option.js`](https://github.com/tj/commander.js/blob/main/lib/option.js#L268) This class is to make it easier to work with dual options, without changing the existing implementation. We support separate dual options for separate positive and negative options, like `--build` and `--no-build`, which share a single option value. This works nicely for some use cases, but is tricky for others where we want separate behaviours despite the single shared option value. `DualOptions` manages paired positive and negative CLI options that share the same option attribute, such as `--build` and `--no-build`. It determines the value represented by the option that was supplied, allowing the parser to preserve distinct behavior for each side of a dual option. ## Methods | Method | Signature | Returns | |---|---|---| | `valueFromOption` | `valueFromOption(value: undefined, option: undefined)` | `void` | ## Where it refuses work - `DualOptions` stops the work with an early return when `!this.dualOptions.has(optionKey)`. ## Diagram ```mermaid graph LR A[CLI input] --> B[Option] B --> C[DualOptions] C --> D[valueFromOption] D --> E[Shared option value] ``` ## Usage ```js import { Command } from 'commander'; const program = new Command(); program .option('--build', 'enable build output') .option('--no-build', 'disable build output'); program.parse(); const options = program.opts(); if (options.build) { console.log('Build output is enabled.'); } else { console.log('Build output is disabled.'); } ``` ## AI Coding Instructions - Treat `DualOptions` as parser support code for positive and negative options that map to the same attribute. - Keep paired option names aligned, such as `--build` and `--no-build`, so they resolve to the same option value. - Use `valueFromOption()` when converting a parsed option occurrence into its stored value. - Do not assume a negative option always means the parsed value is `false`; preserve the option-specific behavior handled by this class. ## Used by 1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example. ### Imported by (1) - `Command` — `lib/command.js`:14