HEX
Server: LiteSpeed
System: Linux server161.web-hosting.com 4.18.0-553.54.1.lve.el8.x86_64 #1 SMP Wed Jun 4 13:01:13 UTC 2025 x86_64
User: imagzxcb (1058)
PHP: 8.1.34
Disabled: NONE
Upload Files
File: /home/imagzxcb/public_html/db127a/columnify.tar
columnify.js000064400000023704152045561630007124 0ustar00"use strict";

var wcwidth = require('./width');

var _require = require('./utils');

var padRight = _require.padRight;
var padCenter = _require.padCenter;
var padLeft = _require.padLeft;
var splitIntoLines = _require.splitIntoLines;
var splitLongWords = _require.splitLongWords;
var truncateString = _require.truncateString;

var DEFAULT_HEADING_TRANSFORM = function DEFAULT_HEADING_TRANSFORM(key) {
  return key.toUpperCase();
};

var DEFAULT_DATA_TRANSFORM = function DEFAULT_DATA_TRANSFORM(cell, column, index) {
  return cell;
};

var DEFAULTS = Object.freeze({
  maxWidth: Infinity,
  minWidth: 0,
  columnSplitter: ' ',
  truncate: false,
  truncateMarker: '…',
  preserveNewLines: false,
  paddingChr: ' ',
  showHeaders: true,
  headingTransform: DEFAULT_HEADING_TRANSFORM,
  dataTransform: DEFAULT_DATA_TRANSFORM
});

module.exports = function (items) {
  var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

  var columnConfigs = options.config || {};
  delete options.config; // remove config so doesn't appear on every column.

  var maxLineWidth = options.maxLineWidth || Infinity;
  if (maxLineWidth === 'auto') maxLineWidth = process.stdout.columns || Infinity;
  delete options.maxLineWidth; // this is a line control option, don't pass it to column

  // Option defaults inheritance:
  // options.config[columnName] => options => DEFAULTS
  options = mixin({}, DEFAULTS, options);

  options.config = options.config || Object.create(null);

  options.spacing = options.spacing || '\n'; // probably useless
  options.preserveNewLines = !!options.preserveNewLines;
  options.showHeaders = !!options.showHeaders;
  options.columns = options.columns || options.include; // alias include/columns, prefer columns if supplied
  var columnNames = options.columns || []; // optional user-supplied columns to include

  items = toArray(items, columnNames);

  // if not suppled column names, automatically determine columns from data keys
  if (!columnNames.length) {
    items.forEach(function (item) {
      for (var columnName in item) {
        if (columnNames.indexOf(columnName) === -1) columnNames.push(columnName);
      }
    });
  }

  // initialize column defaults (each column inherits from options.config)
  var columns = columnNames.reduce(function (columns, columnName) {
    var column = Object.create(options);
    columns[columnName] = mixin(column, columnConfigs[columnName]);
    return columns;
  }, Object.create(null));

  // sanitize column settings
  columnNames.forEach(function (columnName) {
    var column = columns[columnName];
    column.name = columnName;
    column.maxWidth = Math.ceil(column.maxWidth);
    column.minWidth = Math.ceil(column.minWidth);
    column.truncate = !!column.truncate;
    column.align = column.align || 'left';
  });

  // sanitize data
  items = items.map(function (item) {
    var result = Object.create(null);
    columnNames.forEach(function (columnName) {
      // null/undefined -> ''
      result[columnName] = item[columnName] != null ? item[columnName] : '';
      // toString everything
      result[columnName] = '' + result[columnName];
      if (columns[columnName].preserveNewLines) {
        // merge non-newline whitespace chars
        result[columnName] = result[columnName].replace(/[^\S\n]/gmi, ' ');
      } else {
        // merge all whitespace chars
        result[columnName] = result[columnName].replace(/\s/gmi, ' ');
      }
    });
    return result;
  });

  // transform data cells
  columnNames.forEach(function (columnName) {
    var column = columns[columnName];
    items = items.map(function (item, index) {
      var col = Object.create(column);
      item[columnName] = column.dataTransform(item[columnName], col, index);

      var changedKeys = Object.keys(col);
      // disable default heading transform if we wrote to column.name
      if (changedKeys.indexOf('name') !== -1) {
        if (column.headingTransform !== DEFAULT_HEADING_TRANSFORM) return;
        column.headingTransform = function (heading) {
          return heading;
        };
      }
      changedKeys.forEach(function (key) {
        return column[key] = col[key];
      });
      return item;
    });
  });

  // add headers
  var headers = {};
  if (options.showHeaders) {
    columnNames.forEach(function (columnName) {
      var column = columns[columnName];

      if (!column.showHeaders) {
        headers[columnName] = '';
        return;
      }

      headers[columnName] = column.headingTransform(column.name);
    });
    items.unshift(headers);
  }
  // get actual max-width between min & max
  // based on length of data in columns
  columnNames.forEach(function (columnName) {
    var column = columns[columnName];
    column.width = items.map(function (item) {
      return item[columnName];
    }).reduce(function (min, cur) {
      // if already at maxWidth don't bother testing
      if (min >= column.maxWidth) return min;
      return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, wcwidth(cur))));
    }, 0);
  });

  // split long words so they can break onto multiple lines
  columnNames.forEach(function (columnName) {
    var column = columns[columnName];
    items = items.map(function (item) {
      item[columnName] = splitLongWords(item[columnName], column.width, column.truncateMarker);
      return item;
    });
  });

  // wrap long lines. each item is now an array of lines.
  columnNames.forEach(function (columnName) {
    var column = columns[columnName];
    items = items.map(function (item, index) {
      var cell = item[columnName];
      item[columnName] = splitIntoLines(cell, column.width);

      // if truncating required, only include first line + add truncation char
      if (column.truncate && item[columnName].length > 1) {
        item[columnName] = splitIntoLines(cell, column.width - wcwidth(column.truncateMarker));
        var firstLine = item[columnName][0];
        if (!endsWith(firstLine, column.truncateMarker)) item[columnName][0] += column.truncateMarker;
        item[columnName] = item[columnName].slice(0, 1);
      }
      return item;
    });
  });

  // recalculate column widths from truncated output/lines
  columnNames.forEach(function (columnName) {
    var column = columns[columnName];
    column.width = items.map(function (item) {
      return item[columnName].reduce(function (min, cur) {
        if (min >= column.maxWidth) return min;
        return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, wcwidth(cur))));
      }, 0);
    }).reduce(function (min, cur) {
      if (min >= column.maxWidth) return min;
      return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, cur)));
    }, 0);
  });

  var rows = createRows(items, columns, columnNames, options.paddingChr); // merge lines into rows
  // conceive output
  return rows.reduce(function (output, row) {
    return output.concat(row.reduce(function (rowOut, line) {
      return rowOut.concat(line.join(options.columnSplitter));
    }, []));
  }, []).map(function (line) {
    return truncateString(line, maxLineWidth);
  }).join(options.spacing);
};

