code:
# 0.9.0
- update dependencies, in particular `levn` and `type-check` - this could affect behaviour of argument parsing

# 0.8.3
- changes dependency from `wordwrap` to `word-wrap` due to license issue
- update dependencies

# 0.8.2
- fix bug #18 - detect missing value when flag is last item
- update dependencies

# 0.8.1
- update `fast-levenshtein` dependency

# 0.8.0
- update `levn` dependency - supplying a float value to an option with type `Int` now throws an error, instead of silently converting to an `Int`

# 0.7.1
- fix bug with use of `defaults` and `concatRepeatedArrays` or `mergeRepeatedObjects`

# 0.7.0
- added `concatrepeatedarrays` option: `oneValuePerFlag`, only allows one array value per flag
- added `typeAliases` option
- added `parseArgv` which takes an array and parses with the first two items sliced off
- changed enum help style
- bug fixes (#12)
- use of `concatRepeatedArrays` and `mergeRepeatedObjects` at the top level is deprecated, use it as either a per-option option, or set them in the `defaults` object to set them for all objects

# 0.6.0
- added `defaults` lib-option flag, allowing one to set default properties for all options
- added `concatRepeatedArrays` and `mergeRepeatedObjects` as option level properties, allowing you to turn this feature on for specific options only

# 0.5.0
- `Boolean` flags with `default: 'true'`, and no short aliases, will by default show the `--no` version in help

# 0.4.0
- add `mergeRepeatedObjects` setting

# 0.3.0
- add `concatRepeatedArrays` setting
- add `overrideRequired` option setting
- use just Levenshtein string compare algo rather than Levenshtein Damerau to due dependency license issue

# 0.2.2
- bug fixes

# 0.2.1
- improved interpolation
- added changelog

# 0.2.0
- add dependency checks to options - added `dependsOn` as an option property
- add interpolation for `prepend` and `append` text with new `generateHelp` option, `interpolate`

# 0.1.1
- update dependencies

# 0.1.0
- initial release


code:
# Optionator
<a name="optionator" />

Optionator is a JavaScript/Node.js option parsing and help generation library used by [eslint](http://eslint.org), [Grasp](http://graspjs.com), [LiveScript](http://livescript.net), [esmangle](https://github.com/estools/esmangle), [escodegen](https://github.com/estools/escodegen), and [many more](https://www.npmjs.com/browse/depended/optionator).

For an online demo, check out the [Grasp online demo](http://www.graspjs.com/#demo).

[About](#about) · [Usage](#usage) · [Settings Format](#settings-format) · [Argument Format](#argument-format)

## Why?
The  problem with other option parsers, such as `yargs` or `minimist`, is they just accept all input, valid or not.
With Optionator, if you mistype an option, it will give you an error (with a suggestion for what you meant).
If you give the wrong type of argument for an option, it will give you an error rather than supplying the wrong input to your application.

    $ cmd --halp
    Invalid option '--halp' - perhaps you meant '--help'?

    $ cmd --count str
    Invalid value for option 'count' - expected type Int, received value: str.

Other helpful features include reformatting the help text based on the size of the console, so that it fits even if the console is narrow, and accepting not just an array (eg. process.argv), but a string or object as well, making things like testing much easier.

## About
Optionator uses [type-check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) behind the scenes to cast and verify input according the specified types.

MIT license. Version 0.9.4

    npm install optionator

For updates on Optionator, [follow me on twitter](https://twitter.com/gkzahariev).

Optionator is a Node.js module, but can be used in the browser as well if packed with webpack/browserify.

## Usage
`require('optionator');` returns a function. It has one property, `VERSION`, the current version of the library as a string. This function is called with an object specifying your options and other information, see the [settings format section](#settings-format). This in turn returns an object with three properties, `parse`, `parseArgv`, `generateHelp`, and `generateHelpForOption`, which are all functions.

```js
var 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'
    }]
});

var options = optionator.parseArgv(process.argv);
if (options.help) {
    console.log(optionator.generateHelp());
}
...
```

### parse(input, parseOptions)
`parse` processes the `input` according to your settings, and returns an object with the results.

##### arguments
* input - `[String] | Object | String` - the input you wish to parse
* parseOptions - `{slice: Int}` - all options optional
    - `slice` specifies how much to slice away from the beginning if the input is an array or string - by default `0` for string, `2` for array (works with `process.argv`)

##### returns
`Object` - the parsed options, each key is a camelCase version of the option name (specified in dash-case), and each value is the processed value for that option. Positional values are in an array under the `_` key.

##### example
```js
parse(['node', 't.js', '--count', '2', 'positional']); // {count: 2, _: ['positional']}
parse('--count 2 positional');                         // {count: 2, _: ['positional']}
parse({count: 2, _:['positional']});                   // {count: 2, _: ['positional']}
```

### parseArgv(input)
`parseArgv` works exactly like `parse`, but only for array input and it slices off the first two elements.

##### arguments
* input - `[String]` - the input you wish to parse

##### returns
See "returns" section in "parse"

##### example
```js
parseArgv(process.argv);
```

### generateHelp(helpOptions)
`generateHelp` produces help text based on your settings.

##### arguments
* helpOptions - `{showHidden: Boolean, interpolate: Object}` - all options optional
    - `showHidden` specifies whether to show options with `hidden: true` specified, by default it is `false`
    - `interpolate` specify data to be interpolated in `prepend` and `append` text, `{{key}}` is the format - eg. `generateHelp({interpolate:{version: '0.4.2'}})`, will change this `append` text: `Version {{version}}` to `Version 0.4.2`

##### returns
`String` - the generated help text

##### example
```js
generateHelp(); /*
"Usage: cmd [options] positional

  -h, --help       displays help
  -c, --count Int  number of things

Version  1.0.0
"*/
```

### generateHelpForOption(optionName)
`generateHelpForOption` produces expanded help text for the specified with `optionName` option. If an `example` was specified for the option, it will be displayed,  and if a `longDescription` was specified, it will display that instead of the `description`.

##### arguments
* optionName - `String` - the name of the option to display

##### returns
`String` - the generated help text for the option

##### example
```js
generateHelpForOption('count'); /*
"-c, --count Int
description: number of things
example: cmd --count 2
"*/
```

## Settings Format
When your `require('optionator')`, you get a function that takes in a settings object. This object has the type:

    {
      prepend: String,
      append: String,
      options: [{heading: String} | {
        option: String,
        alias: [String] | String,
        type: String,
        enum: [String],
        default: String,
        restPositional: Boolean,
        required: Boolean,
        overrideRequired: Boolean,
        dependsOn: [String] | String,
        concatRepeatedArrays: Boolean | (Boolean, Object),
        mergeRepeatedObjects: Boolean,
        description: String,
        longDescription: String,
        example: [String] | String
      }],
      helpStyle: {
        aliasSeparator: String,
        typeSeparator: String,
        descriptionSeparator: String,
        initialIndent: Int,
        secondaryIndent: Int,
        maxPadFactor: Number
      },
      mutuallyExclusive: [[String | [String]]],
      concatRepeatedArrays: Boolean | (Boolean, Object), // deprecated, set in defaults object
      mergeRepeatedObjects: Boolean, // deprecated, set in defaults object
      positionalAnywhere: Boolean,
      typeAliases: Object,
      defaults: Object
    }

All of the properties are optional (the `Maybe` has been excluded for brevities sake), except for having either `heading: String` or `option: String` in each object in the `options` array.

### Top Level Properties
* `prepend` is an optional string to be placed before the options in the help text
* `append` is an optional string to be placed after the options in the help text
* `options` is a required array specifying your options and headings, the options and headings will be displayed in the order specified
* `helpStyle` is an optional object which enables you to change the default appearance of some aspects of the help text
* `mutuallyExclusive` is an optional array of arrays of either strings or arrays of strings. The top level array is a list of rules, each rule is a list of elements - each element can be either a string (the name of an option), or a list of strings (a group of option names) - there will be an error if more than one element is present
* `concatRepeatedArrays` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property
* `mergeRepeatedObjects` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property
* `positionalAnywhere` is an optional boolean (defaults to `true`) - when `true` it allows positional arguments anywhere, when `false`, all arguments after the first positional one are taken to be positional as well, even if they look like a flag. For example, with `positionalAnywhere: false`, the arguments `--flag --boom 12 --crack` would have two positional arguments: `12` and `--crack`
* `typeAliases` is an optional object, it allows you to set aliases for types, eg. `{Path: 'String'}` would allow you to use the type `Path` as an alias for the type `String`
* `defaults` is an optional object following the option properties format, which specifies default values for all options. A default will be overridden if manually set. For example, you can do `default: { type: "String" }` to set the default type of all options to `String`, and then override that default in an individual option by setting the `type` property

#### Heading Properties
* `heading` a required string, the name of the heading

#### Option Properties
* `option` the required name of the option - use dash-case, without the leading dashes
* `alias` is an optional string or array of strings which specify any aliases for the option
* `type` is a required string in the [type check](https://github.com/gkz/type-check) [format](https://github.com/gkz/type-check#type-format), this will be used to cast the inputted value and validate it
* `enum` is an optional array of strings, each string will be parsed by [levn](https://github.com/gkz/levn) - the argument value must be one of the resulting values - each potential value must validate against the specified `type`
* `default` is a optional string, which will be parsed by [levn](https://github.com/gkz/levn) and used as the default value if none is set - the value must validate against the specified `type`
* `restPositional` is an optional boolean - if set to `true`, everything after the option will be taken to be a positional argument, even if it looks like a named argument
* `required` is an optional boolean - if set to `true`, the option parsing will fail if the option is not defined
* `overrideRequired` is a optional boolean - if set to `true` and the option is used, and there is another option which is required but not set, it will override the need for the required option and there will be no error - this is useful if you have required options and want to use `--help` or `--version` flags
* `concatRepeatedArrays` is an optional boolean or tuple with boolean and options object (defaults to `false`) - when set to `true` and an option contains an array value and is repeated, the subsequent values for the flag will be appended rather than overwriting the original value - eg. option `g` of type `[String]`: `-g a -g b -g c,d` will result in `['a','b','c','d']`

 You can supply an options object by giving the following value: `[true, options]`. The one currently supported option is `oneValuePerFlag`, this only allows one array value per flag. This is useful if your potential values contain a comma.
* `mergeRepeatedObjects` is an optional boolean (defaults to `false`) - when set to `true` and an option contains an object value and is repeated, the subsequent values for the flag will be merged rather than overwriting the original value - eg. option `g` of type `Object`: `-g a:1 -g b:2 -g c:3,d:4` will result in `{a: 1, b: 2, c: 3, d: 4}`
* `dependsOn` is an optional string or array of strings - if simply a string (the name of another option), it will make sure that that other option is set, if an array of strings, depending on whether `'and'` or `'or'` is first, it will either check whether all (`['and', 'option-a', 'option-b']`), or at least one (`['or', 'option-a', 'option-b']`) other options are set
* `description` is an optional string, which will be displayed next to the option in the help text
* `longDescription` is an optional string, it will be displayed instead of the `description` when `generateHelpForOption` is used
* `example` is an optional string or array of strings with example(s) for the option - these will be displayed when `generateHelpForOption` is used

#### Help Style Properties
* `aliasSeparator` is an optional string, separates multiple names from each other - default: ' ,'
* `typeSeparator` is an optional string, separates the type from the names - default: ' '
* `descriptionSeparator` is an optional string , separates the description from the padded name and type - default: '  '
* `initialIndent` is an optional int - the amount of indent for options - default: 2
* `secondaryIndent` is an optional int - the amount of indent if wrapped fully (in addition to the initial indent) - default: 4
* `maxPadFactor` is an optional number - affects the default level of padding for the names/type, it is multiplied by the average of the length of the names/type - default: 1.5

## Argument Format
At the highest level there are two types of arguments: named, and positional.

Name arguments of any length are prefixed with `--` (eg. `--go`), and those of one character may be prefixed with either `--` or `-` (eg. `-g`).

There are two types of named arguments: boolean flags (eg. `--problemo`, `-p`) which take no value and result in a `true` if they are present, the falsey `undefined` if they are not present, or `false` if present and explicitly prefixed with `no` (eg. `--no-problemo`). Named arguments with values (eg. `--tseries 800`, `-t 800`) are the other type. If the option has a type `Boolean` it will automatically be made into a boolean flag. Any other type results in a named argument that takes a value.

For more information about how to properly set types to get the value you want, take a look at the [type check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) pages.

You can group single character arguments that use a single `-`, however all except the last must be boolean flags (which take no value). The last may be a boolean flag, or an argument which takes a value - eg. `-ba 2` is equivalent to `-b -a 2`.

Positional arguments are all those values which do not fall under the above - they can be anywhere, not just at the end. For example, in `cmd -b one -a 2 two` where `b` is a boolean flag, and `a` has the type `Number`, there are two positional arguments, `one` and `two`.

Everything after an `--` is positional, even if it looks like a named argument.

You may optionally use `=` to separate option names from values, for example: `--count=2`.

If you specify the option `NUM`, then any argument using a single `-` followed by a number will be valid and will set the value of `NUM`. Eg. `-2` will be parsed into `NUM: 2`.

If duplicate named arguments are present, the last one will be taken.

## Technical About
`optionator` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [levn](https://github.com/gkz/levn) to cast arguments to their specified type, and uses [type-check](https://github.com/gkz/type-check) to validate values. It also uses the [prelude.ls](http://preludels.com/) library.

license: mit


code:
// Generated by LiveScript 1.6.0
(function(){
  var ref$, id, find, sort, min, max, map, unlines, nameToRaw, dasherize, naturalJoin, wordWrap, wordwrap, getPreText, setHelpStyleDefaults, generateHelpForOption, generateHelp;
  ref$ = require('prelude-ls'), id = ref$.id, find = ref$.find, sort = ref$.sort, min = ref$.min, max = ref$.max, map = ref$.map, unlines = ref$.unlines;
  ref$ = require('./util'), nameToRaw = ref$.nameToRaw, dasherize = ref$.dasherize, naturalJoin = ref$.naturalJoin;
  wordWrap = require('word-wrap');
  wordwrap = function(a, b){
    var ref$, indent, width;
    ref$ = b === undefined
      ? ['', a - 1]
      : [repeatString$(' ', a), b - a - 1], indent = ref$[0], width = ref$[1];
    return function(text){
      return wordWrap(text, {
        indent: indent,
        width: width,
        trim: true
      });
    };
  };
  getPreText = function(option, arg$, maxWidth){
    var mainName, shortNames, ref$, longNames, type, description, aliasSeparator, typeSeparator, initialIndent, names, namesString, namesStringLen, typeSeparatorString, typeSeparatorStringLen, wrap;
    mainName = option.option, shortNames = (ref$ = option.shortNames) != null
      ? ref$
      : [], longNames = (ref$ = option.longNames) != null
      ? ref$
      : [], type = option.type, description = option.description;
    aliasSeparator = arg$.aliasSeparator, typeSeparator = arg$.typeSeparator, initialIndent = arg$.initialIndent;
    if (option.negateName) {
      mainName = "no-" + mainName;
      if (longNames) {
        longNames = map(function(it){
          return "no-" + it;
        }, longNames);
      }
    }
    names = mainName.length === 1
      ? [mainName].concat(shortNames, longNames)
      : shortNames.concat([mainName], longNames);
    namesString = map(nameToRaw, names).join(aliasSeparator);
    namesStringLen = namesString.length;
    typeSeparatorString = mainName === 'NUM' ? '::' : typeSeparator;
    typeSeparatorStringLen = typeSeparatorString.length;
    if (maxWidth != null && !option.boolean && initialIndent + namesStringLen + typeSeparatorStringLen + type.length > maxWidth) {
      wrap = wordwrap(initialIndent + namesStringLen + typeSeparatorStringLen, maxWidth);
      return namesString + "" + typeSeparatorString + wrap(type).replace(/^\s+/, '');
    } else {
      return namesString + "" + (option.boolean
        ? ''
        : typeSeparatorString + "" + type);
    }
  };
  setHelpStyleDefaults = function(helpStyle){
    helpStyle.aliasSeparator == null && (helpStyle.aliasSeparator = ', ');
    helpStyle.typeSeparator == null && (helpStyle.typeSeparator = ' ');
    helpStyle.descriptionSeparator == null && (helpStyle.descriptionSeparator = '  ');
    helpStyle.initialIndent == null && (helpStyle.initialIndent = 2);
    helpStyle.secondaryIndent == null && (helpStyle.secondaryIndent = 4);
    helpStyle.maxPadFactor == null && (helpStyle.maxPadFactor = 1.5);
  };
  generateHelpForOption = function(getOption, arg$){
    var stdout, helpStyle, ref$;
    stdout = arg$.stdout, helpStyle = (ref$ = arg$.helpStyle) != null
      ? ref$
      : {};
    setHelpStyleDefaults(helpStyle);
    return function(optionName){
      var maxWidth, wrap, option, e, pre, defaultString, restPositionalString, description, fullDescription, that, preDescription, descriptionString, exampleString, examples, seperator;
      maxWidth = stdout != null && stdout.isTTY ? stdout.columns - 1 : null;
      wrap = maxWidth ? wordwrap(maxWidth) : id;
      try {
        option = getOption(dasherize(optionName));
      } catch (e$) {
        e = e$;
        return e.message;
      }
      pre = getPreText(option, helpStyle);
      defaultString = option['default'] && !option.negateName ? "\ndefault: " + option['default'] : '';
      restPositionalString = option.restPositional ? 'Everything after this option is considered a positional argument, even if it looks like an option.' : '';
      description = option.longDescription || option.description && sentencize(option.description);
      fullDescription = description && restPositionalString
        ? description + " " + restPositionalString
        : (that = description || restPositionalString) ? that : '';
      preDescription = 'description:';
      descriptionString = !fullDescription
        ? ''
        : maxWidth && fullDescription.length - 1 - preDescription.length > maxWidth
          ? "\n" + preDescription + "\n" + wrap(fullDescription)
          : "\n" + preDescription + " " + fullDescription;
      exampleString = (that = option.example) ? (examples = [].concat(that), examples.length > 1
        ? "\nexamples:\n" + unlines(examples)
        : "\nexample: " + examples[0]) : '';
      seperator = defaultString || descriptionString || exampleString ? "\n" + repeatString$('=', pre.length) : '';
      return pre + "" + seperator + defaultString + descriptionString + exampleString;
    };
  };
  generateHelp = function(arg$){
    var options, prepend, append, helpStyle, ref$, stdout, aliasSeparator, typeSeparator, descriptionSeparator, maxPadFactor, initialIndent, secondaryIndent;
    options = arg$.options, prepend = arg$.prepend, append = arg$.append, helpStyle = (ref$ = arg$.helpStyle) != null
      ? ref$
      : {}, stdout = arg$.stdout;
    setHelpStyleDefaults(helpStyle);
    aliasSeparator = helpStyle.aliasSeparator, typeSeparator = helpStyle.typeSeparator, descriptionSeparator = helpStyle.descriptionSeparator, maxPadFactor = helpStyle.maxPadFactor, initialIndent = helpStyle.initialIndent, secondaryIndent = helpStyle.secondaryIndent;
    return function(arg$){
      var ref$, showHidden, interpolate, maxWidth, output, out, data, optionCount, totalPreLen, preLens, i$, len$, item, that, pre, descParts, desc, preLen, sortedPreLens, maxPreLen, preLenMean, x, padAmount, descSepLen, fullWrapCount, partialWrapCount, descLen, totalLen, initialSpace, wrapAllFull, i, wrap;
      ref$ = arg$ != null
        ? arg$
        : {}, showHidden = ref$.showHidden, interpolate = ref$.interpolate;
      maxWidth = stdout != null && stdout.isTTY ? stdout.columns - 1 : null;
      output = [];
      out = function(it){
        return output.push(it != null ? it : '');
      };
      if (prepend) {
        out(interpolate ? interp(prepend, interpolate) : prepend);
        out();
      }
      data = [];
      optionCount = 0;
      totalPreLen = 0;
      preLens = [];
      for (i$ = 0, len$ = (ref$ = options).length; i$ < len$; ++i$) {
        item = ref$[i$];
        if (showHidden || !item.hidden) {
          if (that = item.heading) {
            data.push({
              type: 'heading',
              value: that
            });
          } else {
            pre = getPreText(item, helpStyle, maxWidth);
            descParts = [];
            if ((that = item.description) != null) {
              descParts.push(that);
            }
            if (that = item['enum']) {
              descParts.push("either: " + naturalJoin(that));
            }
            if (item['default'] && !item.negateName) {
              descParts.push("default: " + item['default']);
            }
            desc = descParts.join(' - ');
            data.push({
              type: 'option',
              pre: pre,
              desc: desc,
              descLen: desc.length
            });
            preLen = pre.length;
            optionCount++;
            totalPreLen += preLen;
            preLens.push(preLen);
          }
        }
      }
      sortedPreLens = sort(preLens);
      maxPreLen = sortedPreLens[sortedPreLens.length - 1];
      preLenMean = initialIndent + totalPreLen / optionCount;
      x = optionCount > 2 ? min(preLenMean * maxPadFactor, maxPreLen) : maxPreLen;
      for (i$ = sortedPreLens.length - 1; i$ >= 0; --i$) {
        preLen = sortedPreLens[i$];
        if (preLen <= x) {
          padAmount = preLen;
          break;
        }
      }
      descSepLen = descriptionSeparator.length;
      if (maxWidth != null) {
        fullWrapCount = 0;
        partialWrapCount = 0;
        for (i$ = 0, len$ = data.length; i$ < len$; ++i$) {
          item = data[i$];
          if (item.type === 'option') {
            pre = item.pre, desc = item.desc, descLen = item.descLen;
            if (descLen === 0) {
              item.wrap = 'none';
            } else {
              preLen = max(padAmount, pre.length) + initialIndent + descSepLen;
              totalLen = preLen + descLen;
              if (totalLen > maxWidth) {
                if (descLen / 2.5 > maxWidth - preLen) {
                  fullWrapCount++;
                  item.wrap = 'full';
                } else {
                  partialWrapCount++;
                  item.wrap = 'partial';
                }
              } else {
                item.wrap = 'none';
              }
            }
          }
        }
      }
      initialSpace = repeatString$(' ', initialIndent);
      wrapAllFull = optionCount > 1 && fullWrapCount + partialWrapCount * 0.5 > optionCount * 0.5;
      for (i$ = 0, len$ = data.length; i$ < len$; ++i$) {
        i = i$;
        item = data[i$];
        if (item.type === 'heading') {
          if (i !== 0) {
            out();
          }
          out(item.value + ":");
        } else {
          pre = item.pre, desc = item.desc, descLen = item.descLen, wrap = item.wrap;
          if (maxWidth != null) {
            if (wrapAllFull || wrap === 'full') {
              wrap = wordwrap(initialIndent + secondaryIndent, maxWidth);
              out(initialSpace + "" + pre + "\n" + wrap(desc));
              continue;
            } else if (wrap === 'partial') {
              wrap = wordwrap(initialIndent + descSepLen + max(padAmount, pre.length), maxWidth);
              out(initialSpace + "" + pad(pre, padAmount) + descriptionSeparator + wrap(desc).replace(/^\s+/, ''));
              continue;
            }
          }
          if (descLen === 0) {
            out(initialSpace + "" + pre);
          } else {
            out(initialSpace + "" + pad(pre, padAmount) + descriptionSeparator + desc);
          }
        }
      }
      if (append) {
        out();
        out(interpolate ? interp(append, interpolate) : append);
      }
      return unlines(output);
    };
  };
  function pad(str, num){
    var len, padAmount;
    len = str.length;
    padAmount = num - len;
    return str + "" + repeatString$(' ', padAmount > 0 ? padAmount : 0);
  }
  function sentencize(str){
    var first, rest, period;
    first = str.charAt(0).toUpperCase();
    rest = str.slice(1);
    period = /[\.!\?]$/.test(str) ? '' : '.';
    return first + "" + rest + period;
  }
  function interp(string, object){
    return string.replace(/{{([a-zA-Z$_][a-zA-Z$_0-9]*)}}/g, function(arg$, key){
      var ref$;
      return (ref$ = object[key]) != null
        ? ref$
        : "{{" + key + "}}";
    });
  }
  module.exports = {
    generateHelp: generateHelp,
    generateHelpForOption: generateHelpForOption
  };
  function repeatString$(str, n){
    for (var r = ''; n > 0; (n >>= 1) && (str += str)) if (n & 1) r += str;
    return r;
  }
}).call(this);


code:
// Generated by LiveScript 1.6.0
(function(){
  var VERSION, ref$, id, map, compact, any, groupBy, partition, chars, isItNaN, keys, Obj, camelize, deepIs, closestString, nameToRaw, dasherize, naturalJoin, generateHelp, generateHelpForOption, parsedTypeCheck, parseType, parseLevn, camelizeKeys, parseString, main, toString$ = {}.toString, slice$ = [].slice, arrayFrom$ = Array.from || function(x){return slice$.call(x);};
  VERSION = '0.9.4';
  ref$ = require('prelude-ls'), id = ref$.id, map = ref$.map, compact = ref$.compact, any = ref$.any, groupBy = ref$.groupBy, partition = ref$.partition, chars = ref$.chars, isItNaN = ref$.isItNaN, keys = ref$.keys, Obj = ref$.Obj, camelize = ref$.camelize;
  deepIs = require('deep-is');
  ref$ = require('./util'), closestString = ref$.closestString, nameToRaw = ref$.nameToRaw, dasherize = ref$.dasherize, naturalJoin = ref$.naturalJoin;
  ref$ = require('./help'), generateHelp = ref$.generateHelp, generateHelpForOption = ref$.generateHelpForOption;
  ref$ = require('type-check'), parsedTypeCheck = ref$.parsedTypeCheck, parseType = ref$.parseType;
  parseLevn = require('levn').parsedTypeParse;
  camelizeKeys = function(obj){
    var key, value, resultObj$ = {};
    for (key in obj) {
      value = obj[key];
      resultObj$[camelize(key)] = value;
    }
    return resultObj$;
  };
  parseString = function(string){
    var assignOpt, regex, replaceRegex, result;
    assignOpt = '--?[a-zA-Z][-a-z-A-Z0-9]*=';
    regex = RegExp('(?:' + assignOpt + ')?(?:\'(?:\\\\\'|[^\'])+\'|"(?:\\\\"|[^"])+")|[^\'"\\s]+', 'g');
    replaceRegex = RegExp('^(' + assignOpt + ')?[\'"]([\\s\\S]*)[\'"]$');
    result = map(function(it){
      return it.replace(replaceRegex, '$1$2');
    }, string.match(regex) || []);
    return result;
  };
  main = function(libOptions){
    var opts, defaults, required, traverse, getOption, parse;
    opts = {};
    defaults = {};
    required = [];
    if (toString$.call(libOptions.stdout).slice(8, -1) === 'Undefined') {
      libOptions.stdout = process.stdout;
    }
    libOptions.positionalAnywhere == null && (libOptions.positionalAnywhere = true);
    libOptions.typeAliases == null && (libOptions.typeAliases = {});
    libOptions.defaults == null && (libOptions.defaults = {});
    if (libOptions.concatRepeatedArrays != null) {
      libOptions.defaults.concatRepeatedArrays = libOptions.concatRepeatedArrays;
    }
    if (libOptions.mergeRepeatedObjects != null) {
      libOptions.defaults.mergeRepeatedObjects = libOptions.mergeRepeatedObjects;
    }
    traverse = function(options){
      var i$, len$, option, name, k, ref$, v, type, that, e, parsedPossibilities, parsedType, j$, len1$, possibility, rawDependsType, dependsOpts, dependsType, cra, alias, shortNames, longNames;
      if (toString$.call(options).slice(8, -1) !== 'Array') {
        throw new Error('No options defined.');
      }
      for (i$ = 0, len$ = options.length; i$ < len$; ++i$) {
        option = options[i$];
        if (option.heading == null) {
          name = option.option;
          if (opts[name] != null) {
            throw new Error("Option '" + name + "' already defined.");
          }
          for (k in ref$ = libOptions.defaults) {
            v = ref$[k];
            option[k] == null && (option[k] = v);
          }
          if (option.type === 'Boolean') {
            option.boolean == null && (option.boolean = true);
          }
          if (option.parsedType == null) {
            if (!option.type) {
              throw new Error("No type defined for option '" + name + "'.");
            }
            try {
              type = (that = libOptions.typeAliases[option.type]) != null
                ? that
                : option.type;
              option.parsedType = parseType(type);
            } catch (e$) {
              e = e$;
              throw new Error("Option '" + name + "': Error parsing type '" + option.type + "': " + e.message);
            }
          }
          if (option['default']) {
            try {
              defaults[name] = parseLevn(option.parsedType, option['default']);
            } catch (e$) {
              e = e$;
              throw new Error("Option '" + name + "': Error parsing default value '" + option['default'] + "' for type '" + option.type + "': " + e.message);
            }
          }
          if (option['enum'] && !option.parsedPossiblities) {
            parsedPossibilities = [];
            parsedType = option.parsedType;
            for (j$ = 0, len1$ = (ref$ = option['enum']).length; j$ < len1$; ++j$) {
              possibility = ref$[j$];
              try {
                parsedPossibilities.push(parseLevn(parsedType, possibility));
              } catch (e$) {
                e = e$;
                throw new Error("Option '" + name + "': Error parsing enum value '" + possibility + "' for type '" + option.type + "': " + e.message);
              }
            }
            option.parsedPossibilities = parsedPossibilities;
          }
          if (that = option.dependsOn) {
            if (that.length) {
              ref$ = [].concat(option.dependsOn), rawDependsType = ref$[0], dependsOpts = slice$.call(ref$, 1);
              dependsType = rawDependsType.toLowerCase();
              if (dependsOpts.length) {
                if (dependsType === 'and' || dependsType === 'or') {
                  option.dependsOn = [dependsType].concat(arrayFrom$(dependsOpts));
                } else {
                  throw new Error("Option '" + name + "': If you have more than one dependency, you must specify either 'and' or 'or'");
                }
              } else {
                if ((ref$ = dependsType.toLowerCase()) === 'and' || ref$ === 'or') {
                  option.dependsOn = null;
                } else {
                  option.dependsOn = ['and', rawDependsType];
                }
              }
            } else {
              option.dependsOn = null;
            }
          }
          if (option.required) {
            required.push(name);
          }
          opts[name] = option;
          if (option.concatRepeatedArrays != null) {
            cra = option.concatRepeatedArrays;
            if ('Boolean' === toString$.call(cra).slice(8, -1)) {
              option.concatRepeatedArrays = [cra, {}];
            } else if (cra.length === 1) {
              option.concatRepeatedArrays = [cra[0], {}];
            } else if (cra.length !== 2) {
              throw new Error("Invalid setting for concatRepeatedArrays");
            }
          }
          if (option.alias || option.aliases) {
            if (name === 'NUM') {
              throw new Error("-NUM option can't have aliases.");
            }
            if (option.alias) {
              option.aliases == null && (option.aliases = [].concat(option.alias));
            }
            for (j$ = 0, len1$ = (ref$ = option.aliases).length; j$ < len1$; ++j$) {
              alias = ref$[j$];
              if (opts[alias] != null) {
                throw new Error("Option '" + alias + "' already defined.");
              }
              opts[alias] = option;
            }
            ref$ = partition(fn$, option.aliases), shortNames = ref$[0], longNames = ref$[1];
            option.shortNames == null && (option.shortNames = shortNames);
            option.longNames == null && (option.longNames = longNames);
          }
          if ((!option.aliases || option.shortNames.length === 0) && option.type === 'Boolean' && option['default'] === 'true') {
            option.negateName = true;
          }
        }
      }
      function fn$(it){
        return it.length === 1;
      }
    };
    traverse(libOptions.options);
    getOption = function(name){
      var opt, possiblyMeant;
      opt = opts[name];
      if (opt == null) {
        possiblyMeant = closestString(keys(opts), name);
        throw new Error("Invalid option '" + nameToRaw(name) + "'" + (possiblyMeant ? " - perhaps you meant '" + nameToRaw(possiblyMeant) + "'?" : '.'));
      }
      return opt;
    };
    parse = function(input, arg$){
      var slice, obj, positional, restPositional, overrideRequired, prop, setValue, setDefaults, checkRequired, mutuallyExclusiveError, checkMutuallyExclusive, checkDependency, checkDependencies, checkProp, args, key, value, option, ref$, i$, len$, arg, that, result, short, argName, usingAssign, val, flags, len, j$, len1$, i, flag, opt, name, valPrime, negated, noedName;
      slice = (arg$ != null
        ? arg$
        : {}).slice;
      obj = {};
      positional = [];
      restPositional = false;
      overrideRequired = false;
      prop = null;
      setValue = function(name, value){
        var opt, val, cra, e, currentType;
        opt = getOption(name);
        if (opt.boolean) {
          val = value;
        } else {
          try {
            cra = opt.concatRepeatedArrays;
            if (cra != null && cra[0] && cra[1].oneValuePerFlag && opt.parsedType.length === 1 && opt.parsedType[0].structure === 'array') {
              val = [parseLevn(opt.parsedType[0].of, value)];
            } else {
              val = parseLevn(opt.parsedType, value);
            }
          } catch (e$) {
            e = e$;
            throw new Error("Invalid value for option '" + name + "' - expected type " + opt.type + ", received value: " + value + ".");
          }
          if (opt['enum'] && !any(function(it){
            return deepIs(it, val);
          }, opt.parsedPossibilities)) {
            throw new Error("Option " + name + ": '" + val + "' not one of " + naturalJoin(opt['enum']) + ".");
          }
        }
        currentType = toString$.call(obj[name]).slice(8, -1);
        if (obj[name] != null) {
          if (opt.concatRepeatedArrays != null && opt.concatRepeatedArrays[0] && currentType === 'Array') {
            obj[name] = obj[name].concat(val);
          } else if (opt.mergeRepeatedObjects && currentType === 'Object') {
            import$(obj[name], val);
          } else {
            obj[name] = val;
          }
        } else {
          obj[name] = val;
        }
        if (opt.restPositional) {
          restPositional = true;
        }
        if (opt.overrideRequired) {
          overrideRequired = true;
        }
      };
      setDefaults = function(){
        var name, ref$, value;
        for (name in ref$ = defaults) {
          value = ref$[name];
          if (obj[name] == null) {
            obj[name] = value;
          }
        }
      };
      checkRequired = function(){
        var i$, ref$, len$, name;
        if (overrideRequired) {
          return;
        }
        for (i$ = 0, len$ = (ref$ = required).length; i$ < len$; ++i$) {
          name = ref$[i$];
          if (!obj[name]) {
            throw new Error("Option " + nameToRaw(name) + " is required.");
          }
        }
      };
      mutuallyExclusiveError = function(first, second){
        throw new Error("The options " + nameToRaw(first) + " and " + nameToRaw(second) + " are mutually exclusive - you cannot use them at the same time.");
      };
      checkMutuallyExclusive = function(){
        var rules, i$, len$, rule, present, j$, len1$, element, k$, len2$, opt;
        rules = libOptions.mutuallyExclusive;
        if (!rules) {
          return;
        }
        for (i$ = 0, len$ = rules.length; i$ < len$; ++i$) {
          rule = rules[i$];
          present = null;
          for (j$ = 0, len1$ = rule.length; j$ < len1$; ++j$) {
            element = rule[j$];
            if (toString$.call(element).slice(8, -1) === 'Array') {
              for (k$ = 0, len2$ = element.length; k$ < len2$; ++k$) {
                opt = element[k$];
                if (opt in obj) {
                  if (present != null) {
                    mutuallyExclusiveError(present, opt);
                  } else {
                    present = opt;
                    break;
                  }
                }
              }
            } else {
              if (element in obj) {
                if (present != null) {
                  mutuallyExclusiveError(present, element);
                } else {
                  present = element;
                }
              }
            }
          }
        }
      };
      checkDependency = function(option){
        var dependsOn, type, targetOptionNames, i$, len$, targetOptionName, targetOption;
        dependsOn = option.dependsOn;
        if (!dependsOn || option.dependenciesMet) {
          return true;
        }
        type = dependsOn[0], targetOptionNames = slice$.call(dependsOn, 1);
        for (i$ = 0, len$ = targetOptionNames.length; i$ < len$; ++i$) {
          targetOptionName = targetOptionNames[i$];
          targetOption = obj[targetOptionName];
          if (targetOption && checkDependency(targetOption)) {
            if (type === 'or') {
              return true;
            }
          } else if (type === 'and') {
            throw new Error("The option '" + option.option + "' did not have its dependencies met.");
          }
        }
        if (type === 'and') {
          return true;
        } else {
          throw new Error("The option '" + option.option + "' did not meet any of its dependencies.");
        }
      };
      checkDependencies = function(){
        var name;
        for (name in obj) {
          checkDependency(opts[name]);
        }
      };
      checkProp = function(){
        if (prop) {
          throw new Error("Value for '" + prop + "' of type '" + getOption(prop).type + "' required.");
        }
      };
      switch (toString$.call(input).slice(8, -1)) {
      case 'String':
        args = parseString(input.slice(slice != null ? slice : 0));
        break;
      case 'Array':
        args = input.slice(slice != null ? slice : 2);
        break;
      case 'Object':
        obj = {};
        for (key in input) {
          value = input[key];
          if (key !== '_') {
            option = getOption(dasherize(key));
            if (parsedTypeCheck(option.parsedType, value)) {
              obj[option.option] = value;
            } else {
              throw new Error("Option '" + option.option + "': Invalid type for '" + value + "' - expected type '" + option.type + "'.");
            }
          }
        }
        checkMutuallyExclusive();
        checkDependencies();
        setDefaults();
        checkRequired();
        return ref$ = camelizeKeys(obj), ref$._ = input._ || [], ref$;
      default:
        throw new Error("Invalid argument to 'parse': " + input + ".");
      }
      for (i$ = 0, len$ = args.length; i$ < len$; ++i$) {
        arg = args[i$];
        if (arg === '--') {
          restPositional = true;
        } else if (restPositional) {
          positional.push(arg);
        } else {
          if (that = arg.match(/^(--?)([a-zA-Z][-a-zA-Z0-9]*)(=)?(.*)?$/)) {
            result = that;
            checkProp();
            short = result[1].length === 1;
            argName = result[2];
            usingAssign = result[3] != null;
            val = result[4];
            if (usingAssign && val == null) {
              throw new Error("No value for '" + argName + "' specified.");
            }
            if (short) {
              flags = chars(argName);
              len = flags.length;
              for (j$ = 0, len1$ = flags.length; j$ < len1$; ++j$) {
                i = j$;
                flag = flags[j$];
                opt = getOption(flag);
                name = opt.option;
                if (restPositional) {
                  positional.push(flag);
                } else if (i === len - 1) {
                  if (usingAssign) {
                    valPrime = opt.boolean ? parseLevn([{
                      type: 'Boolean'
                    }], val) : val;
                    setValue(name, valPrime);
                  } else if (opt.boolean) {
                    setValue(name, true);
                  } else {
                    prop = name;
                  }
                } else if (opt.boolean) {
                  setValue(name, true);
                } else {
                  throw new Error("Can't set argument '" + flag + "' when not last flag in a group of short flags.");
                }
              }
            } else {
              negated = false;
              if (that = argName.match(/^no-(.+)$/)) {
                negated = true;
                noedName = that[1];
                opt = getOption(noedName);
              } else {
                opt = getOption(argName);
              }
              name = opt.option;
              if (opt.boolean) {
                valPrime = usingAssign ? parseLevn([{
                  type: 'Boolean'
                }], val) : true;
                if (negated) {
                  setValue(name, !valPrime);
                } else {
                  setValue(name, valPrime);
                }
              } else {
                if (negated) {
                  throw new Error("Only use 'no-' prefix for Boolean options, not with '" + noedName + "'.");
                }
                if (usingAssign) {
                  setValue(name, val);
                } else {
                  prop = name;
                }
              }
            }
          } else if (that = arg.match(/^-([0-9]+(?:\.[0-9]+)?)$/)) {
            opt = opts.NUM;
            if (!opt) {
              throw new Error('No -NUM option defined.');
            }
            setValue(opt.option, that[1]);
          } else {
            if (prop) {
              setValue(prop, arg);
              prop = null;
            } else {
              positional.push(arg);
              if (!libOptions.positionalAnywhere) {
                restPositional = true;
              }
            }
          }
        }
      }
      checkProp();
      checkMutuallyExclusive();
      checkDependencies();
      setDefaults();
      checkRequired();
      return ref$ = camelizeKeys(obj), ref$._ = positional, ref$;
    };
    return {
      parse: parse,
      parseArgv: function(it){
        return parse(it, {
          slice: 2
        });
      },
      generateHelp: generateHelp(libOptions),
      generateHelpForOption: generateHelpForOption(getOption, libOptions)
    };
  };
  main.VERSION = VERSION;
  module.exports = main;
  function import$(obj, src){
    var own = {}.hasOwnProperty;
    for (var key in src) if (own.call(src, key)) obj[key] = src[key];
    return obj;
  }
}).call(this);


code:
// Generated by LiveScript 1.6.0
(function(){
  var prelude, map, sortBy, fl, closestString, nameToRaw, dasherize, naturalJoin;
  prelude = require('prelude-ls'), map = prelude.map, sortBy = prelude.sortBy;
  fl = require('fast-levenshtein');
  closestString = function(possibilities, input){
    var distances, ref$, string, distance;
    if (!possibilities.length) {
      return;
    }
    distances = map(function(it){
      var ref$, longer, shorter;
      ref$ = input.length > it.length
        ? [input, it]
        : [it, input], longer = ref$[0], shorter = ref$[1];
      return {
        string: it,
        distance: fl.get(longer, shorter)
      };
    })(
    possibilities);
    ref$ = sortBy(function(it){
      return it.distance;
    }, distances)[0], string = ref$.string, distance = ref$.distance;
    return string;
  };
  nameToRaw = function(name){
    if (name.length === 1 || name === 'NUM') {
      return "-" + name;
    } else {
      return "--" + name;
    }
  };
  dasherize = function(string){
    if (/^[A-Z]/.test(string)) {
      return string;
    } else {
      return prelude.dasherize(string);
    }
  };
  naturalJoin = function(array){
    if (array.length < 3) {
      return array.join(' or ');
    } else {
      return array.slice(0, -1).join(', ') + ", or " + array[array.length - 1];
    }
  };
  module.exports = {
    closestString: closestString,
    nameToRaw: nameToRaw,
    dasherize: dasherize,
    naturalJoin: naturalJoin
  };
}).call(this);


optionator

author: George Zahariev <z@georgezahariev.com>

description: option parsing and help generation

keywords:
options
flags
option parsing
cli

files: lib README.md LICENSE

license: MIT

type: git

test: make test


code:
import {SpinnerName} from 'cli-spinners';

declare namespace ora {
	interface Spinner {
		readonly interval?: number;
		readonly frames: string[];
	}

	type Color =
		| 'black'
		| 'red'
		| 'green'
		| 'yellow'
		| 'blue'
		| 'magenta'
		| 'cyan'
		| 'white'
		| 'gray';

	type PrefixTextGenerator = () => string;

	interface Options {
		/**
		Text to display after the spinner.
		*/
		readonly text?: string;

		/**
		Text or a function that returns text to display before the spinner. No prefix text will be displayed if set to an empty string.
		*/
		readonly prefixText?: string | PrefixTextGenerator;

		/**
		Name of one of the provided spinners. See [`example.js`](https://github.com/BendingBender/ora/blob/main/example.js) in this repo if you want to test out different spinners. On Windows, it will always use the line spinner as the Windows command-line doesn't have proper Unicode support.

		@default 'dots'

		Or an object like:

		@example
		```
		{
			interval: 80, // Optional
			frames: ['-', '+', '-']
		}
		```
		*/
		readonly spinner?: SpinnerName | Spinner;

		/**
		Color of the spinner.

		@default 'cyan'
		*/
		readonly color?: Color;

		/**
		Set to `false` to stop Ora from hiding the cursor.

		@default true
		*/
		readonly hideCursor?: boolean;

		/**
		Indent the spinner with the given number of spaces.

		@default 0
		*/
		readonly indent?: number;

		/**
		Interval between each frame.

		Spinners provide their own recommended interval, so you don't really need to specify this.

		Default: Provided by the spinner or `100`.
		*/
		readonly interval?: number;

		/**
		Stream to write the output.

		You could for example set this to `process.stdout` instead.

		@default process.stderr
		*/
		readonly stream?: NodeJS.WritableStream;

		/**
		Force enable/disable the spinner. If not specified, the spinner will be enabled if the `stream` is being run inside a TTY context (not spawned or piped) and/or not in a CI environment.

		Note that `{isEnabled: false}` doesn't mean it won't output anything. It just means it won't output the spinner, colors, and other ansi escape codes. It will still log text.
		*/
		readonly isEnabled?: boolean;

		/**
		Disable the spinner and all log text. All output is suppressed and `isEnabled` will be considered `false`.

		@default false
		*/
		readonly isSilent?: boolean;

		/**
		Discard stdin input (except Ctrl+C) while running if it's TTY. This prevents the spinner from twitching on input, outputting broken lines on `Enter` key presses, and prevents buffering of input while the spinner is running.

		This has no effect on Windows as there's no good way to implement discarding stdin properly there.

		@default true
		*/
		readonly discardStdin?: boolean;
	}

	interface PersistOptions {
		/**
		Symbol to replace the spinner with.

		@default ' '
		*/
		readonly symbol?: string;

		/**
		Text to be persisted after the symbol.

		Default: Current `text`.
		*/
		readonly text?: string;

		/**
		Text or a function that returns text to be persisted before the symbol. No prefix text will be displayed if set to an empty string.

		Default: Current `prefixText`.
		*/
		readonly prefixText?: string | PrefixTextGenerator;
	}

	interface Ora {
		/**
		A boolean of whether the instance is currently spinning.
		*/
		readonly isSpinning: boolean;

		/**
		Change the text after the spinner.
		*/
		text: string;

		/**
		Change the text or function that returns text before the spinner. No prefix text will be displayed if set to an empty string.
		*/
		prefixText: string | PrefixTextGenerator;

		/**
		Change the spinner color.
		*/
		color: Color;

		/**
		Change the spinner.
		*/
		spinner: SpinnerName | Spinner;

		/**
		Change the spinner indent.
		*/
		indent: number;

		/**
		Start the spinner.

		@param text - Set the current text.
		@returns The spinner instance.
		*/
		start(text?: string): Ora;

		/**
		Stop and clear the spinner.

		@returns The spinner instance.
		*/
		stop(): Ora;

		/**
		Stop the spinner, change it to a green `✔` and persist the current text, or `text` if provided.

		@param text - Will persist text if provided.
		@returns The spinner instance.
		*/
		succeed(text?: string): Ora;

		/**
		Stop the spinner, change it to a red `✖` and persist the current text, or `text` if provided.

		@param text - Will persist text if provided.
		@returns The spinner instance.
		*/
		fail(text?: string): Ora;

		/**
		Stop the spinner, change it to a yellow `⚠` and persist the current text, or `text` if provided.

		@param text - Will persist text if provided.
		@returns The spinner instance.
		*/
		warn(text?: string): Ora;

		/**
		Stop the spinner, change it to a blue `ℹ` and persist the current text, or `text` if provided.

		@param text - Will persist text if provided.
		@returns The spinner instance.
		*/
		info(text?: string): Ora;

		/**
		Stop the spinner and change the symbol or text.

		@returns The spinner instance.
		*/
		stopAndPersist(options?: PersistOptions): Ora;

		/**
		Clear the spinner.

		@returns The spinner instance.
		*/
		clear(): Ora;

		/**
		Manually render a new frame.

		@returns The spinner instance.
		*/
		render(): Ora;

		/**
		Get a new frame.

		@returns The spinner instance text.
		*/
		frame(): string;
	}
}

declare const ora: {
	/**
	Elegant terminal spinner.

	@param options - If a string is provided, it is treated as a shortcut for `options.text`.

	@example
	```
	import ora = require('ora');

	const spinner = ora('Loading unicorns').start();

	setTimeout(() => {
		spinner.color = 'yellow';
		spinner.text = 'Loading rainbows';
	}, 1000);
	```
	*/
	(options?: ora.Options | string): ora.Ora;

	/**
	Starts a spinner for a promise. The spinner is stopped with `.succeed()` if the promise fulfills or with `.fail()` if it rejects.

	@param action - The promise to start the spinner for.
	@param options - If a string is provided, it is treated as a shortcut for `options.text`.
	@returns The spinner instance.
	*/
	promise(
		action: PromiseLike<unknown>,
		options?: ora.Options | string
	): ora.Ora;
};

export = ora;


code:
'use strict';
const readline = require('readline');
const chalk = require('chalk');
const cliCursor = require('cli-cursor');
const cliSpinners = require('cli-spinners');
const logSymbols = require('log-symbols');
const stripAnsi = require('strip-ansi');
const wcwidth = require('wcwidth');
const isInteractive = require('is-interactive');
const isUnicodeSupported = require('is-unicode-supported');
const {BufferListStream} = require('bl');

const TEXT = Symbol('text');
const PREFIX_TEXT = Symbol('prefixText');
const ASCII_ETX_CODE = 0x03; // Ctrl+C emits this code

class StdinDiscarder {
	constructor() {
		this.requests = 0;

		this.mutedStream = new BufferListStream();
		this.mutedStream.pipe(process.stdout);

		const self = this; // eslint-disable-line unicorn/no-this-assignment
		this.ourEmit = function (event, data, ...args) {
			const {stdin} = process;
			if (self.requests > 0 || stdin.emit === self.ourEmit) {
				if (event === 'keypress') { // Fixes readline behavior
					return;
				}

				if (event === 'data' && data.includes(ASCII_ETX_CODE)) {
					process.emit('SIGINT');
				}

				Reflect.apply(self.oldEmit, this, [event, data, ...args]);
			} else {
				Reflect.apply(process.stdin.emit, this, [event, data, ...args]);
			}
		};
	}

	start() {
		this.requests++;

		if (this.requests === 1) {
			this.realStart();
		}
	}

	stop() {
		if (this.requests <= 0) {
			throw new Error('`stop` called more times than `start`');
		}

		this.requests--;

		if (this.requests === 0) {
			this.realStop();
		}
	}

	realStart() {
		// No known way to make it work reliably on Windows
		if (process.platform === 'win32') {
			return;
		}

		this.rl = readline.createInterface({
			input: process.stdin,
			output: this.mutedStream
		});

		this.rl.on('SIGINT', () => {
			if (process.listenerCount('SIGINT') === 0) {
				process.emit('SIGINT');
			} else {
				this.rl.close();
				process.kill(process.pid, 'SIGINT');
			}
		});
	}

	realStop() {
		if (process.platform === 'win32') {
			return;
		}

		this.rl.close();
		this.rl = undefined;
	}
}

let stdinDiscarder;

class Ora {
	constructor(options) {
		if (!stdinDiscarder) {
			stdinDiscarder = new StdinDiscarder();
		}

		if (typeof options === 'string') {
			options = {
				text: options
			};
		}

		this.options = {
			text: '',
			color: 'cyan',
			stream: process.stderr,
			discardStdin: true,
			...options
		};

		this.spinner = this.options.spinner;

		this.color = this.options.color;
		this.hideCursor = this.options.hideCursor !== false;
		this.interval = this.options.interval || this.spinner.interval || 100;
		this.stream = this.options.stream;
		this.id = undefined;
		this.isEnabled = typeof this.options.isEnabled === 'boolean' ? this.options.isEnabled : isInteractive({stream: this.stream});
		this.isSilent = typeof this.options.isSilent === 'boolean' ? this.options.isSilent : false;

		// Set *after* `this.stream`
		this.text = this.options.text;
		this.prefixText = this.options.prefixText;
		this.linesToClear = 0;
		this.indent = this.options.indent;
		this.discardStdin = this.options.discardStdin;
		this.isDiscardingStdin = false;
	}

	get indent() {
		return this._indent;
	}

	set indent(indent = 0) {
		if (!(indent >= 0 && Number.isInteger(indent))) {
			throw new Error('The `indent` option must be an integer from 0 and up');
		}

		this._indent = indent;
	}

	_updateInterval(interval) {
		if (interval !== undefined) {
			this.interval = interval;
		}
	}

	get spinner() {
		return this._spinner;
	}

	set spinner(spinner) {
		this.frameIndex = 0;

		if (typeof spinner === 'object') {
			if (spinner.frames === undefined) {
				throw new Error('The given spinner must have a `frames` property');
			}

			this._spinner = spinner;
		} else if (!isUnicodeSupported()) {
			this._spinner = cliSpinners.line;
		} else if (spinner === undefined) {
			// Set default spinner
			this._spinner = cliSpinners.dots;
		} else if (spinner !== 'default' && cliSpinners[spinner]) {
			this._spinner = cliSpinners[spinner];
		} else {
			throw new Error(`There is no built-in spinner named '${spinner}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`);
		}

		this._updateInterval(this._spinner.interval);
	}

	get text() {
		return this[TEXT];
	}

	set text(value) {
		this[TEXT] = value;
		this.updateLineCount();
	}

	get prefixText() {
		return this[PREFIX_TEXT];
	}

	set prefixText(value) {
		this[PREFIX_TEXT] = value;
		this.updateLineCount();
	}

	get isSpinning() {
		return this.id !== undefined;
	}

	getFullPrefixText(prefixText = this[PREFIX_TEXT], postfix = ' ') {
		if (typeof prefixText === 'string') {
			return prefixText + postfix;
		}

		if (typeof prefixText === 'function') {
			return prefixText() + postfix;
		}

		return '';
	}

	updateLineCount() {
		const columns = this.stream.columns || 80;
		const fullPrefixText = this.getFullPrefixText(this.prefixText, '-');
		this.lineCount = 0;
		for (const line of stripAnsi(fullPrefixText + '--' + this[TEXT]).split('\n')) {
			this.lineCount += Math.max(1, Math.ceil(wcwidth(line) / columns));
		}
	}

	get isEnabled() {
		return this._isEnabled && !this.isSilent;
	}

	set isEnabled(value) {
		if (typeof value !== 'boolean') {
			throw new TypeError('The `isEnabled` option must be a boolean');
		}

		this._isEnabled = value;
	}

	get isSilent() {
		return this._isSilent;
	}

	set isSilent(value) {
		if (typeof value !== 'boolean') {
			throw new TypeError('The `isSilent` option must be a boolean');
		}

		this._isSilent = value;
	}

	frame() {
		const {frames} = this.spinner;
		let frame = frames[this.frameIndex];

		if (this.color) {
			frame = chalk[this.color](frame);
		}

		this.frameIndex = ++this.frameIndex % frames.length;
		const fullPrefixText = (typeof this.prefixText === 'string' && this.prefixText !== '') ? this.prefixText + ' ' : '';
		const fullText = typeof this.text === 'string' ? ' ' + this.text : '';

		return fullPrefixText + frame + fullText;
	}

	clear() {
		if (!this.isEnabled || !this.stream.isTTY) {
			return this;
		}

		for (let i = 0; i < this.linesToClear; i++) {
			if (i > 0) {
				this.stream.moveCursor(0, -1);
			}

			this.stream.clearLine();
			this.stream.cursorTo(this.indent);
		}

		this.linesToClear = 0;

		return this;
	}

	render() {
		if (this.isSilent) {
			return this;
		}

		this.clear();
		this.stream.write(this.frame());
		this.linesToClear = this.lineCount;

		return this;
	}

	start(text) {
		if (text) {
			this.text = text;
		}

		if (this.isSilent) {
			return this;
		}

		if (!this.isEnabled) {
			if (this.text) {
				this.stream.write(`- ${this.text}\n`);
			}

			return this;
		}

		if (this.isSpinning) {
			return this;
		}

		if (this.hideCursor) {
			cliCursor.hide(this.stream);
		}

		if (this.discardStdin && process.stdin.isTTY) {
			this.isDiscardingStdin = true;
			stdinDiscarder.start();
		}

		this.render();
		this.id = setInterval(this.render.bind(this), this.interval);

		return this;
	}

	stop() {
		if (!this.isEnabled) {
			return this;
		}

		clearInterval(this.id);
		this.id = undefined;
		this.frameIndex = 0;
		this.clear();
		if (this.hideCursor) {
			cliCursor.show(this.stream);
		}

		if (this.discardStdin && process.stdin.isTTY && this.isDiscardingStdin) {
			stdinDiscarder.stop();
			this.isDiscardingStdin = false;
		}

		return this;
	}

	succeed(text) {
		return this.stopAndPersist({symbol: logSymbols.success, text});
	}

	fail(text) {
		return this.stopAndPersist({symbol: logSymbols.error, text});
	}

	warn(text) {
		return this.stopAndPersist({symbol: logSymbols.warning, text});
	}

	info(text) {
		return this.stopAndPersist({symbol: logSymbols.info, text});
	}

	stopAndPersist(options = {}) {
		if (this.isSilent) {
			return this;
		}

		const prefixText = options.prefixText || this.prefixText;
		const text = options.text || this.text;
		const fullText = (typeof text === 'string') ? ' ' + text : '';

		this.stop();
		this.stream.write(`${this.getFullPrefixText(prefixText, ' ')}${options.symbol || ' '}${fullText}\n`);

		return this;
	}
}

const oraFactory = function (options) {
	return new Ora(options);
};

module.exports = oraFactory;

module.exports.promise = (action, options) => {
	// eslint-disable-next-line promise/prefer-await-to-then
	if (typeof action.then !== 'function') {
		throw new TypeError('Parameter `action` must be a Promise');
	}

	const spinner = new Ora(options);
	spinner.start();

	(async () => {
		try {
			await action;
			spinner.succeed();
		} catch {
			spinner.fail();
		}
	})();

	return spinner;
};


code:
declare type CSSColor =
	| 'aliceblue'
	| 'antiquewhite'
	| 'aqua'
	| 'aquamarine'
	| 'azure'
	| 'beige'
	| 'bisque'
	| 'black'
	| 'blanchedalmond'
	| 'blue'
	| 'blueviolet'
	| 'brown'
	| 'burlywood'
	| 'cadetblue'
	| 'chartreuse'
	| 'chocolate'
	| 'coral'
	| 'cornflowerblue'
	| 'cornsilk'
	| 'crimson'
	| 'cyan'
	| 'darkblue'
	| 'darkcyan'
	| 'darkgoldenrod'
	| 'darkgray'
	| 'darkgreen'
	| 'darkgrey'
	| 'darkkhaki'
	| 'darkmagenta'
	| 'darkolivegreen'
	| 'darkorange'
	| 'darkorchid'
	| 'darkred'
	| 'darksalmon'
	| 'darkseagreen'
	| 'darkslateblue'
	| 'darkslategray'
	| 'darkslategrey'
	| 'darkturquoise'
	| 'darkviolet'
	| 'deeppink'
	| 'deepskyblue'
	| 'dimgray'
	| 'dimgrey'
	| 'dodgerblue'
	| 'firebrick'
	| 'floralwhite'
	| 'forestgreen'
	| 'fuchsia'
	| 'gainsboro'
	| 'ghostwhite'
	| 'gold'
	| 'goldenrod'
	| 'gray'
	| 'green'
	| 'greenyellow'
	| 'grey'
	| 'honeydew'
	| 'hotpink'
	| 'indianred'
	| 'indigo'
	| 'ivory'
	| 'khaki'
	| 'lavender'
	| 'lavenderblush'
	| 'lawngreen'
	| 'lemonchiffon'
	| 'lightblue'
	| 'lightcoral'
	| 'lightcyan'
	| 'lightgoldenrodyellow'
	| 'lightgray'
	| 'lightgreen'
	| 'lightgrey'
	| 'lightpink'
	| 'lightsalmon'
	| 'lightseagreen'
	| 'lightskyblue'
	| 'lightslategray'
	| 'lightslategrey'
	| 'lightsteelblue'
	| 'lightyellow'
	| 'lime'
	| 'limegreen'
	| 'linen'
	| 'magenta'
	| 'maroon'
	| 'mediumaquamarine'
	| 'mediumblue'
	| 'mediumorchid'
	| 'mediumpurple'
	| 'mediumseagreen'
	| 'mediumslateblue'
	| 'mediumspringgreen'
	| 'mediumturquoise'
	| 'mediumvioletred'
	| 'midnightblue'
	| 'mintcream'
	| 'mistyrose'
	| 'moccasin'
	| 'navajowhite'
	| 'navy'
	| 'oldlace'
	| 'olive'
	| 'olivedrab'
	| 'orange'
	| 'orangered'
	| 'orchid'
	| 'palegoldenrod'
	| 'palegreen'
	| 'paleturquoise'
	| 'palevioletred'
	| 'papayawhip'
	| 'peachpuff'
	| 'peru'
	| 'pink'
	| 'plum'
	| 'powderblue'
	| 'purple'
	| 'rebeccapurple'
	| 'red'
	| 'rosybrown'
	| 'royalblue'
	| 'saddlebrown'
	| 'salmon'
	| 'sandybrown'
	| 'seagreen'
	| 'seashell'
	| 'sienna'
	| 'silver'
	| 'skyblue'
	| 'slateblue'
	| 'slategray'
	| 'slategrey'
	| 'snow'
	| 'springgreen'
	| 'steelblue'
	| 'tan'
	| 'teal'
	| 'thistle'
	| 'tomato'
	| 'turquoise'
	| 'violet'
	| 'wheat'
	| 'white'
	| 'whitesmoke'
	| 'yellow'
	| 'yellowgreen';

declare namespace ansiStyles {
	interface ColorConvert {
		/**
		The RGB color space.

		@param red - (`0`-`255`)
		@param green - (`0`-`255`)
		@param blue - (`0`-`255`)
		*/
		rgb(red: number, green: number, blue: number): string;

		/**
		The RGB HEX color space.

		@param hex - A hexadecimal string containing RGB data.
		*/
		hex(hex: string): string;

		/**
		@param keyword - A CSS color name.
		*/
		keyword(keyword: CSSColor): string;

		/**
		The HSL color space.

		@param hue - (`0`-`360`)
		@param saturation - (`0`-`100`)
		@param lightness - (`0`-`100`)
		*/
		hsl(hue: number, saturation: number, lightness: number): string;

		/**
		The HSV color space.

		@param hue - (`0`-`360`)
		@param saturation - (`0`-`100`)
		@param value - (`0`-`100`)
		*/
		hsv(hue: number, saturation: number, value: number): string;

		/**
		The HSV color space.

		@param hue - (`0`-`360`)
		@param whiteness - (`0`-`100`)
		@param blackness - (`0`-`100`)
		*/
		hwb(hue: number, whiteness: number, blackness: number): string;

		/**
		Use a [4-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4-bit) to set text color.
		*/
		ansi(ansi: number): string;

		/**
		Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color.
		*/
		ansi256(ansi: number): string;
	}

	interface CSPair {
		/**
		The ANSI terminal control sequence for starting this style.
		*/
		readonly open: string;

		/**
		The ANSI terminal control sequence for ending this style.
		*/
		readonly close: string;
	}

	interface ColorBase {
		readonly ansi: ColorConvert;
		readonly ansi256: ColorConvert;
		readonly ansi16m: ColorConvert;

		/**
		The ANSI terminal control sequence for ending this color.
		*/
		readonly close: string;
	}

	interface Modifier {
		/**
		Resets the current color chain.
		*/
		readonly reset: CSPair;

		/**
		Make text bold.
		*/
		readonly bold: CSPair;

		/**
		Emitting only a small amount of light.
		*/
		readonly dim: CSPair;

		/**
		Make text italic. (Not widely supported)
		*/
		readonly italic: CSPair;

		/**
		Make text underline. (Not widely supported)
		*/
		readonly underline: CSPair;

		/**
		Inverse background and foreground colors.
		*/
		readonly inverse: CSPair;

		/**
		Prints the text, but makes it invisible.
		*/
		readonly hidden: CSPair;

		/**
		Puts a horizontal line through the center of the text. (Not widely supported)
		*/
		readonly strikethrough: CSPair;
	}

	interface ForegroundColor {
		readonly black: CSPair;
		readonly red: CSPair;
		readonly green: CSPair;
		readonly yellow: CSPair;
		readonly blue: CSPair;
		readonly cyan: CSPair;
		readonly magenta: CSPair;
		readonly white: CSPair;

		/**
		Alias for `blackBright`.
		*/
		readonly gray: CSPair;

		/**
		Alias for `blackBright`.
		*/
		readonly grey: CSPair;

		readonly blackBright: CSPair;
		readonly redBright: CSPair;
		readonly greenBright: CSPair;
		readonly yellowBright: CSPair;
		readonly blueBright: CSPair;
		readonly cyanBright: CSPair;
		readonly magentaBright: CSPair;
		readonly whiteBright: CSPair;
	}

	interface BackgroundColor {
		readonly bgBlack: CSPair;
		readonly bgRed: CSPair;
		readonly bgGreen: CSPair;
		readonly bgYellow: CSPair;
		readonly bgBlue: CSPair;
		readonly bgCyan: CSPair;
		readonly bgMagenta: CSPair;
		readonly bgWhite: CSPair;

		/**
		Alias for `bgBlackBright`.
		*/
		readonly bgGray: CSPair;

		/**
		Alias for `bgBlackBright`.
		*/
		readonly bgGrey: CSPair;

		readonly bgBlackBright: CSPair;
		readonly bgRedBright: CSPair;
		readonly bgGreenBright: CSPair;
		readonly bgYellowBright: CSPair;
		readonly bgBlueBright: CSPair;
		readonly bgCyanBright: CSPair;
		readonly bgMagentaBright: CSPair;
		readonly bgWhiteBright: CSPair;
	}
}

declare const ansiStyles: {
	readonly modifier: ansiStyles.Modifier;
	readonly color: ansiStyles.ForegroundColor & ansiStyles.ColorBase;
	readonly bgColor: ansiStyles.BackgroundColor & ansiStyles.ColorBase;
	readonly codes: ReadonlyMap<number, number>;
} & ansiStyles.BackgroundColor & ansiStyles.ForegroundColor & ansiStyles.Modifier;

export = ansiStyles;


code:
'use strict';

const wrapAnsi16 = (fn, offset) => (...args) => {
	const code = fn(...args);
	return `\u001B[${code + offset}m`;
};

const wrapAnsi256 = (fn, offset) => (...args) => {
	const code = fn(...args);
	return `\u001B[${38 + offset};5;${code}m`;
};

const wrapAnsi16m = (fn, offset) => (...args) => {
	const rgb = fn(...args);
	return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
};

const ansi2ansi = n => n;
const rgb2rgb = (r, g, b) => [r, g, b];

const setLazyProperty = (object, property, get) => {
	Object.defineProperty(object, property, {
		get: () => {
			const value = get();

			Object.defineProperty(object, property, {
				value,
				enumerable: true,
				configurable: true
			});

			return value;
		},
		enumerable: true,
		configurable: true
	});
};

/** @type {typeof import('color-convert')} */
let colorConvert;
const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
	if (colorConvert === undefined) {
		colorConvert = require('color-convert');
	}

	const offset = isBackground ? 10 : 0;
	const styles = {};

	for (const [sourceSpace, suite] of Object.entries(colorConvert)) {
		const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
		if (sourceSpace === targetSpace) {
			styles[name] = wrap(identity, offset);
		} else if (typeof suite === 'object') {
			styles[name] = wrap(suite[targetSpace], offset);
		}
	}

	return styles;
};

function assembleStyles() {
	const codes = new Map();
	const styles = {
		modifier: {
			reset: [0, 0],
			// 21 isn't widely supported and 22 does the same thing
			bold: [1, 22],
			dim: [2, 22],
			italic: [3, 23],
			underline: [4, 24],
			inverse: [7, 27],
			hidden: [8, 28],
			strikethrough: [9, 29]
		},
		color: {
			black: [30, 39],
			red: [31, 39],
			green: [32, 39],
			yellow: [33, 39],
			blue: [34, 39],
			magenta: [35, 39],
			cyan: [36, 39],
			white: [37, 39],

			// Bright color
			blackBright: [90, 39],
			redBright: [91, 39],
			greenBright: [92, 39],
			yellowBright: [93, 39],
			blueBright: [94, 39],
			magentaBright: [95, 39],
			cyanBright: [96, 39],
			whiteBright: [97, 39]
		},
		bgColor: {
			bgBlack: [40, 49],
			bgRed: [41, 49],
			bgGreen: [42, 49],
			bgYellow: [43, 49],
			bgBlue: [44, 49],
			bgMagenta: [45, 49],
			bgCyan: [46, 49],
			bgWhite: [47, 49],

			// Bright color
			bgBlackBright: [100, 49],
			bgRedBright: [101, 49],
			bgGreenBright: [102, 49],
			bgYellowBright: [103, 49],
			bgBlueBright: [104, 49],
			bgMagentaBright: [105, 49],
			bgCyanBright: [106, 49],
			bgWhiteBright: [107, 49]
		}
	};

	// Alias bright black as gray (and grey)
	styles.color.gray = styles.color.blackBright;
	styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
	styles.color.grey = styles.color.blackBright;
	styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;

	for (const [groupName, group] of Object.entries(styles)) {
		for (const [styleName, style] of Object.entries(group)) {
			styles[styleName] = {
				open: `\u001B[${style[0]}m`,
				close: `\u001B[${style[1]}m`
			};

			group[styleName] = styles[styleName];

			codes.set(style[0], style[1]);
		}

		Object.defineProperty(styles, groupName, {
			value: group,
			enumerable: false
		});
	}

	Object.defineProperty(styles, 'codes', {
		value: codes,
		enumerable: false
	});

	styles.color.close = '\u001B[39m';
	styles.bgColor.close = '\u001B[49m';

	setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
	setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
	setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
	setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
	setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
	setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));

	return styles;
}

// Make the export immutable
Object.defineProperty(module, 'exports', {
	enumerable: true,
	get: assembleStyles
});


ansi-styles

description: ANSI escape codes for styling strings in the terminal

repository: chalk/ansi-styles

test: xo && ava && tsd

screenshot: svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor

keywords: ansi styles color colour colors terminal console cli string tty escape formatting rgb 256 shell xterm log logging command-line text


code:
# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles)

> [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal

You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings.

<img src="screenshot.svg" width="900">

## Install

```
$ npm install ansi-styles
```

## Usage

```js
const style = require('ansi-styles');

console.log(`${style.green.open}Hello world!${style.green.close}`);

// Color conversion between 16/256/truecolor
// NOTE: If conversion goes to 16 colors or 256 colors, the original color
//       may be degraded to fit that color palette. This means terminals
//       that do not support 16 million colors will best-match the
//       original color.
console.log(style.bgColor.ansi.hsl(120, 80, 72) + 'Hello world!' + style.bgColor.close);
console.log(style.color.ansi256.rgb(199, 20, 250) + 'Hello world!' + style.color.close);
console.log(style.color.ansi16m.hex('#abcdef') + 'Hello world!' + style.color.close);
```

## API

Each style has an `open` and `close` property.

## Styles

### Modifiers

- `reset`
- `bold`
- `dim`
- `italic` *(Not widely supported)*
- `underline`
- `inverse`
- `hidden`
- `strikethrough` *(Not widely supported)*

### Colors

- `black`
- `red`
- `green`
- `yellow`
- `blue`
- `magenta`
- `cyan`
- `white`
- `blackBright` (alias: `gray`, `grey`)
- `redBright`
- `greenBright`
- `yellowBright`
- `blueBright`
- `magentaBright`
- `cyanBright`
- `whiteBright`

### Background colors

- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
- `bgBlackBright` (alias: `bgGray`, `bgGrey`)
- `bgRedBright`
- `bgGreenBright`
- `bgYellowBright`
- `bgBlueBright`
- `bgMagentaBright`
- `bgCyanBright`
- `bgWhiteBright`

## Advanced usage

By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module.

- `style.modifier`
- `style.color`
- `style.bgColor`

###### Example

```js
console.log(style.color.green.open);
```

Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `style.codes`, which returns a `Map` with the open codes as keys and close codes as values.

###### Example

```js
console.log(style.codes.get(36));
//=> 39
```

## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728)

`ansi-styles` uses the [`color-convert`](https://github.com/Qix-/color-convert) package to allow for converting between various colors and ANSI escapes, with support for 256 and 16 million colors.

The following color spaces from `color-convert` are supported:

- `rgb`
- `hex`
- `keyword`
- `hsl`
- `hsv`
- `hwb`
- `ansi`
- `ansi256`

To use these, call the associated conversion function with the intended output, for example:

```js
style.color.ansi.rgb(100, 200, 15); // RGB to 16 color ansi foreground code
style.bgColor.ansi.rgb(100, 200, 15); // RGB to 16 color ansi background code

style.color.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code
style.bgColor.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code

style.color.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color foreground code
style.bgColor.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color background code
```

## Related

- [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal

## Maintainers

- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)

## For enterprise

Available as part of the Tidelift Subscription.

The maintainers of `ansi-styles` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-ansi-styles?utm_source=npm-ansi-styles&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)


code:
/**
Basic foreground colors.

[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
*/
declare type ForegroundColor =
	| 'black'
	| 'red'
	| 'green'
	| 'yellow'
	| 'blue'
	| 'magenta'
	| 'cyan'
	| 'white'
	| 'gray'
	| 'grey'
	| 'blackBright'
	| 'redBright'
	| 'greenBright'
	| 'yellowBright'
	| 'blueBright'
	| 'magentaBright'
	| 'cyanBright'
	| 'whiteBright';

/**
Basic background colors.

[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
*/
declare type BackgroundColor =
	| 'bgBlack'
	| 'bgRed'
	| 'bgGreen'
	| 'bgYellow'
	| 'bgBlue'
	| 'bgMagenta'
	| 'bgCyan'
	| 'bgWhite'
	| 'bgGray'
	| 'bgGrey'
	| 'bgBlackBright'
	| 'bgRedBright'
	| 'bgGreenBright'
	| 'bgYellowBright'
	| 'bgBlueBright'
	| 'bgMagentaBright'
	| 'bgCyanBright'
	| 'bgWhiteBright';

/**
Basic colors.

[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
*/
declare type Color = ForegroundColor | BackgroundColor;

declare type Modifiers =
	| 'reset'
	| 'bold'
	| 'dim'
	| 'italic'
	| 'underline'
	| 'inverse'
	| 'hidden'
	| 'strikethrough'
	| 'visible';

declare namespace chalk {
	/**
	Levels:
	- `0` - All colors disabled.
	- `1` - Basic 16 colors support.
	- `2` - ANSI 256 colors support.
	- `3` - Truecolor 16 million colors support.
	*/
	type Level = 0 | 1 | 2 | 3;

	interface Options {
		/**
		Specify the color support for Chalk.

		By default, color support is automatically detected based on the environment.

		Levels:
		- `0` - All colors disabled.
		- `1` - Basic 16 colors support.
		- `2` - ANSI 256 colors support.
		- `3` - Truecolor 16 million colors support.
		*/
		level?: Level;
	}

	/**
	Return a new Chalk instance.
	*/
	type Instance = new (options?: Options) => Chalk;

	/**
	Detect whether the terminal supports color.
	*/
	interface ColorSupport {
		/**
		The color level used by Chalk.
		*/
		level: Level;

		/**
		Return whether Chalk supports basic 16 colors.
		*/
		hasBasic: boolean;

		/**
		Return whether Chalk supports ANSI 256 colors.
		*/
		has256: boolean;

		/**
		Return whether Chalk supports Truecolor 16 million colors.
		*/
		has16m: boolean;
	}

	interface ChalkFunction {
		/**
		Use a template string.

		@remarks Template literals are unsupported for nested calls (see [issue #341](https://github.com/chalk/chalk/issues/341))

		@example
		```
		import chalk = require('chalk');

		log(chalk`
		CPU: {red ${cpu.totalPercent}%}
		RAM: {green ${ram.used / ram.total * 100}%}
		DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
		`);
		```

		@example
		```
		import chalk = require('chalk');

		log(chalk.red.bgBlack`2 + 3 = {bold ${2 + 3}}`)
		```
		*/
		(text: TemplateStringsArray, ...placeholders: unknown[]): string;

		(...text: unknown[]): string;
	}

	interface Chalk extends ChalkFunction {
		/**
		Return a new Chalk instance.
		*/
		Instance: Instance;

		/**
		The color support for Chalk.

		By default, color support is automatically detected based on the environment.

		Levels:
		- `0` - All colors disabled.
		- `1` - Basic 16 colors support.
		- `2` - ANSI 256 colors support.
		- `3` - Truecolor 16 million colors support.
		*/
		level: Level;

		/**
		Use HEX value to set text color.

		@param color - Hexadecimal value representing the desired color.

		@example
		```
		import chalk = require('chalk');

		chalk.hex('#DEADED');
		```
		*/
		hex(color: string): Chalk;

		/**
		Use keyword color value to set text color.

		@param color - Keyword value representing the desired color.

		@example
		```
		import chalk = require('chalk');

		chalk.keyword('orange');
		```
		*/
		keyword(color: string): Chalk;

		/**
		Use RGB values to set text color.
		*/
		rgb(red: number, green: number, blue: number): Chalk;

		/**
		Use HSL values to set text color.
		*/
		hsl(hue: number, saturation: number, lightness: number): Chalk;

		/**
		Use HSV values to set text color.
		*/
		hsv(hue: number, saturation: number, value: number): Chalk;

		/**
		Use HWB values to set text color.
		*/
		hwb(hue: number, whiteness: number, blackness: number): Chalk;

		/**
		Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set text color.

		30 <= code && code < 38 || 90 <= code && code < 98
		For example, 31 for red, 91 for redBright.
		*/
		ansi(code: number): Chalk;

		/**
		Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color.
		*/
		ansi256(index: number): Chalk;

		/**
		Use HEX value to set background color.

		@param color - Hexadecimal value representing the desired color.

		@example
		```
		import chalk = require('chalk');

		chalk.bgHex('#DEADED');
		```
		*/
		bgHex(color: string): Chalk;

		/**
		Use keyword color value to set background color.

		@param color - Keyword value representing the desired color.

		@example
		```
		import chalk = require('chalk');

		chalk.bgKeyword('orange');
		```
		*/
		bgKeyword(color: string): Chalk;

		/**
		Use RGB values to set background color.
		*/
		bgRgb(red: number, green: number, blue: number): Chalk;

		/**
		Use HSL values to set background color.
		*/
		bgHsl(hue: number, saturation: number, lightness: number): Chalk;

		/**
		Use HSV values to set background color.
		*/
		bgHsv(hue: number, saturation: number, value: number): Chalk;

		/**
		Use HWB values to set background color.
		*/
		bgHwb(hue: number, whiteness: number, blackness: number): Chalk;

		/**
		Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set background color.

		30 <= code && code < 38 || 90 <= code && code < 98
		For example, 31 for red, 91 for redBright.
		Use the foreground code, not the background code (for example, not 41, nor 101).
		*/
		bgAnsi(code: number): Chalk;

		/**
		Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color.
		*/
		bgAnsi256(index: number): Chalk;

		/**
		Modifier: Resets the current color chain.
		*/
		readonly reset: Chalk;

		/**
		Modifier: Make text bold.
		*/
		readonly bold: Chalk;

		/**
		Modifier: Emitting only a small amount of light.
		*/
		readonly dim: Chalk;

		/**
		Modifier: Make text italic. (Not widely supported)
		*/
		readonly italic: Chalk;

		/**
		Modifier: Make text underline. (Not widely supported)
		*/
		readonly underline: Chalk;

		/**
		Modifier: Inverse background and foreground colors.
		*/
		readonly inverse: Chalk;

		/**
		Modifier: Prints the text, but makes it invisible.
		*/
		readonly hidden: Chalk;

		/**
		Modifier: Puts a horizontal line through the center of the text. (Not widely supported)
		*/
		readonly strikethrough: Chalk;

		/**
		Modifier: Prints the text only when Chalk has a color support level > 0.
		Can be useful for things that are purely cosmetic.
		*/
		readonly visible: Chalk;

		readonly black: Chalk;
		readonly red: Chalk;
		readonly green: Chalk;
		readonly yellow: Chalk;
		readonly blue: Chalk;
		readonly magenta: Chalk;
		readonly cyan: Chalk;
		readonly white: Chalk;

		/*
		Alias for `blackBright`.
		*/
		readonly gray: Chalk;

		/*
		Alias for `blackBright`.
		*/
		readonly grey: Chalk;

		readonly blackBright: Chalk;
		readonly redBright: Chalk;
		readonly greenBright: Chalk;
		readonly yellowBright: Chalk;
		readonly blueBright: Chalk;
		readonly magentaBright: Chalk;
		readonly cyanBright: Chalk;
		readonly whiteBright: Chalk;

		readonly bgBlack: Chalk;
		readonly bgRed: Chalk;
		readonly bgGreen: Chalk;
		readonly bgYellow: Chalk;
		readonly bgBlue: Chalk;
		readonly bgMagenta: Chalk;
		readonly bgCyan: Chalk;
		readonly bgWhite: Chalk;

		/*
		Alias for `bgBlackBright`.
		*/
		readonly bgGray: Chalk;

		/*
		Alias for `bgBlackBright`.
		*/
		readonly bgGrey: Chalk;

		readonly bgBlackBright: Chalk;
		readonly bgRedBright: Chalk;
		readonly bgGreenBright: Chalk;
		readonly bgYellowBright: Chalk;
		readonly bgBlueBright: Chalk;
		readonly bgMagentaBright: Chalk;
		readonly bgCyanBright: Chalk;
		readonly bgWhiteBright: Chalk;
	}
}

/**
Main Chalk object that allows to chain styles together.
Call the last one as a method with a string argument.
Order doesn't matter, and later styles take precedent in case of a conflict.
This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
*/
declare const chalk: chalk.Chalk & chalk.ChalkFunction & {
	supportsColor: chalk.ColorSupport | false;
	Level: chalk.Level;
	Color: Color;
	ForegroundColor: ForegroundColor;
	BackgroundColor: BackgroundColor;
	Modifiers: Modifiers;
	stderr: chalk.Chalk & {supportsColor: chalk.ColorSupport | false};
};

export = chalk;


chalk

description: Terminal string styling done right

repository: chalk/chalk

main: source

test: xo && nyc ava && tsd

bench: matcha benchmark.js

keywords: color colour colors terminal console cli string str ansi style styles tty formatting rgb 256 shell xterm log logging command-line text

unicorn/prefer-string-slice: off

unicorn/prefer-includes: off

@typescript-eslint/member-ordering: off

no-redeclare: off

unicorn/string-content: off

unicorn/better-regex: off


code:
> Terminal string styling done right

[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents) [![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) ![TypeScript-ready](https://img.shields.io/npm/types/chalk.svg) [![run on repl.it](https://repl.it/badge/github/chalk/chalk)](https://repl.it/github/chalk/chalk)

---

				Sindre Sorhus' open source work is supported by the community on GitHub Sponsors and Dev

		Special thanks to:

			All your environment variables, in one place

				Stop struggling with scattered API keys, hacking together home-brewed tools,

				and avoiding access controls. Keep your team and servers in sync with Doppler.

---

## Highlights

- Expressive API
- Highly performant
- Ability to nest styles
- [256/Truecolor color support](#256-and-truecolor-color-support)
- Auto-detects color support
- Doesn't extend `String.prototype`
- Clean and focused
- Actively maintained
- [Used by ~50,000 packages](https://www.npmjs.com/browse/depended/chalk) as of January 1, 2020

## Install

```console
$ npm install chalk
```

## Usage

```js
const chalk = require('chalk');

console.log(chalk.blue('Hello world!'));
```

Chalk comes with an easy to use composable API where you just chain and nest the styles you want.

```js
const chalk = require('chalk');
const log = console.log;

// Combine styled and normal strings
log(chalk.blue('Hello') + ' World' + chalk.red('!'));

// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold('Hello world!'));

// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));

// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));

// Nest styles of the same type even (color, underline, background)
log(chalk.green(
	'I am a green line ' +
	chalk.blue.underline.bold('with a blue substring') +
	' that becomes green again!'
));

// ES2015 template literal
log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);

// ES2015 tagged template literal
log(chalk`
CPU: {red ${cpu.totalPercent}%}
RAM: {green ${ram.used / ram.total * 100}%}
DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
`);

// Use RGB colors in terminal emulators that support it.
log(chalk.keyword('orange')('Yay for orange colored text!'));
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
log(chalk.hex('#DEADED').bold('Bold gray!'));
```

Easily define your own themes:

```js
const chalk = require('chalk');

const error = chalk.bold.red;
const warning = chalk.keyword('orange');

console.log(error('Error!'));
console.log(warning('Warning!'));
```

Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args):

```js
const name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
//=> 'Hello Sindre'
```

## API

### chalk.`<style>[.<style>...](string, [string...])`

Example: `chalk.red.bold.underline('Hello', 'world');`

Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.

Multiple arguments will be separated by space.

### chalk.level

Specifies the level of color support.

Color support is automatically detected, but you can override it by setting the `level` property. You should however only do this in your own code as it applies globally to all Chalk consumers.

If you need to change this in a reusable module, create a new instance:

```js
const ctx = new chalk.Instance({level: 0});
```

| Level | Description |
| :---: | :--- |
| `0` | All colors disabled |
| `1` | Basic color support (16 colors) |
| `2` | 256 color support |
| `3` | Truecolor support (16 million colors) |

### chalk.supportsColor

Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.

Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.

Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.

### chalk.stderr and chalk.stderr.supportsColor

`chalk.stderr` contains a separate instance configured with color support detected for `stderr` stream instead of `stdout`. Override rules from `chalk.supportsColor` apply to this too. `chalk.stderr.supportsColor` is exposed for convenience.

## Styles

### Modifiers

- `reset` - Resets the current color chain.
- `bold` - Make text bold.
- `dim` - Emitting only a small amount of light.
- `italic` - Make text italic. *(Not widely supported)*
- `underline` - Make text underline. *(Not widely supported)*
- `inverse`- Inverse background and foreground colors.
- `hidden` - Prints the text, but makes it invisible.
- `strikethrough` - Puts a horizontal line through the center of the text. *(Not widely supported)*
- `visible`- Prints the text only when Chalk has a color level > 0. Can be useful for things that are purely cosmetic.

### Colors

- `black`
- `red`
- `green`
- `yellow`
- `blue`
- `magenta`
- `cyan`
- `white`
- `blackBright` (alias: `gray`, `grey`)
- `redBright`
- `greenBright`
- `yellowBright`
- `blueBright`
- `magentaBright`
- `cyanBright`
- `whiteBright`

### Background colors

- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
- `bgBlackBright` (alias: `bgGray`, `bgGrey`)
- `bgRedBright`
- `bgGreenBright`
- `bgYellowBright`
- `bgBlueBright`
- `bgMagentaBright`
- `bgCyanBright`
- `bgWhiteBright`

## Tagged template literal

Chalk can be used as a [tagged template literal](https://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals).

```js
const chalk = require('chalk');

const miles = 18;
const calculateFeet = miles => miles * 5280;

console.log(chalk`
	There are {bold 5280 feet} in a mile.
	In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}.
`);
```

Blocks are delimited by an opening curly brace (`{`), a style, some content, and a closing curly brace (`}`).

Template styles are chained exactly like normal Chalk styles. The following three statements are equivalent:

```js
console.log(chalk.bold.rgb(10, 100, 200)('Hello!'));
console.log(chalk.bold.rgb(10, 100, 200)`Hello!`);
console.log(chalk`{bold.rgb(10,100,200) Hello!}`);
```

Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain spaces between parameters.

All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped.

## 256 and Truecolor color support

Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728) (16 million colors) on supported terminal apps.

Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying `{level: n}` as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red).

Examples:

- `chalk.hex('#DEADED').underline('Hello, world!')`
- `chalk.keyword('orange')('Some orange text')`
- `chalk.rgb(15, 100, 204).inverse('Hello!')`

Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `keyword` for foreground colors and `bgKeyword` for background colors).

- `chalk.bgHex('#DEADED').underline('Hello, world!')`
- `chalk.bgKeyword('orange')('Some orange text')`
- `chalk.bgRgb(15, 100, 204).inverse('Hello!')`

The following color models can be used:

- [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')`
- [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')`
- [`keyword`](https://www.w3.org/wiki/CSS/Properties/color/keywords) (CSS keywords) - Example: `chalk.keyword('orange').bold('Orange!')`
- [`hsl`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 100, 50).bold('Orange!')`
- [`hsv`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsv(32, 100, 100).bold('Orange!')`
- [`hwb`](https://en.wikipedia.org/wiki/HWB_color_model) - Example: `chalk.hwb(32, 0, 50).bold('Orange!')`
- [`ansi`](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) - Example: `chalk.ansi(31).bgAnsi(93)('red on yellowBright')`
- [`ansi256`](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) - Example: `chalk.bgAnsi256(194)('Honeydew, more or less')`

## Windows

If you're on Windows, do yourself a favor and use [Windows Terminal](https://github.com/microsoft/terminal) instead of `cmd.exe`.

## Origin story

[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68) and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative.

## chalk for enterprise

Available as part of the Tidelift Subscription.

The maintainers of chalk and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-chalk?utm_source=npm-chalk&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)

## Related

- [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
- [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal
- [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color
- [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Strip ANSI escape codes from a stream
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
- [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes
- [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models
- [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal
- [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to strings
- [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings
- [terminal-link](https://github.com/sindresorhus/terminal-link) - Create clickable links in the terminal

## Maintainers

- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)