CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-yargs-parser

The mighty option parser used by yargs for parsing command-line arguments with extensive configuration options.

Overview
Eval results
Files

parser-options.mddocs/

Parser Options

Parser options provide hints and specifications that control how individual arguments are processed and coerced during parsing. These options allow fine-grained control over argument interpretation.

Import

import parser from "yargs-parser";

API

interface Options {
  /** An object representing the set of aliases for a key */
  alias: Dictionary<string | string[]>;
  /** Indicate that keys should be parsed as an array */
  array: ArrayOption | ArrayOption[];
  /** Arguments should be parsed as booleans */
  boolean: string | string[];
  /** Indicate a key that represents a path to a configuration file */
  config: string | string[] | Dictionary<boolean | ConfigCallback>;
  /** Configuration objects to parse, their properties will be set as arguments */
  configObjects: Dictionary<any>[];
  /** Provide configuration options to the yargs-parser */
  configuration: Partial<Configuration>;
  /** Provide a custom synchronous function that returns a coerced value from the argument provided */
  coerce: Dictionary<CoerceCallback>;
  /** Indicate a key that should be used as a counter */
  count: string | string[];
  /** Provide default values for keys */
  default: Dictionary<any>;
  /** Environment variables (`process.env`) with the prefix provided should be parsed */
  envPrefix?: string;
  /** Specify that a key requires n arguments */
  narg: Dictionary<number>;
  /** `path.normalize()` will be applied to values set to this key */
  normalize: string | string[];
  /** Keys should be treated as strings (even if they resemble a number) */
  string: string | string[];
  /** Keys should be treated as numbers */
  number: string | string[];
  /** i18n handler, defaults to util.format */
  __: (format: any, ...param: any[]) => string;
  /** Alias lookup table defaults */
  key: Dictionary<any>;
}

type ArrayOption = string | { 
  key: string; 
  boolean?: boolean; 
  string?: boolean; 
  number?: boolean; 
  integer?: boolean; 
};

type CoerceCallback = (arg: any) => any;
type ConfigCallback = (configPath: string) => { [key: string]: any } | Error;

interface Dictionary<T = any> {
  [key: string]: T;
}

Type Specification Options

Boolean Options

Specify which keys should be treated as boolean flags.

const result = parser(['--debug', '--verbose', 'false'], {
  boolean: ['debug', 'verbose']
});
console.log(result);
// Output: { _: [], debug: true, verbose: true }
// Note: 'false' is treated as a positional argument, not a boolean value

String Options

Force keys to be treated as strings, preventing automatic number conversion.

const result = parser(['--version', '1.0.0', '--port', '3000'], {
  string: ['version', 'port']
});
console.log(result);
// Output: { _: [], version: '1.0.0', port: '3000' }
// Without string option, port would become number 3000

Number Options

Force keys to be treated as numbers.

const result = parser(['--timeout', '30s', '--count', '042'], {
  number: ['timeout', 'count']
});
console.log(result);
// Output: { _: [], timeout: NaN, count: 42 }
// '30s' cannot be parsed as number, becomes NaN
// '042' is parsed as decimal 42, not octal

Array Options

Specify keys that should be treated as arrays, with optional type coercion.

// Simple array specification
const simple = parser(['--files', 'a.txt', '--files', 'b.txt'], {
  array: ['files']
});
console.log(simple);
// Output: { _: [], files: ['a.txt', 'b.txt'] }

// Array with type specification
const typed = parser(['--ports', '3000', '--ports', '4000', '--debug', '--debug'], {
  array: [
    { key: 'ports', number: true },
    { key: 'debug', boolean: true }
  ]
});
console.log(typed);
// Output: { _: [], ports: [3000, 4000], debug: [true, true] }

Alias Options

Define alternative names for options.

const result = parser(['-v', '--name', 'Alice', '-p', '8080'], {
  alias: {
    verbose: ['v'],
    name: ['n', 'user'],
    port: 'p'  // Single alias can be string instead of array
  }
});
console.log(result);
// Output: { _: [], v: true, verbose: true, name: 'Alice', n: 'Alice', user: 'Alice', p: 8080, port: 8080 }

Default Values

Provide default values for options not specified on command line.