/**
 * Convert wrapped lines into rows with padded values.
 *
 * @param Array items data to process
 * @param Array columns column width settings for wrapping
 * @param Array columnNames column ordering
 * @return Array items wrapped in arrays, corresponding to lines
 */

function createRows(items, columns, columnNames, paddingChr) {
  return items.map(function (item) {
    var row = [];
    var numLines = 0;
    columnNames.forEach(function (columnName) {
      numLines = Math.max(numLines, item[columnName].length);
    });
    // combine matching lines of each rows

    var _loop = function _loop(i) {
      row[i] = row[i] || [];
      columnNames.forEach(function (columnName) {
        var column = columns[columnName];
        var val = item[columnName][i] || ''; // || '' ensures empty columns get padded
        if (column.align === 'right') row[i].push(padLeft(val, column.width, paddingChr));else if (column.align === 'center' || column.align === 'centre') row[i].push(padCenter(val, column.width, paddingChr));else row[i].push(padRight(val, column.width, paddingChr));
      });
    };

    for (var i = 0; i < numLines; i++) {
      _loop(i);
    }
    return row;
  });
}

/**
 * Object.assign
 *
 * @return Object Object with properties mixed in.
 */

function mixin() {
  var _Object;

  if (Object.assign) return (_Object = Object).assign.apply(_Object, arguments);
  return ObjectAssign.apply(undefined, arguments);
}

function ObjectAssign(target, firstSource) {
  "use strict";

  if (target === undefined || target === null) throw new TypeError("Cannot convert first argument to object");

  var to = Object(target);

  var hasPendingException = false;
  var pendingException;

  for (var i = 1; i < arguments.length; i++) {
    var nextSource = arguments[i];
    if (nextSource === undefined || nextSource === null) continue;

    var keysArray = Object.keys(Object(nextSource));
    for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
      var nextKey = keysArray[nextIndex];
      try {
        var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
        if (desc !== undefined && desc.enumerable) to[nextKey] = nextSource[nextKey];
      } catch (e) {
        if (!hasPendingException) {
          hasPendingException = true;
          pendingException = e;
        }
      }
    }

    if (hasPendingException) throw pendingException;
  }
  return to;
}

/**
 * Adapted from String.prototype.endsWith polyfill.
 */

function endsWith(target, searchString, position) {
  position = position || target.length;
  position = position - searchString.length;
  var lastIndex = target.lastIndexOf(searchString);
  return lastIndex !== -1 && lastIndex === position;
}

