Argument Parsing
CLI Forge turns raw process.argv into a fully-typed args object. You declare options on a builder, and the parser handles tokenization, type coercion, defaults, environment variables, config files, and validation. This guide is a reference for what's available and how the pieces fit together.
How parsing works
When you call .forge(), every command level runs through the same normalization pipeline before its handler executes:
- Tokenize raw CLI arguments
- Apply environment variables for options that read from
env - Apply configuration files registered with
.config() - Apply defaults for missing options
- Coerce values via the option's
coercefunction - Validate: check
required,choices, customvalidate,conflicts,implies, and (in strict mode) unknown arguments
Earlier sources beat later ones: a CLI flag overrides an env var, which overrides a config file, which overrides a default. For nested commands, parsing happens at each level so subcommand options can reference parent options.
For the full lifecycle including builders, middleware, and init hooks, see the execution lifecycle example.
Option types
CLI Forge supports six option kinds plus positional arguments. Each kind contributes its TypeScript type to the inferred args object.
String
The default kind. Accepts any string value.
.option('name', {
type: 'string',
description: 'Release name',
default: 'latest',
})
Pass on the CLI as --name release. Restrict allowed values with choices (see Validation below).
Number
Coerces the input to a JavaScript number. Non-numeric input fails validation.
.option('port', {
type: 'number',
description: 'Port to listen on',
default: 3000,
})
Pass on the CLI as --port 8080.
Boolean
Boolean flags accept three forms: bare flag, explicit value, and negated flag.
.option('verbose', {
type: 'boolean',
description: 'Enable verbose logging',
default: false,
})
All of these set the option:
--verbose→true--verbose true/--verbose false→true/false--no-verbose→false
Array
Arrays collect multiple values into a single string[] or number[], depending on items.
.option('tags', {
type: 'array',
items: 'string',
description: 'Tags to apply (space, comma, or repeated flag)',
default: [],
})
The same option can be passed three ways:
- Space-separated:
--tags api db admin - Comma-separated:
--tags api,db,admin - Repeated flags:
--tags api --tags db --tags admin
For items: 'number', each value is coerced to a number individually.
Object
Object options carry nested structure with full type inference. You declare the shape with properties, and the parser accepts either dot-notation flags or a JSON string (or both, mixed).
For a quick demonstration of nested types and dot-notation, see the object dot-notation example.
For a deeper walkthrough — defaults at any level, conditionally required nested properties, validation, and JSON input — see the object arguments example.
Pass on the CLI as:
- Dot-notation:
--config.server.host localhost --config.server.port 8080 - JSON string:
--config '{"server":{"host":"localhost","port":8080}}' - Mixed (later values win):
--config '{"server":{}}' --config.server.port 8080
Object options are verbose for users — prefer flat options for common settings, and reserve objects for genuinely nested configuration.
oneOf
oneOf lets a single flag accept values of different types, with the parser trying each valueType in order.
A common pattern is a flag that doubles as a boolean toggle and a typed selector, like --color / --no-color / --color=always:
import cliForge from 'cli-forge';
const cli = cliForge('color-demo')
.option('color', {
type: 'oneOf',
valueTypes: [
{ type: 'string', choices: ['auto', 'always', 'never'] as const },
{ type: 'boolean' },
],
default: 'auto',
description: 'When to use colors in output',
})
.handler((args) => {
console.log(`Color mode: ${args.color}`);
});
export default cli;
if (require.main === module) {
(async () => {
await cli.forge();
})();
}
Boolean handling is exclusive when boolean appears in valueTypes: the bare flag (--color), negation (--no-color), and the literals true/false always go to the boolean parser. All other inputs are tried against the remaining types in array order.
For oneOf of number | string and nested object branches, see the oneOf example.
Positional arguments
Positional arguments are values without a leading --flag. Register them with .positional() instead of .option(). They're matched by order on the command line.
.positional('target', {
type: 'string',
required: true,
description: 'Where to deploy (e.g. production, staging)',
})
With this declaration, argument-types deploy production binds target to "production". Positionals can be required: true, accept defaults, or use any of the other option types — the same type system applies.
Aliases and short flags
Every option can carry extra names through alias. Aliases and short flags are one mechanism — a single-character alias is the short flag:
cli('deploy')
.option('force', { type: 'boolean', alias: ['f'] })
.option('verbose', { type: 'boolean', alias: ['v'] })
.option('name', { type: 'string', alias: ['n', 'app-name'] })
.forge();
The length of an alias decides how you can type it:
- One character — usable with a single dash (
-f) and groupable. - Two or more characters — long-form only (
--app-name). A single dash is read as a group of one-character aliases, so-app-nameis not the alias, it's the charactersa,p,p, and so on. Help output follows the same convention: any alias longer than one character renders with two dashes.
Grouping
Single-character aliases combine behind one dash. -fv means -f -v:
deploy -fv # force: true, verbose: true
deploy -fn release # force: true, name: 'release'
The first option in a group that takes a value ends the group. The rest of that token is its value, which is how GNU tools read short flags. So the attached, = and separate forms all agree:
deploy -fnrelease # force: true, name: 'release'
deploy -fn=release # force: true, name: 'release'
deploy -fn release # force: true, name: 'release'
Nothing after that option is read as a flag, whatever the characters happen to alias elsewhere. Put value-taking options last:
deploy -nf release # name: 'f' — 'release' is left over, and force is unset
Array options end a group the same way. -fl a b fills list with a and b; -lf a b fills it with f, a and b.
Unrecognized characters
A character that resolves to nothing is reported on its own. With only force declared, -fx sets force and leaves -x in unmatched:
deploy -fx # force: true, unmatched: ['-x']
deploy -x # unmatched: ['-x']
The exception is a group where no character resolves, which stays intact as one unmatched token so pass-through consumers see the argument as typed.
Take care when declaring a multi-character alias whose characters double as single-character aliases on the same command. Given --prc alongside -p and -r, typing -prc out of habit resolves against the merged option set of the whole command chain, not against --prc. If -p takes a value, -prc means -p rc; if every member is a flag, p and r bind and -c is reported with the token that produced it, so it still suggests --prc. Neither reading is what the user meant — pick alias letters that don't spell each other.
Validation
Validation runs after coercion and before the handler. Each feature is opt-in.
Choices
Restrict an option to a set of allowed values. With a static array, TypeScript narrows the value to the literal union (e.g. 'sir' | 'madame').
.option('name', {
type: 'string',
description: 'The name to say hello to',
required: true,
// Choices limits valid values for the option.
// If the provided value is not in the choices array, an error will be thrown.
choices: ['sir', 'madame'],
})
Choices can also be a function for runtime-computed values:
.option('phrase', {
type: 'string',
default: 'hello',
// Choices can also be provided as a function that returns an array of valid values.
// This can be useful if the choices are dynamic or need to be calculated at runtime.
choices: () => ['hello', 'hi', 'hey'],
}),
Required
Set required: true to fail validation when no value is provided from any source (CLI, env, config, default).
Custom validate
Provide a validate(value) function that returns true for valid input or an error message string. Runs after coerce and choices.
Conflicts and implications
Express relationships between options with .conflicts() and .implies():
cli('conflicts-and-implications', {
builder: (args) =>
args
.option('source', {
describe: 'Source database',
type: 'string',
})
.option('target', {
describe: 'Target database',
type: 'string',
})
.option('dry-run', {
describe: 'Simulate the migration without making changes',
type: 'boolean',
})
.option('force', {
describe: 'Force the migration even if there are warnings',
type: 'boolean',
})
.option('backup', {
describe: 'Where should the backup be stored',
type: 'string',
})
// Conflicts creates mutually exclusive arguments. Validation will throw an error if both options are provided.
// In this case, it makes sense that the user wouldn't want to both simulate and force a migration.
.conflicts('dry-run', 'force')
// Implies creates mutually required arguments. Validation will throw an error if the first argument is provided without the second.
// Practically in this case, this means that if the user provides the --force option, they must also provide the --backup option.
.implies('force', 'backup'),
handler: (_args) => {
// ...
},
}).forge();
.conflicts('a', 'b')—aandbcannot both be provided..implies('a', 'b')— providingarequiresbto also be provided.
Strict mode
By default, unknown arguments are silently collected into an unmatched array. Strict mode rejects them:
const cli = cliForge('strict-mode-example')
// Enable strict mode - unmatched arguments will throw validation errors
.strict()
.option('name', {
type: 'string',
description: 'The name to greet',
default: 'World',
})
.command('$0', {
builder: (args) => args,
handler: (args) => {
console.log(`Hello, ${args.name}!`);
},
});
Use non-strict mode when wrapping another tool that needs pass-through arguments.
Strict mode runs three checks, and .strict() takes an object to turn any of them off:
unknownOptions— an unmatched token starting with-.unknownArguments— an unmatched bare token, including a typoed subcommand name.partialShortFlagGroups— a short flag group such as-fxwhere some characters resolved and some didn't.
The object spreads over the all-checks-on default, so .strict({ unknownArguments: false }) reads as "strict, except stray positionals". partialShortFlagGroups stays separate from unknownOptions because a partial group has already applied the values of the characters that did resolve.
For the deeper validation reference (validation order, custom validators, error handling), see the validation guide.
Value sources
In addition to CLI flags, options can be populated from environment variables, configuration files, or defaults. Precedence (highest wins): CLI flags > env vars > config files > defaults.
Environment variables
Two opt-in modes:
- Per-option — set
env: 'MY_VAR'on individual options to pull from a specific variable. - Global — call
.env()to enable env-var support for every option, with names auto-derived from the CLI name and option name.
import cli from 'cli-forge';
// Without calling .env(), environment variable support is opt-in per option.
// Only options with an explicit `env` key can be populated from the environment —
// every other option can only be set via command-line flags.
const app = cli('greet-app').command('hello', {
builder: (args) =>
args
.option('name', {
type: 'string',
required: true,
description: 'Name to greet',
// Reads from the GREET_NAME environment variable.
// The key you provide here is used as-is (no prefix is applied).
// camelCase, dashed-case, and UPPER_SNAKE_CASE are all accepted.
env: 'GREET_NAME',
})
.option('greeting', {
type: 'string',
default: 'Hello',
description: 'Greeting word to use',
env: 'GREET_GREETING',
})
.option('verbose', {
type: 'boolean',
default: false,
description: 'Print extra details',
// No `env` key — this option cannot be set from the environment.
// It can only be passed as --verbose on the command line.
}),
handler: (args) => {
if (args.verbose) {
console.log('Verbose mode enabled');
}
console.log(`${args.greeting}, ${args.name}!`);
},
});
export default app;
if (require.main === module) {
app.forge();
}
The same CLI with global env support:
import cli from 'cli-forge';
// Calling .env() enables environment variable support for every option at once.
// The CLI name is converted to UPPER_SNAKE_CASE and used as a prefix, so the
// CLI named "greet-app" produces the prefix "GREET_APP".
//
// For example:
// --name reads from GREET_APP_NAME
// --greeting reads from GREET_APP_GREETING
const app = cli('greet-app')
.env()
.command('hello', {
builder: (args) =>
args
.option('name', {
type: 'string',
required: true,
description: 'Name to greet',
})
.option('greeting', {
type: 'string',
default: 'Hello',
description: 'Greeting word to use',
}),
handler: (args) => {
console.log(`${args.greeting}, ${args.name}!`);
},
});
export default app;
if (require.main === module) {
app.forge();
}
Configuration files
Register a configuration provider with .config() to load values from JSON or package.json. Multiple providers can be registered; the first to supply a value wins. Config files can extends other configs for shared base configurations.
See the configuration files guide for the full reference.
Defaults
Three forms — direct value, { value, description }, and { factory, description } — see the default values example for when each form makes sense (notably, description keeps generated docs deterministic when the actual default depends on env or arch).
Quick reference
| Feature | Where to declare | Purpose |
|---|---|---|
type: 'string' | option | Plain string value |
type: 'number' | option | Numeric value, coerced from string |
type: 'boolean' | option | Flag, supports --no- negation |
type: 'array' + items | option | List of strings or numbers |
type: 'object' + properties | option | Nested structure via dot-notation or JSON |
type: 'oneOf' + valueTypes | option | Multi-typed flag (e.g. boolean-or-string) |
.positional(name, opts) | builder | Argument matched by position, not by flag |
alias: [...] | option | Extra names; a one-character alias is the short flag |
choices: [...] | option | Restrict to a fixed set, narrows TS type |
required: true | option | Fail if no value from any source |
default: ... | option | Fallback when no source provides a value |
coerce: (v) => ... | option | Transform the parsed value |
validate: (v) => ... | option | Custom validation, returns true or error string |
env: 'NAME' | option | Read from a specific environment variable |
.env() | CLI | Enable env-var support for every option |
.config(provider) | CLI | Load values from JSON or package.json |
.conflicts('a', 'b') | builder | Mutually exclusive options |
.implies('a', 'b') | builder | a requires b |
.strict() | CLI | Reject unrecognized arguments |