const result = parser(['--name', 'Alice'], {
  default: {
    port: 3000,
    debug: false,
    env: 'development',
    name: 'Anonymous'  // Overridden by command line value
  }
});
console.log(result);
// Output: { _: [], name: 'Alice', port: 3000, debug: false, env: 'development' }

Advanced Options

Count Options

Specify keys that should count occurrences (like -vvv for verbosity levels).

const result = parser(['-v', '-v', '-v', '--debug', '--debug'], {
  count: ['v', 'debug']
});
console.log(result);
// Output: { _: [], v: 3, debug: 2 }

Coerce Options

Apply custom transformation functions to argument values.

const result = parser(['--date', '2023-12-25', '--tags', 'dev,test,prod'], {
  coerce: {
    date: (arg: string) => new Date(arg),
    tags: (arg: string) => arg.split(',')
  }
});
console.log(result);
// Output: { _: [], date: Date('2023-12-25'), tags: ['dev', 'test', 'prod'] }

Narg Options

Specify that options should consume multiple following arguments.

const result = parser(['--point', '10', '20', '--color', 'red', 'green', 'blue'], {
  narg: {
    point: 2,
    color: 3
  }
});
console.log(result);
// Output: { _: [], point: [10, 20], color: ['red', 'green', 'blue'] }

Normalize Options

Apply path normalization to specified keys (Node.js only).

const result = parser(['--input', '../docs/./file.txt', '--output', '/tmp//result.txt'], {
  normalize: ['input', 'output']
});
console.log(result);
// Output: { _: [], input: '../docs/file.txt', output: '/tmp/result.txt' }

Configuration Integration

Parser options work alongside configuration options:

const result = parser(['--foo-bar', '42', '--items', 'a', '--items', 'b'], {
  string: ['foo-bar'],  // Prevent number conversion
  array: ['items'],     // Force array creation
  configuration: {
    'camel-case-expansion': true,  // Enable camelCase aliases
    'duplicate-arguments-array': true  // Enable array creation for duplicates
  }
});
console.log(result);
// Output: { _: [], 'foo-bar': '42', fooBar: '42', items: ['a', 'b'] }

Environment Variable Parsing

Parse environment variables with a specified prefix:

// Assuming environment variables: MYAPP_PORT=8080, MYAPP_DEBUG=true
const result = parser(['--name', 'test'], {
  envPrefix: 'MYAPP',
  boolean: ['debug'],
  number: ['port']
});
console.log(result);
// Output: { _: [], name: 'test', port: 8080, debug: true }

Configuration File Support

Load configuration from files:

// Basic config file support
const result = parser(['--config', 'app.json', '--debug'], {
  config: ['config'],
  boolean: ['debug']
});

// Advanced config with custom loader
const advanced = parser(['--settings', 'custom.conf'], {
  config: {
    settings: (configPath: string) => {
      // Custom configuration loader
      const content = fs.readFileSync(configPath, 'utf8');
      return parseCustomFormat(content);
    }
  }
});

Configuration Objects

Provide pre-loaded configuration objects:

const result = parser(['--name', 'CLI-value'], {
  configObjects: [
    { port: 3000, debug: true },
    { env: 'production', timeout: 30 }
  ],
  default: {
    name: 'default-name'
  }
});
console.log(result);
// Output: { _: [], name: 'CLI-value', port: 3000, debug: true, env: 'production', timeout: 30 }
// CLI arguments override config objects, which override defaults

Complex Example

Combining multiple parser options:

const result = parser([
  '--env', 'production',
  '--ports', '3000', '--ports', '4000',
  '-v', '-v',
  '--database-url', 'postgres://localhost/app',
  '--feature-flags', 'feature1,feature2'
], {
  alias: {
    verbose: ['v'],
    env: ['e'],
    'database-url': ['db']
  },
  array: [
    { key: 'ports', number: true }
  ],
  count: ['verbose'],
  string: ['env', 'database-url'],
  coerce: {
    'feature-flags': (arg: string) => arg.split(',')
  },
  default: {
    env: 'development',
    verbose: 0,
    'feature-flags': []
  },
  configuration: {
    'camel-case-expansion': true,
    'strip-dashed': false
  }
});

console.log(result);
// Complex output with all transformations applied

Install with Tessl CLI

npx tessl i tessl/npm-yargs-parser

docs

configuration.md

core-parsing.md

detailed-parsing.md

index.md

parser-options.md

string-utilities.md

tokenize-arg-string.md

tile.json