JavaScript option parsing and help generation library with strict type checking and validation
npx @tessl/cli install tessl/npm-optionator@0.9.0Optionator is a JavaScript/Node.js option parsing and help generation library that provides strict type checking and validation. Unlike other option parsers that accept all input, Optionator validates options against specified types and provides intelligent error reporting with suggestions for misspelled options.
npm install optionatorconst optionator = require('optionator');For ES modules (with transpilation):
import optionator from 'optionator';const optionator = require('optionator')({
prepend: 'Usage: cmd [options]',
append: 'Version 1.0.0',
options: [{
option: 'help',
alias: 'h',
type: 'Boolean',
description: 'displays help'
}, {
option: 'count',
alias: 'c',
type: 'Int',
description: 'number of things',
example: 'cmd --count 2'
}]
});
// Parse command line arguments
const options = optionator.parseArgv(process.argv);
// Display help if needed
if (options.help) {
console.log(optionator.generateHelp());
}
console.log(options.count); // Parsed and validated count valueOptionator is built around a factory function that creates parser instances with configured options:
Creates an optionator instance with the specified configuration options.
/**
* Creates an optionator instance for parsing command line options
* @param {OptionatorConfig} config - Configuration object defining options and behavior
* @returns {OptionatorInstance} Parser instance with parse, parseArgv, generateHelp methods
*/
function optionator(config: OptionatorConfig): OptionatorInstance;
interface OptionatorConfig {
prepend?: string;
append?: string;
options: Array<OptionDefinition | HeadingDefinition>;
helpStyle?: HelpStyleConfig;
mutuallyExclusive?: Array<Array<string | Array<string>>>;
positionalAnywhere?: boolean;
typeAliases?: Record<string, string>;
defaults?: Partial<OptionDefinition>;
concatRepeatedArrays?: boolean | [boolean, Record<string, any>];
mergeRepeatedObjects?: boolean;
stdout?: NodeJS.WriteStream;
}
interface OptionDefinition {
option: string;
alias?: string | Array<string>;
type: string;
enum?: Array<string>;
default?: string;
description?: string;
longDescription?: string;
example?: string | Array<string>;
required?: boolean;
restPositional?: boolean;
overrideRequired?: boolean;
dependsOn?: string | Array<string>;
concatRepeatedArrays?: boolean | [boolean, Record<string, any>];
mergeRepeatedObjects?: boolean;
boolean?: boolean;
hidden?: boolean;
}
interface HeadingDefinition {
heading: string;
}
interface HelpStyleConfig {
aliasSeparator?: string;
typeSeparator?: string;
descriptionSeparator?: string;
initialIndent?: number;
secondaryIndent?: number;
maxPadFactor?: number;
}
interface OptionatorInstance {
parse: (input: string | Array<string> | Record<string, any>, options?: ParseOptions) => ParsedOptions;
parseArgv: (input: Array<string>) => ParsedOptions;
generateHelp: (options?: HelpOptions) => string;
generateHelpForOption: (optionName: string) => string;
}Processes input according to the configured options and returns parsed results.
/**
* Processes input according to settings and returns parsed options
* @param {string | Array<string> | Record<string, any>} input - The input to parse
* @param {ParseOptions} options - Optional parsing configuration
* @returns {ParsedOptions} Object with parsed options and positional arguments
*/
parse(input: string | Array<string> | Record<string, any>, options?: ParseOptions): ParsedOptions;
interface ParseOptions {
slice?: number;
}
interface ParsedOptions {
[optionName: string]: any;
_: Array<string>;
}Usage Examples:
// Parse array of arguments
const result = optionator.parse(['--count', '5', 'file.txt']);
// Result: { count: 5, _: ['file.txt'] }
// Parse string input
const result = optionator.parse('--count 5 file.txt');
// Result: { count: 5, _: ['file.txt'] }
// Parse object input
const result = optionator.parse({ count: 5, _: ['file.txt'] });
// Result: { count: 5, _: ['file.txt'] }Parses array input with automatic slicing for process.argv compatibility.
/**
* Parses array input with default slice of 2 for process.argv
* @param {Array<string>} input - Array of command line arguments
* @returns {ParsedOptions} Object with parsed options and positional arguments
*/
parseArgv(input: Array<string>): ParsedOptions;Usage Example:
// Typically used with process.argv
const options = optionator.parseArgv(process.argv);
// Equivalent to: optionator.parse(process.argv, { slice: 2 })Produces formatted help text based on the configured options.
/**
* Generates formatted help text based on configuration
* @param {HelpOptions} options - Optional help generation settings
* @returns {string} Formatted help text
*/
generateHelp(options?: HelpOptions): string;
interface HelpOptions {
showHidden?: boolean;
interpolate?: Record<string, string>;
}Usage Example:
console.log(optionator.generateHelp());
/*
Usage: cmd [options]
-h, --help displays help
-c, --count Int number of things
Version 1.0.0
*/
// With interpolation
console.log(optionator.generateHelp({
interpolate: { version: '2.1.0' }
}));Generates detailed help text for a specific option.
/**
* Generates detailed help text for a specific option
* @param {string} optionName - Name of the option to display help for
* @returns {string} Detailed help text for the option
*/
generateHelpForOption(optionName: string): string;Usage Example:
console.log(optionator.generateHelpForOption('count'));
/*
-c, --count Int
description: number of things
example: cmd --count 2
*/Static version property available on the main export.
/**
* Current version of the optionator library
*/
optionator.VERSION: string;Optionator uses type-check format for type specifications. Common types include:
Boolean - Boolean flagsInt - Integer numbersNumber - Floating point numbersString - Text strings[String] - Arrays of strings{String: Number} - Objects with string keys and number valuesString | Number - Union typesMaybe String - Optional typesMain Configuration Properties:
prepend: Text displayed before the options in help outputappend: Text displayed after the options in help outputoptions (required): Array of option definitions and heading definitionshelpStyle: Object configuring help text formattingmutuallyExclusive: Array of mutually exclusive option groupspositionalAnywhere: Whether positional arguments can appear anywhere (default: true)typeAliases: Object defining type aliases for custom type namesdefaults: Default values applied to all option definitionsconcatRepeatedArrays: Global setting for concatenating repeated array valuesmergeRepeatedObjects: Global setting for merging repeated object valuesstdout: Output stream for help text (default: process.stdout)Option Definition Properties:
option (required): Option name in dash-case without leading dashesalias: String or array of alias names (single character for short flags)type (required): Type specification in type-check formatenum: Array of allowed values (parsed by levn)default: Default value as string (parsed by levn)description: Short description for help textlongDescription: Detailed description for individual option helpexample: Usage example(s) for option helprequired: Whether the option is requiredrestPositional: Take all remaining arguments as positionaloverrideRequired: Override required validation when this option is useddependsOn: Other options this option depends onconcatRepeatedArrays: Concatenate repeated array values instead of overwriting (can be boolean or [boolean, options])mergeRepeatedObjects: Merge repeated object values instead of overwritingboolean: Treat option as boolean flag (auto-set for Boolean type)hidden: Hide from help unless showHidden is trueMutual Exclusivity:
mutuallyExclusive: [
['verbose', 'quiet'], // --verbose and --quiet are mutually exclusive
[['output', 'o'], 'silent'] // --output/-o and --silent are mutually exclusive
]Dependencies:
dependsOn: 'config' // Simple dependency
dependsOn: ['and', 'user', 'pass'] // Requires both user AND pass
dependsOn: ['or', 'token', 'key'] // Requires either token OR keyOptionator supports a special -NUM pattern for numeric flags (e.g., -42, -3.14):
// Define NUM option
options: [{
option: 'NUM',
type: 'Number',
description: 'Set numeric value'
}]
// Usage: command -42 will set NUM option to 42Note: NUM options cannot have aliases and are accessed via -NUM format.
For Boolean options without aliases that default to true, optionator automatically enables no-prefix negation:
// This Boolean option with default 'true' and no aliases
{ option: 'color', type: 'Boolean', default: 'true' }
// Can be negated with --no-colorOptionator provides detailed error messages for various validation failures:
Example error messages:
Invalid option '--halp' - perhaps you meant '--help'?
Invalid value for option 'count' - expected type Int, received value: abc.
Option --verbose is required.
The options --verbose and --quiet are mutually exclusive.
The option 'secure' did not have its dependencies met.
No -NUM option defined.
Only use 'no-' prefix for Boolean options, not with 'verbose'.