function toArray(items, columnNames) {
  if (Array.isArray(items)) return items;
  var rows = [];
  for (var key in items) {
    var item = {};
    item[columnNames[0] || 'key'] = key;
    item[columnNames[1] || 'value'] = items[key];
    rows.push(item);
  }
  return rows;
}

LICENSE000064400000002064152045561630005562 0ustar00The MIT License (MIT)

Copyright (c) 2013 Tim Oxley

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Readme.md000064400000026364152045561630006305 0ustar00# columnify

[![NPM](https://nodei.co/npm/columnify.png?downloads=true&downloadRank=true&stars=true&chrome)](https://nodei.co/npm-dl/columnify/)
[![NPM](https://nodei.co/npm-dl/columnify.png?months=3&height=3&chrome)](https://nodei.co/npm/columnify/)

[![Build Status](https://img.shields.io/travis/timoxley/columnify.svg?style=flat)](https://travis-ci.org/timoxley/columnify)
[![NPM Version](https://img.shields.io/npm/v/columnify.svg?style=flat)](https://npmjs.org/package/columnify)
[![License](http://img.shields.io/npm/l/columnify.svg?style=flat)](LICENSE)
[![Dependency Status](https://david-dm.org/timoxley/columnify.svg)](https://david-dm.org/timoxley/columnify)
[![devDependency Status](https://david-dm.org/timoxley/columnify/dev-status.svg)](https://david-dm.org/timoxley/columnify#info=devDependencies)

Create text-based columns suitable for console output from objects or
arrays of objects.

Columns are automatically resized to fit the content of the largest
cell. Each cell will be padded with spaces to fill the available space
and ensure column contents are left-aligned.

Designed to [handle sensible wrapping in npm search results](https://github.com/isaacs/npm/pull/2328).

`npm search` before & after integrating columnify:

![npm-tidy-search](https://f.cloud.github.com/assets/43438/1848959/ae02ad04-76a1-11e3-8255-4781debffc26.gif)

## Installation & Update

```
$ npm install --save columnify@latest
```

## Usage

```javascript
var columnify = require('columnify')
var columns = columnify(data, options)
console.log(columns)
```

## Examples

### Columnify Objects

Objects are converted to a list of key/value pairs:

```javascript
var data = {
  "commander@0.6.1": 1,
  "minimatch@0.2.14": 3,
  "mkdirp@0.3.5": 2,
  "sigmund@1.0.0": 3
}

console.log(columnify(data))
```
#### Output:
```
KEY               VALUE
commander@0.6.1   1
minimatch@0.2.14  3
mkdirp@0.3.5      2
sigmund@1.0.0     3
```

### Custom Column Names

```javascript
var data = {
  "commander@0.6.1": 1,
  "minimatch@0.2.14": 3,
  "mkdirp@0.3.5": 2,
  "sigmund@1.0.0": 3
}

console.log(columnify(data, {columns: ['MODULE', 'COUNT']}))
```
#### Output:
```
MODULE            COUNT
commander@0.6.1   1
minimatch@0.2.14  3
mkdirp@0.3.5      2
sigmund@1.0.0     3
```

### Columnify Arrays of Objects

Column headings are extracted from the keys in supplied objects.

```javascript
var columnify = require('columnify')

var columns = columnify([{
  name: 'mod1',
  version: '0.0.1'
}, {
  name: 'module2',
  version: '0.2.0'
}])

console.log(columns)
```
#### Output:
```
NAME    VERSION
mod1    0.0.1  
module2 0.2.0  
```

### Filtering & Ordering Columns

By default, all properties are converted into columns, whether or not
they exist on every object or not.

To explicitly specify which columns to include, and in which order,
supply a "columns" or "include" array ("include" is just an alias).

```javascript
var data = [{
  name: 'module1',
  description: 'some description',
  version: '0.0.1',
}, {
  name: 'module2',
  description: 'another description',
  version: '0.2.0',
}]

var columns = columnify(data, {
  columns: ['name', 'version']
})

console.log(columns)
```

#### Output:
```
NAME    VERSION
module1 0.0.1
module2 0.2.0
```

## Global and Per Column Options
You can set a number of options at a global level (ie. for all columns) or on a per column basis.

Set options on a per column basis by using the `config` option to specify individual columns:

```javascript
var columns = columnify(data, {
  optionName: optionValue,
  config: {
    columnName: {optionName: optionValue},
    columnName: {optionName: optionValue},
  }
})
```

### Maximum and Minimum Column Widths
As with all options, you can define the `maxWidth` and `minWidth` globally, or for specified columns. By default, wrapping will happen at word boundaries. Empty cells or those which do not fill the `minWidth` will be padded with spaces.

```javascript
var columns = columnify([{
  name: 'mod1',
  description: 'some description which happens to be far larger than the max',
  version: '0.0.1',
}, {
  name: 'module-two',
  description: 'another description larger than the max',
  version: '0.2.0',
}], {
  minWidth: 20,
  config: {
    description: {maxWidth: 30}
  }
})

console.log(columns)
```

#### Output:
```
NAME                 DESCRIPTION                    VERSION             
mod1                 some description which happens 0.0.1               
                     to be far larger than the max                      
module-two           another description larger     0.2.0               
                     than the max                         
```

#### Maximum Line Width

You can set a hard maximum line width using the `maxLineWidth` option.
Beyond this value data is unceremoniously truncated with no truncation
marker.

This can either be a number or 'auto' to set the value to the width of
stdout.

Setting this value to 'auto' prevent TTY-imposed line-wrapping when
lines exceed the screen width.

#### Truncating Column Cells Instead of Wrapping

You can disable wrapping and instead truncate content at the maximum
column width by using the `truncate` option. Truncation respects word boundaries.  A truncation marker, `…`, will appear next to the last word in any truncated line.

```javascript
var columns = columnify(data, {
  truncate: true,
  config: {
    description: {
      maxWidth: 20
    }
  }
})

console.log(columns)
```
#### Output:
```
NAME       DESCRIPTION          VERSION
mod1       some description…    0.0.1  
module-two another description… 0.2.0  
```


### Align Right/Center
You can set the alignment of the column data by using the `align` option.

```js
var data = {
  "mocha@1.18.2": 1,
  "commander@2.0.0": 1,
  "debug@0.8.1": 1
}

columnify(data, {config: {value: {align: 'right'}}})
```

####  Output:
```
KEY                  VALUE
mocha@1.18.2             1
commander@2.0.0          1
debug@0.8.1              1
```

`align: 'center'` works in a similar way.


### Padding Character

Set a character to fill whitespace within columns with the `paddingChr` option.

```js
var data = {
  "shortKey": "veryVeryVeryVeryVeryLongVal",
  "veryVeryVeryVeryVeryLongKey": "shortVal"
}

columnify(data, { paddingChr: '.'})
```

####  Output:
```
KEY........................ VALUE......................
shortKey................... veryVeryVeryVeryVeryLongVal
veryVeryVeryVeryVeryLongKey shortVal...................
```

### Preserve Existing Newlines

By default, `columnify` sanitises text by replacing any occurance of 1 or more whitespace characters with a single space.

`columnify` can be configured to respect existing new line characters using the `preserveNewLines` option. Note this will still collapse all other whitespace.

```javascript
var data = [{
  name: "glob@3.2.9",
  paths: [
    "node_modules/tap/node_modules/glob",
    "node_modules/tape/node_modules/glob"
  ].join('\n')
}, {
  name: "nopt@2.2.1",
  paths: [
    "node_modules/tap/node_modules/nopt"
  ]
}, {
  name: "runforcover@0.0.2",
  paths: "node_modules/tap/node_modules/runforcover"
}]

console.log(columnify(data, {preserveNewLines: true}))
```
#### Output:
```
NAME              PATHS
glob@3.2.9        node_modules/tap/node_modules/glob
                  node_modules/tape/node_modules/glob
nopt@2.2.1        node_modules/tap/node_modules/nopt
runforcover@0.0.2 node_modules/tap/node_modules/runforcover
```

Compare this with output without `preserveNewLines`:

```javascript
console.log(columnify(data, {preserveNewLines: false}))
// or just
console.log(columnify(data))
```

```
NAME              PATHS
glob@3.2.9        node_modules/tap/node_modules/glob node_modules/tape/node_modules/glob
nopt@2.2.1        node_modules/tap/node_modules/nopt
runforcover@0.0.2 node_modules/tap/node_modules/runforcover
```

### Custom Truncation Marker

You can change the truncation marker to something other than the default
`…` by using the `truncateMarker` option.

```javascript
var columns = columnify(data, {
  truncate: true,
  truncateMarker: '>',
  widths: {
    description: {
      maxWidth: 20
    }
  }
})

console.log(columns)
```
#### Output:
```
NAME       DESCRIPTION          VERSION
mod1       some description>    0.0.1  
module-two another description> 0.2.0  
```

### Custom Column Splitter

If your columns need some bling, you can split columns with custom
characters by using the `columnSplitter` option.

```javascript
var columns = columnify(data, {
  columnSplitter: ' | '
})

console.log(columns)
```
#### Output:
```
NAME       | DESCRIPTION                                                  | VERSION
mod1       | some description which happens to be far larger than the max | 0.0.1
module-two | another description larger than the max                      | 0.2.0
```

### Control Header Display

Control whether column headers are displayed by using the `showHeaders` option.

```javascript
var columns = columnify(data, {
  showHeaders: false
})
```

This also works well for hiding a single column header, like an `id` column:
```javascript
var columns = columnify(data, {
  config: {
    id: { showHeaders: false }
  }
})
```

### Transforming Column Data and Headers
If you need to modify the presentation of column content or heading content there are two useful options for doing that: `dataTransform` and `headerTransform`. Both of these take a function and need to return a valid string.

```javascript
var columns = columnify([{
    name: 'mod1',
    description: 'SOME DESCRIPTION TEXT.'
}, {
    name: 'module-two',
    description: 'SOME SLIGHTLY LONGER DESCRIPTION TEXT.'
}], {
    dataTransform: function(data) {
        return data.toLowerCase()
    },
    config: {
        name: {
            headingTransform: function(heading) {
              heading = "module " + heading
              return "*" +  heading.toUpperCase() + "*"
            }
        }
    }
})
```
#### Output:
```
*MODULE NAME* DESCRIPTION                           
mod1          some description text.                
module-two    some slightly longer description text.
```


## Multibyte Character Support

`columnify` uses [mycoboco/wcwidth.js](https://github.com/mycoboco/wcwidth.js) to calculate length of multibyte characters:

```javascript
var data = [{
  name: 'module-one',
  description: 'some description',
  version: '0.0.1',
}, {
  name: '这是一个很长的名字的模块',
  description: '这真的是一个描述的内容这个描述很长',
  version: "0.3.3"
}]

console.log(columnify(data))
```

#### Without multibyte handling:

i.e. before columnify added this feature

```
NAME         DESCRIPTION       VERSION
module-one   some description  0.0.1
这是一个很长的名字的模块 这真的是一个描述的内容这个描述很长 0.3.3
```

#### With multibyte handling:

```
NAME                     DESCRIPTION                        VERSION
module-one               some description                   0.0.1
这是一个很长的名字的模块 这真的是一个描述的内容这个描述很长 0.3.3
```

## Contributions

```
 project  : columnify
 repo age : 1 year, 2 months
 active   : 32 days
 commits  : 120
 files    : 54
 authors  :
    90	Tim Oxley           75.0%
     8	Tim                 6.7%
     7	Arjun Mehta         5.8%
     6	Dany                5.0%
     5	Wei Gao             4.2%
     2	Dany Shaanan        1.7%
     1	Seth Miller         0.8%
     1	Isaac Z. Schlueter  0.8%
```

## License

MIT
Makefile000064400000000200152045561630006203 0ustar00
all: columnify.js

prepublish: all

columnify.js: index.js package.json
	babel index.js > columnify.js

.PHONY: all prepublish
width.js000064400000000214152045561630006225 0ustar00var stripAnsi = require('strip-ansi')
var wcwidth = require('wcwidth')

module.exports = function(str) {
  return wcwidth(stripAnsi(str))
}
package.json000064400000003353152045561630007045 0ustar00{
  "_args": [
    [
      "columnify@1.5.4",
      "/Users/rebecca/code/npm"
    ]
  ],
  "_from": "columnify@1.5.4",
  "_id": "columnify@1.5.4",
  "_inBundle": false,
  "_integrity": "sha1-Rzfd8ce2mop8NAVweC6UfuyOeLs=",
  "_location": "/columnify",
  "_phantomChildren": {},
  "_requested": {
    "type": "version",
    "registry": true,
    "raw": "columnify@1.5.4",
    "name": "columnify",
    "escapedName": "columnify",
    "rawSpec": "1.5.4",
    "saveSpec": null,
    "fetchSpec": "1.5.4"
  },
  "_requiredBy": [
    "/"
  ],
  "_resolved": "https://registry.npmjs.org/columnify/-/columnify-1.5.4.tgz",
  "_spec": "1.5.4",
  "_where": "/Users/rebecca/code/npm",
  "author": {
    "name": "Tim Oxley"
  },
  "babel": {
    "presets": [
      "es2015"
    ]
  },
  "bugs": {
    "url": "https://github.com/timoxley/columnify/issues"
  },
  "dependencies": {
    "strip-ansi": "^3.0.0",
    "wcwidth": "^1.0.0"
  },
  "description": "Render data in text columns. Supports in-column text-wrap.",
  "devDependencies": {
    "babel": "^6.3.26",
    "babel-cli": "^6.3.17",
    "babel-preset-es2015": "^6.3.13",
    "chalk": "^1.1.1",
    "tap-spec": "^4.1.1",
    "tape": "^4.4.0"
  },
  "directories": {
    "test": "test"
  },
  "homepage": "https://github.com/timoxley/columnify",
  "keywords": [
    "column",
    "text",
    "ansi",
    "console",
    "terminal",
    "wrap",
    "table"
  ],
  "license": "MIT",
  "main": "columnify.js",
  "name": "columnify",
  "repository": {
    "type": "git",
    "url": "git://github.com/timoxley/columnify.git"
  },
  "scripts": {
    "bench": "npm test && node bench",
    "prepublish": "make prepublish",
    "pretest": "npm prune",
    "test": "make prepublish && tape test/*.js | tap-spec"
  },
  "version": "1.5.4"
}
utils.js000064400000011404152045561630006251 0ustar00"use strict"

var wcwidth = require('./width')

/**
 * repeat string `str` up to total length of `len`
 *
 * @param String str string to repeat
 * @param Number len total length of output string
 */

function repeatString(str, len) {
  return Array.apply(null, {length: len + 1}).join(str).slice(0, len)
}

/**
 * Pad `str` up to total length `max` with `chr`.
 * If `str` is longer than `max`, padRight will return `str` unaltered.
 *
 * @param String str string to pad
 * @param Number max total length of output string
 * @param String chr optional. Character to pad with. default: ' '
 * @return String padded str
 */

function padRight(str, max, chr) {
  str = str != null ? str : ''
  str = String(str)
  var length = max - wcwidth(str)
  if (length <= 0) return str
  return str + repeatString(chr || ' ', length)
}

/**
 * Pad `str` up to total length `max` with `chr`.
 * If `str` is longer than `max`, padCenter will return `str` unaltered.
 *
 * @param String str string to pad
 * @param Number max total length of output string
 * @param String chr optional. Character to pad with. default: ' '
 * @return String padded str
 */

function padCenter(str, max, chr) {
  str = str != null ? str : ''
  str = String(str)
  var length = max - wcwidth(str)
  if (length <= 0) return str
  var lengthLeft = Math.floor(length/2)
  var lengthRight = length - lengthLeft
  return repeatString(chr || ' ', lengthLeft) + str + repeatString(chr || ' ', lengthRight)
}

/**
 * Pad `str` up to total length `max` with `chr`, on the left.
 * If `str` is longer than `max`, padRight will return `str` unaltered.
 *
 * @param String str string to pad
 * @param Number max total length of output string
 * @param String chr optional. Character to pad with. default: ' '
 * @return String padded str
 */

function padLeft(str, max, chr) {
  str = str != null ? str : ''
  str = String(str)
  var length = max - wcwidth(str)
  if (length <= 0) return str
  return repeatString(chr || ' ', length) + str
}

/**
 * Split a String `str` into lines of maxiumum length `max`.
 * Splits on word boundaries. Preserves existing new lines.
 *
 * @param String str string to split
 * @param Number max length of each line
 * @return Array Array containing lines.
 */

function splitIntoLines(str, max) {
  function _splitIntoLines(str, max) {
    return str.trim().split(' ').reduce(function(lines, word) {
      var line = lines[lines.length - 1]
      if (line && wcwidth(line.join(' ')) + wcwidth(word) < max) {
        lines[lines.length - 1].push(word) // add to line
      }
      else lines.push([word]) // new line
      return lines
    }, []).map(function(l) {
      return l.join(' ')
    })
  }
  return str.split('\n').map(function(str) {
    return _splitIntoLines(str, max)
  }).reduce(function(lines, line) {
    return lines.concat(line)
  }, [])
}

/**
 * Add spaces and `truncationChar` between words of
 * `str` which are longer than `max`.
 *
 * @param String str string to split
 * @param Number max length of each line
 * @param Number truncationChar character to append to split words
 * @return String
 */

function splitLongWords(str, max, truncationChar) {
  str = str.trim()
  var result = []
  var words = str.split(' ')
  var remainder = ''

  var truncationWidth = wcwidth(truncationChar)

  while (remainder || words.length) {
    if (remainder) {
      var word = remainder
      remainder = ''
    } else {
      var word = words.shift()
    }

    if (wcwidth(word) > max) {
      // slice is based on length no wcwidth
      var i = 0
      var wwidth = 0
      var limit = max - truncationWidth
      while (i < word.length) {
        var w = wcwidth(word.charAt(i))
        if (w + wwidth > limit) {
          break
        }
        wwidth += w
        ++i
      }

      remainder = word.slice(i) // get remainder
      // save remainder for next loop

      word = word.slice(0, i) // grab truncated word
      word += truncationChar // add trailing … or whatever
    }
    result.push(word)
  }

  return result.join(' ')
}


/**
 * Truncate `str` into total width `max`
 * If `str` is shorter than `max`,  will return `str` unaltered.
 *
 * @param String str string to truncated
 * @param Number max total wcwidth of output string
 * @return String truncated str
 */

function truncateString(str, max) {

  str = str != null ? str : ''
  str = String(str)

  if(max == Infinity) return str

  var i = 0
  var wwidth = 0
  while (i < str.length) {
    var w = wcwidth(str.charAt(i))
    if(w + wwidth > max)
      break
    wwidth += w
    ++i
  }
  return str.slice(0, i)
}



/**
 * Exports
 */

module.exports.padRight = padRight
module.exports.padCenter = padCenter
module.exports.padLeft = padLeft
module.exports.splitIntoLines = splitIntoLines
module.exports.splitLongWords = splitLongWords
module.exports.truncateString = truncateString
index.js000064400000022300152045561630006215 0ustar00"use strict"

const wcwidth = require('./width')
const {
  padRight,
  padCenter,
  padLeft,
  splitIntoLines,
  splitLongWords,
  truncateString
} = require('./utils')

const DEFAULT_HEADING_TRANSFORM = key => key.toUpperCase()

const DEFAULT_DATA_TRANSFORM = (cell, column, index) => cell

const DEFAULTS = Object.freeze({
  maxWidth: Infinity,
  minWidth: 0,
  columnSplitter: ' ',
  truncate: false,
  truncateMarker: '…',
  preserveNewLines: false,
  paddingChr: ' ',
  showHeaders: true,
  headingTransform: DEFAULT_HEADING_TRANSFORM,
  dataTransform: DEFAULT_DATA_TRANSFORM
})

module.exports = function(items, options = {}) {

  let columnConfigs = options.config || {}
  delete options.config // remove config so doesn't appear on every column.

  let maxLineWidth = options.maxLineWidth || Infinity
  if (maxLineWidth === 'auto') maxLineWidth = process.stdout.columns || Infinity
  delete options.maxLineWidth // this is a line control option, don't pass it to column

  // Option defaults inheritance:
  // options.config[columnName] => options => DEFAULTS
  options = mixin({}, DEFAULTS, options)

  options.config = options.config || Object.create(null)

  options.spacing = options.spacing || '\n' // probably useless
  options.preserveNewLines = !!options.preserveNewLines
  options.showHeaders = !!options.showHeaders;
  options.columns = options.columns || options.include // alias include/columns, prefer columns if supplied
  let columnNames = options.columns || [] // optional user-supplied columns to include

  items = toArray(items, columnNames)

  // if not suppled column names, automatically determine columns from data keys
  if (!columnNames.length) {
    items.forEach(function(item) {
      for (let columnName in item) {
        if (columnNames.indexOf(columnName) === -1) columnNames.push(columnName)
      }
    })
  }

  // initialize column defaults (each column inherits from options.config)
  let columns = columnNames.reduce((columns, columnName) => {
    let column = Object.create(options)
    columns[columnName] = mixin(column, columnConfigs[columnName])
    return columns
  }, Object.create(null))

  // sanitize column settings
  columnNames.forEach(columnName => {
    let column = columns[columnName]
    column.name = columnName
    column.maxWidth = Math.ceil(column.maxWidth)
    column.minWidth = Math.ceil(column.minWidth)
    column.truncate = !!column.truncate
    column.align = column.align || 'left'
  })

  // sanitize data
  items = items.map(item => {
    let result = Object.create(null)
    columnNames.forEach(columnName => {
      // null/undefined -> ''
      result[columnName] = item[columnName] != null ? item[columnName] : ''
      // toString everything
      result[columnName] = '' + result[columnName]
      if (columns[columnName].preserveNewLines) {
        // merge non-newline whitespace chars
        result[columnName] = result[columnName].replace(/[^\S\n]/gmi, ' ')
      } else {
        // merge all whitespace chars
        result[columnName] = result[columnName].replace(/\s/gmi, ' ')
      }
    })
    return result
  })

  // transform data cells
  columnNames.forEach(columnName => {
    let column = columns[columnName]
    items = items.map((item, index) => {
      let col = Object.create(column)
      item[columnName] = column.dataTransform(item[columnName], col, index)

      let changedKeys = Object.keys(col)
      // disable default heading transform if we wrote to column.name
      if (changedKeys.indexOf('name') !== -1) {
        if (column.headingTransform !== DEFAULT_HEADING_TRANSFORM) return
        column.headingTransform = heading => heading
      }
      changedKeys.forEach(key => column[key] = col[key])
      return item
    })
  })

  // add headers
  let headers = {}
  if(options.showHeaders) {
    columnNames.forEach(columnName => {
      let column = columns[columnName]

      if(!column.showHeaders){
        headers[columnName] = '';
        return;
      }

      headers[columnName] = column.headingTransform(column.name)
    })
    items.unshift(headers)
  }
  // get actual max-width between min & max
  // based on length of data in columns
  columnNames.forEach(columnName => {
    let column = columns[columnName]
    column.width = items
    .map(item => item[columnName])
    .reduce((min, cur) => {
      // if already at maxWidth don't bother testing
      if (min >= column.maxWidth) return min
      return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, wcwidth(cur))))
    }, 0)
  })

  // split long words so they can break onto multiple lines
  columnNames.forEach(columnName => {
    let column = columns[columnName]
    items = items.map(item => {
      item[columnName] = splitLongWords(item[columnName], column.width, column.truncateMarker)
      return item
    })
  })

  // wrap long lines. each item is now an array of lines.
  columnNames.forEach(columnName => {
    let column = columns[columnName]
    items = items.map((item, index) => {
      let cell = item[columnName]
      item[columnName] = splitIntoLines(cell, column.width)

      // if truncating required, only include first line + add truncation char
      if (column.truncate && item[columnName].length > 1) {
        item[columnName] = splitIntoLines(cell, column.width - wcwidth(column.truncateMarker))
        let firstLine = item[columnName][0]
        if (!endsWith(firstLine, column.truncateMarker)) item[columnName][0] += column.truncateMarker
        item[columnName] = item[columnName].slice(0, 1)
      }
      return item
    })
  })

  // recalculate column widths from truncated output/lines
  columnNames.forEach(columnName => {
    let column = columns[columnName]
    column.width = items.map(item => {
      return item[columnName].reduce((min, cur) => {
        if (min >= column.maxWidth) return min
        return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, wcwidth(cur))))
      }, 0)
    }).reduce((min, cur) => {
      if (min >= column.maxWidth) return min
      return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, cur)))
    }, 0)
  })


  let rows = createRows(items, columns, columnNames, options.paddingChr) // merge lines into rows
  // conceive output
  return rows.reduce((output, row) => {
    return output.concat(row.reduce((rowOut, line) => {
      return rowOut.concat(line.join(options.columnSplitter))
    }, []))
  }, [])
  .map(line => truncateString(line, maxLineWidth))
  .join(options.spacing)
}

/**
 * Convert wrapped lines into rows with padded values.
 *
 * @param Array items data to process
 * @param Array columns column width settings for wrapping
 * @param Array columnNames column ordering
 * @return Array items wrapped in arrays, corresponding to lines
 */

function createRows(items, columns, columnNames, paddingChr) {
  return items.map(item => {
    let row = []
    let numLines = 0
    columnNames.forEach(columnName => {
      numLines = Math.max(numLines, item[columnName].length)
    })
    // combine matching lines of each rows
    for (let i = 0; i < numLines; i++) {
      row[i] = row[i] || []
      columnNames.forEach(columnName => {
        let column = columns[columnName]
        let val = item[columnName][i] || '' // || '' ensures empty columns get padded
        if (column.align === 'right') row[i].push(padLeft(val, column.width, paddingChr))
        else if (column.align === 'center' || column.align === 'centre') row[i].push(padCenter(val, column.width, paddingChr))
        else row[i].push(padRight(val, column.width, paddingChr))
      })
    }
    return row
  })
}

/**
 * Object.assign
 *
 * @return Object Object with properties mixed in.
 */

function mixin(...args) {
  if (Object.assign) return Object.assign(...args)
  return ObjectAssign(...args)
}

function ObjectAssign(target, firstSource) {
  "use strict";
  if (target === undefined || target === null)
    throw new TypeError("Cannot convert first argument to object");

  var to = Object(target);

  var hasPendingException = false;
  var pendingException;

  for (var i = 1; i < arguments.length; i++) {
    var nextSource = arguments[i];
    if (nextSource === undefined || nextSource === null)
      continue;

    var keysArray = Object.keys(Object(nextSource));
    for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
      var nextKey = keysArray[nextIndex];
      try {
        var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
        if (desc !== undefined && desc.enumerable)
          to[nextKey] = nextSource[nextKey];
      } catch (e) {
        if (!hasPendingException) {
          hasPendingException = true;
          pendingException = e;
        }
      }
    }

    if (hasPendingException)
      throw pendingException;
  }
  return to;
}

/**
 * Adapted from String.prototype.endsWith polyfill.
 */

function endsWith(target, searchString, position) {
  position = position || target.length;
  position = position - searchString.length;
  let lastIndex = target.lastIndexOf(searchString);
  return lastIndex !== -1 && lastIndex === position;
}


function toArray(items, columnNames) {
  if (Array.isArray(items)) return items
  let rows = []
  for (let key in items) {
    let item = {}
    item[columnNames[0] || 'key'] = key
    item[columnNames[1] || 'value'] = items[key]
    rows.push(item)
  }
  return rows
}