or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-optionator

JavaScript option parsing and help generation library with strict type checking and validation

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/optionator@0.9.x

To install, run

npx @tessl/cli install tessl/npm-optionator@0.9.0

index.mddocs/

Optionator

Optionator 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.

Package Information

  • Package Name: optionator
  • Package Type: npm
  • Language: JavaScript (compiled from LiveScript)
  • Installation: npm install optionator

Core Imports

const optionator = require('optionator');

For ES modules (with transpilation):

import optionator from 'optionator';

Basic Usage

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 value

Architecture

Optionator is built around a factory function that creates parser instances with configured options:

  • Factory Function: Main export that creates optionator instances with configuration
  • Type System: Integration with type-check and levn libraries for strict type validation
  • Help Generation: Intelligent help text formatting that adapts to console width
  • Error Reporting: Detailed error messages with suggestions for misspelled options
  • Validation Engine: Comprehensive option validation including dependencies, mutual exclusivity, and requirements

Capabilities

Factory Function

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;
}

Parse Method

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'] }

Parse Argv Method

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 })

Generate Help Method

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' }
}));

Generate Help For Option Method

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
*/

Version Property

Static version property available on the main export.

/**
 * Current version of the optionator library
 */
optionator.VERSION: string;

Types

Option Types

Optionator uses type-check format for type specifications. Common types include:

  • Boolean - Boolean flags
  • Int - Integer numbers
  • Number - Floating point numbers
  • String - Text strings
  • [String] - Arrays of strings
  • {String: Number} - Objects with string keys and number values
  • String | Number - Union types
  • Maybe String - Optional types

Configuration Options

Main Configuration Properties:

  • prepend: Text displayed before the options in help output
  • append: Text displayed after the options in help output
  • options (required): Array of option definitions and heading definitions
  • helpStyle: Object configuring help text formatting
  • mutuallyExclusive: Array of mutually exclusive option groups
  • positionalAnywhere: Whether positional arguments can appear anywhere (default: true)
  • typeAliases: Object defining type aliases for custom type names
  • defaults: Default values applied to all option definitions
  • concatRepeatedArrays: Global setting for concatenating repeated array values
  • mergeRepeatedObjects: Global setting for merging repeated object values
  • stdout: Output stream for help text (default: process.stdout)

Option Definition Properties:

  • option (required): Option name in dash-case without leading dashes
  • alias: String or array of alias names (single character for short flags)
  • type (required): Type specification in type-check format
  • enum: Array of allowed values (parsed by levn)
  • default: Default value as string (parsed by levn)
  • description: Short description for help text
  • longDescription: Detailed description for individual option help
  • example: Usage example(s) for option help
  • required: Whether the option is required
  • restPositional: Take all remaining arguments as positional
  • overrideRequired: Override required validation when this option is used
  • dependsOn: Other options this option depends on
  • concatRepeatedArrays: Concatenate repeated array values instead of overwriting (can be boolean or [boolean, options])
  • mergeRepeatedObjects: Merge repeated object values instead of overwriting
  • boolean: Treat option as boolean flag (auto-set for Boolean type)
  • hidden: Hide from help unless showHidden is true

Mutual 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 key

Special Features

NUM Option Support

Optionator 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 42

Note: NUM options cannot have aliases and are accessed via -NUM format.

No-prefix Boolean Options

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-color

Error Handling

Optionator provides detailed error messages for various validation failures:

  • Invalid options: Suggests closest matching option using Levenshtein distance
  • Type validation: Shows expected vs received type with the invalid value
  • Missing required: Lists which required options are missing
  • Mutual exclusivity: Identifies conflicting options that cannot be used together
  • Dependencies: Reports which dependency requirements are not met
  • Enum validation: Shows which values are allowed for enum-type options
  • NUM option errors: Reports when NUM option is used but not defined

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'.