npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@vvlad1973/args-parser

v1.0.1

Published

Lightweight TypeScript argument parser for CLI with validation, choices, and conditional requirements

Readme

Args Parser

npm version License: MIT TypeScript Node.js

Lightweight TypeScript argument parser for command-line interfaces with validation, choices, and conditional requirements.

Features

  • Positional arguments with validation
  • Named flags with short aliases
  • Type-safe parsing (string, number, boolean)
  • Conditional requirements based on context
  • Choices validation
  • Custom validation functions
  • Conflicting flags detection
  • Multiple values support
  • Rest arguments
  • Default values
  • Auto-generated usage and help text
  • Zero dependencies

Installation

npm install @vvlad1973/args-parser

Quick Start

import { ArgParser } from '@vvlad1973/args-parser';

const result = ArgParser.parse('deploy production --verbose', [
  { name: 'command', required: true, choices: ['deploy', 'build', 'test'] },
  { name: 'target', required: true },
  { name: '--verbose', alias: '-v', type: 'boolean', help: 'Verbose output' }
], 'myapp');

console.log(result.args.command);  // 'deploy'
console.log(result.args.target);   // 'production'
console.log(result.flags['--verbose']); // true
console.log(result.help);          // Auto-generated help text

API Reference

ArgParser.parse(input, definitions, commandName?)

Parses command-line arguments according to provided definitions.

Parameters:

  • input: string | string[] - Input string or arguments array
  • definitions: ArgDefinition[] - Array of argument definitions
  • commandName: string (optional) - Command name for usage string

Returns: ParseResult

interface ParseResult {
  raw: string;                                // Original input
  args: Record<string, ParsedValue | undefined>;  // Positional arguments
  flags: Record<string, ParsedValue | undefined>; // Named flags
  usage: string;                              // Usage string
  help: string;                               // Help text
}

ArgDefinition

Argument definition interface:

interface ArgDefinition {
  name: string;                    // Argument name (e.g., 'user' or '--force')
  alias?: string;                  // Short alias (e.g., '-f' for '--force')
  type?: 'string' | 'number' | 'boolean';  // Argument type (default: 'string')
  required?: boolean | ((context) => boolean);  // Required flag or function
  rest?: boolean;                  // Accept all remaining tokens
  multiple?: boolean;              // Allow multiple values
  help?: string;                   // Help text
  validate?: (value, context) => boolean;  // Custom validation
  choices?: string[];              // List of valid choices
  conflicts?: string[];            // Mutually exclusive flags
  default?: ParsedValue;           // Default value
}

Examples

Basic Positional Arguments

const result = ArgParser.parse('john doe', [
  { name: 'firstName' },
  { name: 'lastName' }
]);

console.log(result.args.firstName); // 'john'
console.log(result.args.lastName);  // 'doe'

Flags with Aliases

const result = ArgParser.parse('-v -o output.txt', [
  { name: '--verbose', alias: '-v', type: 'boolean' },
  { name: '--output', alias: '-o', type: 'string' }
]);

console.log(result.flags['--verbose']); // true
console.log(result.flags['--output']);  // 'output.txt'

Required Arguments

const result = ArgParser.parse('deploy', [
  { name: 'command', required: true },
  { name: 'target', required: true }
]);
// Throws: ArgParseError: Argument target is required

Conditional Requirements

const result = ArgParser.parse('deploy production', [
  { name: 'command', choices: ['deploy', 'build', 'list'] },
  {
    name: 'target',
    required: ctx => ctx.command === 'deploy'  // Required only for 'deploy'
  }
]);

Choices Validation

const result = ArgParser.parse('json', [
  {
    name: 'format',
    choices: ['json', 'yaml', 'xml'],
    help: 'Output format'
  }
]);

Custom Validation

const result = ArgParser.parse('--port 8080', [
  {
    name: '--port',
    type: 'number',
    validate: (val) => val >= 1 && val <= 65535,
    help: 'Server port (1-65535)'
  }
]);

Conflicting Flags

const result = ArgParser.parse('--json --raw', [
  { name: '--json', type: 'boolean', conflicts: ['--raw'] },
  { name: '--raw', type: 'boolean' }
]);
// Throws: ArgParseError: Flags --json and --raw are mutually exclusive

Multiple Values

const result = ArgParser.parse('--tag alpha --tag beta --tag gamma', [
  {
    name: '--tag',
    type: 'string',
    multiple: true,
    help: 'Add tags (can be repeated)'
  }
]);

console.log(result.flags['--tag']); // ['alpha', 'beta', 'gamma']

Rest Arguments

const result = ArgParser.parse('git commit -m Initial commit', [
  { name: 'command' },
  { name: 'subcommand' },
  { name: 'args', rest: true }  // Captures all remaining tokens
]);

console.log(result.args.args); // '-m Initial commit'

Default Values

const result = ArgParser.parse('', [
  { name: 'format', default: 'json' },
  { name: '--verbose', type: 'boolean', default: false }
]);

console.log(result.args.format);        // 'json'
console.log(result.flags['--verbose']); // false

Complex Example

const definitions = [
  {
    name: 'command',
    required: true,
    choices: ['deploy', 'build', 'test'],
    help: 'Command to execute'
  },
  {
    name: 'target',
    required: ctx => ctx.command === 'deploy',
    help: 'Deployment target'
  },
  {
    name: '--env',
    alias: '-e',
    type: 'string',
    choices: ['dev', 'staging', 'prod'],
    default: 'dev',
    help: 'Environment'
  },
  {
    name: '--verbose',
    alias: '-v',
    type: 'boolean',
    default: false,
    help: 'Verbose output'
  },
  {
    name: '--tag',
    type: 'string',
    multiple: true,
    help: 'Tags to apply'
  },
  {
    name: '--dry-run',
    type: 'boolean',
    conflicts: ['--force'],
    help: 'Dry run mode'
  },
  {
    name: '--force',
    type: 'boolean',
    help: 'Force operation'
  }
];

const result = ArgParser.parse(
  'deploy production -e prod -v --tag release --tag v1.0.0',
  definitions,
  'mycli'
);

console.log(result.help);
// Usage: mycli <command:deploy|build|test> [target] [--env <string>] [--verbose] [--tag <string>...] [--dry-run] [--force]
//
// Arguments:
//   command              Command to execute (required)
//   target               Deployment target
//
// Options:
//   --env, -e            Environment
//   --verbose, -v        Verbose output
//   --tag                Tags to apply (can be repeated)
//   --dry-run            Dry run mode
//   --force              Force operation

Error Handling

The parser throws ArgParseError with descriptive messages and usage information:

try {
  const result = ArgParser.parse('--port invalid', [
    { name: '--port', type: 'number' }
  ], 'myapp');
} catch (err) {
  if (err instanceof ArgParseError) {
    console.error(err.message); // "Invalid number: invalid"
    console.error(err.usage);   // "Usage: myapp [--port <number>]"
  }
}

TypeScript Support

Full TypeScript support with exported types:

import {
  ArgParser,
  ArgParseError,
  type ArgDefinition,
  type ParseResult,
  type ParsedValue
} from '@vvlad1973/args-parser';

Comparison with minimist

See COMPARISON.md for detailed comparison with minimist.

Key advantages:

  • Declarative validation (required, choices, custom validators)
  • Conditional requirements
  • Auto-generated help and usage
  • Type-safe parsing
  • Conflicting flags detection
  • Better error messages

License

MIT with Commercial Use

Author

Vladislav Vnukovskiy [email protected]