tools: update ESLint to 7.25.0

Update ESLint to 7.25.0

PR-URL: https://github.com/nodejs/node/pull/38378
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
cjihrig authored and James M Snell committed 2021-04-26 11:49:07 -07:00
1 parent 8c99045089
commit 59db84aba1
107 files changed
+1589 -4878

No files matched your search

@@ -15,12 +15,12 @@ const makeDuplexPair = require('../common/duplexpair');
let { clientSide } = makeDuplexPair();
let clientTLS = new TLSSocket(clientSide, { isServer: false });
let clientTLSHandle = clientTLS._handle;
let clientTLSHandle = clientTLS._handle; // eslint-disable-line no-unused-vars
setImmediate(() => {
clientTLS = null;
global.gc();
clientTLSHandle = null; // eslint-disable-line no-unused-vars
clientTLSHandle = null;
global.gc();
setImmediate(() => {
clientSide = null;
+1 -1
View File
@@ -283,7 +283,7 @@ The following companies, organizations, and individuals support ESLint's ongoing
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/photomatt/d0ef3e1/logo.png" alt="Automattic" height="undefined"></a></p><h3>Gold Sponsors</h3>
<p><a href="https://nx.dev"><img src="https://images.opencollective.com/nx/0efbe42/logo.png" alt="Nx (by Nrwl)" height="96"></a> <a href="https://google.com/chrome"><img src="https://images.opencollective.com/chrome/dc55bd4/logo.png" alt="Chrome's Web Framework & Tools Performance Fund" height="96"></a> <a href="https://www.shopify.com"><img src="https://images.opencollective.com/shopify/e780cd4/logo.png" alt="Shopify" height="96"></a> <a href="https://www.salesforce.com"><img src="https://images.opencollective.com/salesforce/ca8f997/logo.png" alt="Salesforce" height="96"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="96"></a> <a href="https://opensource.microsoft.com"><img src="https://avatars.githubusercontent.com/u/6154722?v=4" alt="Microsoft" height="96"></a> <a href="https://substack.com/"><img src="https://avatars.githubusercontent.com/u/53023767?v=4" alt="Substack" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://retool.com/"><img src="https://images.opencollective.com/retool/98ea68e/logo.png" alt="Retool" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a></p><h3>Bronze Sponsors</h3>
<p><a href="https://buy.fineproxy.org/eng/"><img src="https://images.opencollective.com/buy-fineproxy-org/b282e39/logo.png" alt="Buy.Fineproxy.Org" height="32"></a> <a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="null"><img src="https://images.opencollective.com/bugsnag-stability-monitoring/c2cef36/logo.png" alt="Bugsnag Stability Monitoring" height="32"></a> <a href="https://mixpanel.com"><img src="https://images.opencollective.com/mixpanel/cd682f7/logo.png" alt="Mixpanel" height="32"></a> <a href="https://www.vpsserver.com"><img src="https://images.opencollective.com/vpsservercom/logo.png" alt="VPS Server" height="32"></a> <a href="https://icons8.com"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8: free icons, photos, illustrations, and music" height="32"></a> <a href="https://discordapp.com"><img src="https://images.opencollective.com/discordapp/7e3d9a9/logo.png" alt="Discord" height="32"></a> <a href="https://themeisle.com"><img src="https://images.opencollective.com/themeisle/d5592fe/logo.png" alt="ThemeIsle" height="32"></a> <a href="https://www.firesticktricks.com"><img src="https://images.opencollective.com/fire-stick-tricks/b8fbe2c/logo.png" alt="Fire Stick Tricks" height="32"></a></p>
<p><a href="https://buy.fineproxy.org/eng/"><img src="https://images.opencollective.com/buy-fineproxy-org/b282e39/logo.png" alt="Buy.Fineproxy.Org" height="32"></a> <a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="null"><img src="https://images.opencollective.com/bugsnag-stability-monitoring/c2cef36/logo.png" alt="Bugsnag Stability Monitoring" height="32"></a> <a href="https://mixpanel.com"><img src="https://images.opencollective.com/mixpanel/cd682f7/logo.png" alt="Mixpanel" height="32"></a> <a href="https://www.vpsserver.com"><img src="https://images.opencollective.com/vpsservercom/logo.png" alt="VPS Server" height="32"></a> <a href="https://icons8.com"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8: free icons, photos, illustrations, and music" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/7e3d9a9/logo.png" alt="Discord" height="32"></a> <a href="https://themeisle.com"><img src="https://images.opencollective.com/themeisle/d5592fe/logo.png" alt="ThemeIsle" height="32"></a> <a href="https://www.firesticktricks.com"><img src="https://images.opencollective.com/fire-stick-tricks/b8fbe2c/logo.png" alt="Fire Stick Tricks" height="32"></a></p>
<!--sponsorsend-->
## <a name="technology-sponsors"></a>Technology Sponsors
+3 -3
View File
@@ -1308,9 +1308,9 @@ class Linter {
return [];
}
// Resolve configuration again if the file extension was changed.
if (configForRecursive && path.extname(blockName) !== originalExtname) {
debug("Resolving configuration again because the file extension was changed.");
// Resolve configuration again if the file content or extension was changed.
if (configForRecursive && (text !== blockText || path.extname(blockName) !== originalExtname)) {
debug("Resolving configuration again because the file content or extension was changed.");
return this._verifyWithConfigArray(
blockText,
configForRecursive,
+11 -3
View File
@@ -624,10 +624,18 @@ module.exports = {
// Report the first declaration.
if (unusedVar.defs.length > 0) {
// report last write reference, https://github.com/eslint/eslint/issues/14324
const writeReferences = unusedVar.references.filter(ref => ref.isWrite() && ref.from.variableScope === unusedVar.scope.variableScope);
let referenceToReport;
if (writeReferences.length > 0) {
referenceToReport = writeReferences[writeReferences.length - 1];
}
context.report({
node: unusedVar.references.length ? unusedVar.references[
unusedVar.references.length - 1
].identifier : unusedVar.identifiers[0],
node: referenceToReport ? referenceToReport.identifier : unusedVar.identifiers[0],
messageId: "unusedVar",
data: unusedVar.references.some(ref => ref.isWrite())
? getAssignedMessageData(unusedVar)
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2020 Jordan Harband
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.
-2
View File
@@ -1,2 +0,0 @@
# call-bind
Robustly `.call.bind()` a function.
-15
View File
@@ -1,15 +0,0 @@
'use strict';
var GetIntrinsic = require('get-intrinsic');
var callBind = require('./');
var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
module.exports = function callBoundIntrinsic(name, allowMissing) {
var intrinsic = GetIntrinsic(name, !!allowMissing);
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
return callBind(intrinsic);
}
return intrinsic;
};
-47
View File
@@ -1,47 +0,0 @@
'use strict';
var bind = require('function-bind');
var GetIntrinsic = require('get-intrinsic');
var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);
var $defineProperty = GetIntrinsic('%Object.defineProperty%', true);
var $max = GetIntrinsic('%Math.max%');
if ($defineProperty) {
try {
$defineProperty({}, 'a', { value: 1 });
} catch (e) {
// IE 8 has a broken defineProperty
$defineProperty = null;
}
}
module.exports = function callBind(originalFunction) {
var func = $reflectApply(bind, $call, arguments);
if ($gOPD && $defineProperty) {
var desc = $gOPD(func, 'length');
if (desc.configurable) {
// original length, plus the receiver, minus any additional arguments (after the receiver)
$defineProperty(
func,
'length',
{ value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }
);
}
}
return func;
};
var applyBind = function applyBind() {
return $reflectApply(bind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
module.exports.apply = applyBind;
}
-80
View File
@@ -1,80 +0,0 @@
{
"name": "call-bind",
"version": "1.0.2",
"description": "Robustly `.call.bind()` a function",
"main": "index.js",
"exports": {
".": [
{
"default": "./index.js"
},
"./index.js"
],
"./callBound": [
{
"default": "./callBound.js"
},
"./callBound.js"
],
"./package.json": "./package.json"
},
"scripts": {
"prepublish": "safe-publish-latest",
"lint": "eslint --ext=.js,.mjs .",
"pretest": "npm run lint",
"tests-only": "nyc tape 'test/*'",
"test": "npm run tests-only",
"posttest": "aud --production",
"version": "auto-changelog && git add CHANGELOG.md",
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
},
"repository": {
"type": "git",
"url": "git+https://github.com/ljharb/call-bind.git"
},
"keywords": [
"javascript",
"ecmascript",
"es",
"js",
"callbind",
"callbound",
"call",
"bind",
"bound",
"call-bind",
"call-bound",
"function",
"es-abstract"
],
"author": "Jordan Harband <ljharb@gmail.com>",
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/ljharb/call-bind/issues"
},
"homepage": "https://github.com/ljharb/call-bind#readme",
"devDependencies": {
"@ljharb/eslint-config": "^17.3.0",
"aud": "^1.1.3",
"auto-changelog": "^2.2.1",
"eslint": "^7.17.0",
"nyc": "^10.3.2",
"safe-publish-latest": "^1.1.4",
"tape": "^5.1.1"
},
"dependencies": {
"function-bind": "^1.1.1",
"get-intrinsic": "^1.0.2"
},
"auto-changelog": {
"output": "CHANGELOG.md",
"template": "keepachangelog",
"unreleased": false,
"commitLimit": false,
"backfillLimit": false,
"hideCredit": true
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "chalk",
"version": "4.1.0",
"version": "4.1.1",
"description": "Terminal string styling done right",
"license": "MIT",
"repository": "chalk/chalk",
+42
View File
@@ -13,6 +13,48 @@
<img src="https://cdn.jsdelivr.net/gh/chalk/ansi-styles@8261697c95bf34b6c7767e2cbe9941a851d59385/screenshot.svg" width="900">
<br>
---
<div align="center">
<p>
<p>
<sup>
Sindre Sorhus' open source work is supported by the community on <a href="https://github.com/sponsors/sindresorhus">GitHub Sponsors</a> and <a href="https://stakes.social/0x44d871aebF0126Bf646753E2C976Aa7e68A66c15">Dev</a>
</sup>
</p>
<sup>Special thanks to:</sup>
<br>
<br>
<a href="https://standardresume.co/tech">
<img src="https://sindresorhus.com/assets/thanks/standard-resume-logo.svg" width="160"/>
</a>
<br>
<br>
<a href="https://retool.com/?utm_campaign=sindresorhus">
<img src="https://sindresorhus.com/assets/thanks/retool-logo.svg" width="210"/>
</a>
<br>
<br>
<a href="https://doppler.com/?utm_campaign=github_repo&utm_medium=referral&utm_content=chalk&utm_source=github">
<div>
<img src="https://dashboard.doppler.com/imgs/logo-long.svg" width="240" alt="Doppler">
</div>
<b>All your environment variables, in one place</b>
<div>
<span>Stop struggling with scattered API keys, hacking together home-brewed tools,</span>
<br>
<span>and avoiding access controls. Keep your team and servers in sync with Doppler.</span>
</div>
</a>
</p>
</div>
---
<br>
## Highlights
- Expressive API
-176
View File
@@ -1,176 +0,0 @@
{
"es3": true,
"additionalRules": [],
"requireSemicolons": true,
"disallowMultipleSpaces": true,
"disallowIdentifierNames": [],
"requireCurlyBraces": {
"allExcept": [],
"keywords": ["if", "else", "for", "while", "do", "try", "catch"]
},
"requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"],
"disallowSpaceAfterKeywords": [],
"disallowSpaceBeforeComma": true,
"disallowSpaceAfterComma": false,
"disallowSpaceBeforeSemicolon": true,
"disallowNodeTypes": [
"DebuggerStatement",
"ForInStatement",
"LabeledStatement",
"SwitchCase",
"SwitchStatement",
"WithStatement"
],
"requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] },
"requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true },
"requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true },
"disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true },
"requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true },
"disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true },
"requireSpaceBetweenArguments": true,
"disallowSpacesInsideParentheses": true,
"disallowSpacesInsideArrayBrackets": true,
"disallowQuotedKeysInObjects": { "allExcept": ["reserved"] },
"disallowSpaceAfterObjectKeys": true,
"requireCommaBeforeLineBreak": true,
"disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"],
"requireSpaceAfterPrefixUnaryOperators": [],
"disallowSpaceBeforePostfixUnaryOperators": ["++", "--"],
"requireSpaceBeforePostfixUnaryOperators": [],
"disallowSpaceBeforeBinaryOperators": [],
"requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="],
"requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="],
"disallowSpaceAfterBinaryOperators": [],
"disallowImplicitTypeConversion": ["binary", "string"],
"disallowKeywords": ["with", "eval"],
"requireKeywordsOnNewLine": [],
"disallowKeywordsOnNewLine": ["else"],
"requireLineFeedAtFileEnd": true,
"disallowTrailingWhitespace": true,
"disallowTrailingComma": true,
"excludeFiles": ["node_modules/**", "vendor/**"],
"disallowMultipleLineStrings": true,
"requireDotNotation": { "allExcept": ["keywords"] },
"requireParenthesesAroundIIFE": true,
"validateLineBreaks": "LF",
"validateQuoteMarks": {
"escape": true,
"mark": "'"
},
"disallowOperatorBeforeLineBreak": [],
"requireSpaceBeforeKeywords": [
"do",
"for",
"if",
"else",
"switch",
"case",
"try",
"catch",
"finally",
"while",
"with",
"return"
],
"validateAlignedFunctionParameters": {
"lineBreakAfterOpeningBraces": true,
"lineBreakBeforeClosingBraces": true
},
"requirePaddingNewLinesBeforeExport": true,
"validateNewlineAfterArrayElements": {
"maximum": 8
},
"requirePaddingNewLinesAfterUseStrict": true,
"disallowArrowFunctions": true,
"disallowMultiLineTernary": true,
"validateOrderInObjectKeys": "asc-insensitive",
"disallowIdenticalDestructuringNames": true,
"disallowNestedTernaries": { "maxLevel": 1 },
"requireSpaceAfterComma": { "allExcept": ["trailing"] },
"requireAlignedMultilineParams": false,
"requireSpacesInGenerator": {
"afterStar": true
},
"disallowSpacesInGenerator": {
"beforeStar": true
},
"disallowVar": false,
"requireArrayDestructuring": false,
"requireEnhancedObjectLiterals": false,
"requireObjectDestructuring": false,
"requireEarlyReturn": false,
"requireCapitalizedConstructorsNew": {
"allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"]
},
"requireImportAlphabetized": false,
"requireSpaceBeforeObjectValues": true,
"requireSpaceBeforeDestructuredValues": true,
"disallowSpacesInsideTemplateStringPlaceholders": true,
"disallowArrayDestructuringReturn": false,
"requireNewlineBeforeSingleStatementsInIf": false,
"disallowUnusedVariables": true,
"requireSpacesInsideImportedObjectBraces": true,
"requireUseStrict": true
}
-20
View File
@@ -1,20 +0,0 @@
Copyright (c) 2013 Raynos.
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.
-48
View File
@@ -1,48 +0,0 @@
# function-bind
<!--
[![build status][travis-svg]][travis-url]
[![NPM version][npm-badge-svg]][npm-url]
[![Coverage Status][5]][6]
[![gemnasium Dependency Status][7]][8]
[![Dependency status][deps-svg]][deps-url]
[![Dev Dependency status][dev-deps-svg]][dev-deps-url]
-->
<!-- [![browser support][11]][12] -->
Implementation of function.prototype.bind
## Example
I mainly do this for unit tests I run on phantomjs.
PhantomJS does not have Function.prototype.bind :(
```js
Function.prototype.bind = require("function-bind")
```
## Installation
`npm install function-bind`
## Contributors
- Raynos
## MIT Licenced
[travis-svg]: https://travis-ci.org/Raynos/function-bind.svg
[travis-url]: https://travis-ci.org/Raynos/function-bind
[npm-badge-svg]: https://badge.fury.io/js/function-bind.svg
[npm-url]: https://npmjs.org/package/function-bind
[5]: https://coveralls.io/repos/Raynos/function-bind/badge.png
[6]: https://coveralls.io/r/Raynos/function-bind
[7]: https://gemnasium.com/Raynos/function-bind.png
[8]: https://gemnasium.com/Raynos/function-bind
[deps-svg]: https://david-dm.org/Raynos/function-bind.svg
[deps-url]: https://david-dm.org/Raynos/function-bind
[dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg
[dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies
[11]: https://ci.testling.com/Raynos/function-bind.png
[12]: https://ci.testling.com/Raynos/function-bind
-52
View File
@@ -1,52 +0,0 @@
'use strict';
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var slice = Array.prototype.slice;
var toStr = Object.prototype.toString;
var funcType = '[object Function]';
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.call(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slice.call(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
args.concat(slice.call(arguments))
);
if (Object(result) === result) {
return result;
}
return this;
} else {
return target.apply(
that,
args.concat(slice.call(arguments))
);
}
};
var boundLength = Math.max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs.push('$' + i);
}
bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
-5
View File
@@ -1,5 +0,0 @@
'use strict';
var implementation = require('./implementation');
module.exports = Function.prototype.bind || implementation;
-63
View File
@@ -1,63 +0,0 @@
{
"name": "function-bind",
"version": "1.1.1",
"description": "Implementation of Function.prototype.bind",
"keywords": [
"function",
"bind",
"shim",
"es5"
],
"author": "Raynos <raynos2@gmail.com>",
"repository": "git://github.com/Raynos/function-bind.git",
"main": "index",
"homepage": "https://github.com/Raynos/function-bind",
"contributors": [
{
"name": "Raynos"
},
{
"name": "Jordan Harband",
"url": "https://github.com/ljharb"
}
],
"bugs": {
"url": "https://github.com/Raynos/function-bind/issues",
"email": "raynos2@gmail.com"
},
"dependencies": {},
"devDependencies": {
"@ljharb/eslint-config": "^12.2.1",
"covert": "^1.1.0",
"eslint": "^4.5.0",
"jscs": "^3.0.7",
"tape": "^4.8.0"
},
"license": "MIT",
"scripts": {
"pretest": "npm run lint",
"test": "npm run tests-only",
"posttest": "npm run coverage -- --quiet",
"tests-only": "node test",
"coverage": "covert test/*.js",
"lint": "npm run jscs && npm run eslint",
"jscs": "jscs *.js */*.js",
"eslint": "eslint *.js */*.js"
},
"testling": {
"files": "test/index.js",
"browsers": [
"ie/8..latest",
"firefox/16..latest",
"firefox/nightly",
"chrome/22..latest",
"chrome/canary",
"opera/12..latest",
"opera/next",
"safari/5.1..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2..latest"
]
}
}
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2020 Jordan Harband
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.
-65
View File
@@ -1,65 +0,0 @@
# get-intrinsic <sup>[![Version Badge][npm-version-svg]][package-url]</sup>
[![dependency status][deps-svg]][deps-url]
[![dev dependency status][dev-deps-svg]][dev-deps-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][npm-badge-png]][package-url]
Get and robustly cache all JS language-level intrinsics at first require time.
See the syntax described [in the JS spec](https://tc39.es/ecma262/#sec-well-known-intrinsic-objects) for reference.
## Example
```js
var GetIntrinsic = require('get-intrinsic');
var assert = require('assert');
// static methods
assert.equal(GetIntrinsic('%Math.pow%'), Math.pow);
assert.equal(Math.pow(2, 3), 8);
assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8);
delete Math.pow;
assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8);
// instance methods
var arr = [1];
assert.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push);
assert.deepEqual(arr, [1]);
arr.push(2);
assert.deepEqual(arr, [1, 2]);
GetIntrinsic('%Array.prototype.push%').call(arr, 3);
assert.deepEqual(arr, [1, 2, 3]);
delete Array.prototype.push;
GetIntrinsic('%Array.prototype.push%').call(arr, 4);
assert.deepEqual(arr, [1, 2, 3, 4]);
// missing features
delete JSON.parse; // to simulate a real intrinsic that is missing in the environment
assert.throws(() => GetIntrinsic('%JSON.parse%'));
assert.equal(undefined, GetIntrinsic('%JSON.parse%', true));
```
## Tests
Simply clone the repo, `npm install`, and run `npm test`
## Security
Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report.
[package-url]: https://npmjs.org/package/get-intrinsic
[npm-version-svg]: http://versionbadg.es/ljharb/get-intrinsic.svg
[deps-svg]: https://david-dm.org/ljharb/get-intrinsic.svg
[deps-url]: https://david-dm.org/ljharb/get-intrinsic
[dev-deps-svg]: https://david-dm.org/ljharb/get-intrinsic/dev-status.svg
[dev-deps-url]: https://david-dm.org/ljharb/get-intrinsic#info=devDependencies
[npm-badge-png]: https://nodei.co/npm/get-intrinsic.png?downloads=true&stars=true
[license-image]: https://img.shields.io/npm/l/get-intrinsic.svg
[license-url]: LICENSE
[downloads-image]: https://img.shields.io/npm/dm/get-intrinsic.svg
[downloads-url]: https://npm-stat.com/charts.html?package=get-intrinsic
-330
View File
@@ -1,330 +0,0 @@
'use strict';
var undefined;
var $SyntaxError = SyntaxError;
var $Function = Function;
var $TypeError = TypeError;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = require('has-symbols')();
var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);
var INTRINSICS = {
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': RangeError,
'%ReferenceError%': ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = require('function-bind');
var hasOwn = require('has');
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
-78
View File
@@ -1,78 +0,0 @@
{
"name": "get-intrinsic",
"version": "1.1.1",
"description": "Get and robustly cache all JS language-level intrinsics at first require time",
"main": "index.js",
"exports": {
".": [
{
"default": "./index.js"
},
"./index.js"
],
"./package.json": "./package.json"
},
"scripts": {
"prelint": "evalmd README.md",
"lint": "eslint --ext=.js,.mjs .",
"pretest": "npm run lint",
"tests-only": "nyc tape 'test/**/*.js'",
"test": "npm run tests-only",
"posttest": "aud --production",
"version": "auto-changelog && git add CHANGELOG.md",
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
},
"repository": {
"type": "git",
"url": "git+https://github.com/ljharb/get-intrinsic.git"
},
"keywords": [
"javascript",
"ecmascript",
"es",
"js",
"intrinsic",
"getintrinsic",
"es-abstract"
],
"author": "Jordan Harband <ljharb@gmail.com>",
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/ljharb/get-intrinsic/issues"
},
"homepage": "https://github.com/ljharb/get-intrinsic#readme",
"devDependencies": {
"@ljharb/eslint-config": "^17.5.0",
"aud": "^1.1.3",
"auto-changelog": "^2.2.1",
"call-bind": "^1.0.2",
"es-abstract": "^1.18.0-next.2",
"es-value-fixtures": "^1.0.0",
"eslint": "^7.19.0",
"evalmd": "^0.0.19",
"foreach": "^2.0.5",
"has-bigints": "^1.0.1",
"make-async-function": "^1.0.0",
"make-async-generator-function": "^1.0.0",
"make-generator-function": "^2.0.0",
"nyc": "^10.3.2",
"object-inspect": "^1.9.0",
"tape": "^5.1.1"
},
"auto-changelog": {
"output": "CHANGELOG.md",
"template": "keepachangelog",
"unreleased": false,
"commitLimit": false,
"backfillLimit": false,
"hideCredit": true
},
"dependencies": {
"function-bind": "^1.1.1",
"has": "^1.0.3",
"has-symbols": "^1.0.1"
}
}
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2016 Jordan Harband
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.
-40
View File
@@ -1,40 +0,0 @@
# has-symbols <sup>[![Version Badge][2]][1]</sup>
[![dependency status][5]][6]
[![dev dependency status][7]][8]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][11]][1]
Determine if the JS environment has Symbol support. Supports spec, or shams.
## Example
```js
var hasSymbols = require('has-symbols');
hasSymbols() === true; // if the environment has native Symbol support. Not polyfillable, not forgeable.
var hasSymbolsKinda = require('has-symbols/shams');
hasSymbolsKinda() === true; // if the environment has a Symbol sham that mostly follows the spec.
```
## Supported Symbol shams
- get-own-property-symbols [npm](https://www.npmjs.com/package/get-own-property-symbols) | [github](https://github.com/WebReflection/get-own-property-symbols)
- core-js [npm](https://www.npmjs.com/package/core-js) | [github](https://github.com/zloirock/core-js)
## Tests
Simply clone the repo, `npm install`, and run `npm test`
[1]: https://npmjs.org/package/has-symbols
[2]: https://versionbadg.es/inspect-js/has-symbols.svg
[5]: https://david-dm.org/inspect-js/has-symbols.svg
[6]: https://david-dm.org/inspect-js/has-symbols
[7]: https://david-dm.org/inspect-js/has-symbols/dev-status.svg
[8]: https://david-dm.org/inspect-js/has-symbols#info=devDependencies
[11]: https://nodei.co/npm/has-symbols.png?downloads=true&stars=true
[license-image]: https://img.shields.io/npm/l/has-symbols.svg
[license-url]: LICENSE
[downloads-image]: https://img.shields.io/npm/dm/has-symbols.svg
[downloads-url]: https://npm-stat.com/charts.html?package=has-symbols
-13
View File
@@ -1,13 +0,0 @@
'use strict';
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = require('./shams');
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
-96
View File
@@ -1,96 +0,0 @@
{
"name": "has-symbols",
"version": "1.0.2",
"author": {
"name": "Jordan Harband",
"email": "ljharb@gmail.com",
"url": "http://ljharb.codes"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"contributors": [
{
"name": "Jordan Harband",
"email": "ljharb@gmail.com",
"url": "http://ljharb.codes"
}
],
"description": "Determine if the JS environment has Symbol support. Supports spec, or shams.",
"license": "MIT",
"main": "index.js",
"scripts": {
"prepublish": "safe-publish-latest",
"pretest": "npm run --silent lint",
"test": "npm run tests-only",
"posttest": "aud --production",
"tests-only": "npm run test:stock && npm run test:staging && npm run test:shams",
"test:stock": "nyc node test",
"test:staging": "nyc node --harmony --es-staging test",
"test:shams": "npm run --silent test:shams:getownpropertysymbols && npm run --silent test:shams:corejs",
"test:shams:corejs": "nyc node test/shams/core-js.js",
"test:shams:getownpropertysymbols": "nyc node test/shams/get-own-property-symbols.js",
"lint": "eslint --ext=js,mjs .",
"version": "auto-changelog && git add CHANGELOG.md",
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
},
"repository": {
"type": "git",
"url": "git://github.com/inspect-js/has-symbols.git"
},
"keywords": [
"Symbol",
"symbols",
"typeof",
"sham",
"polyfill",
"native",
"core-js",
"ES6"
],
"devDependencies": {
"@ljharb/eslint-config": "^17.5.1",
"aud": "^1.1.4",
"auto-changelog": "^2.2.1",
"core-js": "^2.6.12",
"eslint": "^7.20.0",
"get-own-property-symbols": "^0.9.5",
"nyc": "^10.3.2",
"safe-publish-latest": "^1.1.4",
"tape": "^5.2.0"
},
"testling": {
"files": "test/index.js",
"browsers": [
"iexplore/6.0..latest",
"firefox/3.0..6.0",
"firefox/15.0..latest",
"firefox/nightly",
"chrome/4.0..10.0",
"chrome/20.0..latest",
"chrome/canary",
"opera/10.0..latest",
"opera/next",
"safari/4.0..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2"
]
},
"engines": {
"node": ">= 0.4"
},
"auto-changelog": {
"output": "CHANGELOG.md",
"template": "keepachangelog",
"unreleased": false,
"commitLimit": false,
"backfillLimit": false,
"hideCredit": true
},
"greenkeeper": {
"ignore": [
"core-js"
]
}
}
-42
View File
@@ -1,42 +0,0 @@
'use strict';
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
-22
View File
@@ -1,22 +0,0 @@
Copyright (c) 2013 Thiago de Arruda
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.
-18
View File
@@ -1,18 +0,0 @@
# has
> Object.prototype.hasOwnProperty.call shortcut
## Installation
```sh
npm install --save has
```
## Usage
```js
var has = require('has');
has({}, 'hasOwnProperty'); // false
has(Object.prototype, 'hasOwnProperty'); // true
```
-48
View File
@@ -1,48 +0,0 @@
{
"name": "has",
"description": "Object.prototype.hasOwnProperty.call shortcut",
"version": "1.0.3",
"homepage": "https://github.com/tarruda/has",
"author": {
"name": "Thiago de Arruda",
"email": "tpadilha84@gmail.com"
},
"contributors": [
{
"name": "Jordan Harband",
"email": "ljharb@gmail.com",
"url": "http://ljharb.codes"
}
],
"repository": {
"type": "git",
"url": "git://github.com/tarruda/has.git"
},
"bugs": {
"url": "https://github.com/tarruda/has/issues"
},
"license": "MIT",
"licenses": [
{
"type": "MIT",
"url": "https://github.com/tarruda/has/blob/master/LICENSE-MIT"
}
],
"main": "./src",
"dependencies": {
"function-bind": "^1.1.1"
},
"devDependencies": {
"@ljharb/eslint-config": "^12.2.1",
"eslint": "^4.19.1",
"tape": "^4.9.0"
},
"engines": {
"node": ">= 0.4.0"
},
"scripts": {
"lint": "eslint .",
"pretest": "npm run lint",
"test": "tape test"
}
}
-5
View File
@@ -1,5 +0,0 @@
'use strict';
var bind = require('function-bind');
module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);
-22
View File
@@ -1,22 +0,0 @@
The MIT License (MIT)
Copyright (c) 2015 Jordan Harband
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.
-58
View File
@@ -1,58 +0,0 @@
# is-boolean-object <sup>[![Version Badge][2]][1]</sup>
[![Build Status][3]][4]
[![dependency status][5]][6]
[![dev dependency status][7]][8]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][11]][1]
[![browser support][9]][10]
Is this value a JS Boolean? This module works cross-realm/iframe, and despite ES6 @@toStringTag.
## Example
```js
var isBoolean = require('is-boolean-object');
var assert = require('assert');
assert.notOk(isBoolean(undefined));
assert.notOk(isBoolean(null));
assert.notOk(isBoolean('foo'));
assert.notOk(isBoolean(function () {}));
assert.notOk(isBoolean([]));
assert.notOk(isBoolean({}));
assert.notOk(isBoolean(/a/g));
assert.notOk(isBoolean(new RegExp('a', 'g')));
assert.notOk(isBoolean(new Date()));
assert.notOk(isBoolean(42));
assert.notOk(isBoolean(NaN));
assert.notOk(isBoolean(Infinity));
assert.ok(isBoolean(new Boolean(42)));
assert.ok(isBoolean(false));
assert.ok(isBoolean(Object(false)));
assert.ok(isBoolean(true));
assert.ok(isBoolean(Object(true)));
```
## Tests
Simply clone the repo, `npm install`, and run `npm test`
[1]: https://npmjs.org/package/is-boolean-object
[2]: http://versionbadg.es/ljharb/is-boolean-object.svg
[3]: https://travis-ci.org/ljharb/is-boolean-object.svg
[4]: https://travis-ci.org/ljharb/is-boolean-object
[5]: https://david-dm.org/ljharb/is-boolean-object.svg
[6]: https://david-dm.org/ljharb/is-boolean-object
[7]: https://david-dm.org/ljharb/is-boolean-object/dev-status.svg
[8]: https://david-dm.org/ljharb/is-boolean-object#info=devDependencies
[9]: https://ci.testling.com/ljharb/is-boolean-object.png
[10]: https://ci.testling.com/ljharb/is-boolean-object
[11]: https://nodei.co/npm/is-boolean-object.png?downloads=true&stars=true
[license-image]: http://img.shields.io/npm/l/is-boolean-object.svg
[license-url]: LICENSE
[downloads-image]: http://img.shields.io/npm/dm/is-boolean-object.svg
[downloads-url]: http://npm-stat.com/charts.html?package=is-boolean-object
-26
View File
@@ -1,26 +0,0 @@
'use strict';
var callBound = require('call-bind/callBound');
var $boolToStr = callBound('Boolean.prototype.toString');
var $toString = callBound('Object.prototype.toString');
var tryBooleanObject = function booleanBrandCheck(value) {
try {
$boolToStr(value);
return true;
} catch (e) {
return false;
}
};
var boolClass = '[object Boolean]';
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
module.exports = function isBoolean(value) {
if (typeof value === 'boolean') {
return true;
}
if (value === null || typeof value !== 'object') {
return false;
}
return hasToStringTag && Symbol.toStringTag in value ? tryBooleanObject(value) : $toString(value) === boolClass;
};
-83
View File
@@ -1,83 +0,0 @@
{
"name": "is-boolean-object",
"version": "1.1.0",
"author": "Jordan Harband <ljharb@gmail.com>",
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"description": "Is this value a JS Boolean? This module works cross-realm/iframe, and despite ES6 @@toStringTag.",
"license": "MIT",
"main": "index.js",
"scripts": {
"prepublish": "safe-publish-latest",
"pretest": "npm run lint",
"test": "npm run tests-only && npm run test:harmony",
"tests-only": "nyc tape 'test/**/*.js'",
"test:harmony": "node --harmony --es-staging test",
"posttest": "aud --production",
"prelint": "npm run eccheck",
"lint": "eslint --ext=js,mjs .",
"eccheck": "eclint check $(git ls-files)",
"version": "auto-changelog && git add CHANGELOG.md",
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
},
"repository": {
"type": "git",
"url": "git://github.com/ljharb/is-boolean-object.git"
},
"keywords": [
"Boolean",
"ES6",
"toStringTag",
"@@toStringTag",
"Boolean object",
"true",
"false",
"is-boolean"
],
"dependencies": {
"call-bind": "^1.0.0"
},
"devDependencies": {
"@ljharb/eslint-config": "^17.3.0",
"aud": "^1.1.3",
"auto-changelog": "^2.2.1",
"eclint": "^2.8.1",
"eslint": "^7.15.0",
"foreach": "^2.0.5",
"indexof": "^0.0.1",
"is": "^3.3.0",
"nyc": "^10.3.2",
"safe-publish-latest": "^1.1.4",
"tape": "^5.0.1"
},
"testling": {
"files": "test.js",
"browsers": [
"iexplore/6.0..latest",
"firefox/3.0..6.0",
"firefox/15.0..latest",
"firefox/nightly",
"chrome/4.0..10.0",
"chrome/20.0..latest",
"chrome/canary",
"opera/10.0..latest",
"opera/next",
"safari/4.0..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2"
]
},
"engines": {
"node": ">= 0.4"
},
"auto-changelog": {
"output": "CHANGELOG.md",
"template": "keepachangelog",
"unreleased": false,
"commitLimit": false,
"backfillLimit": false,
"hideCredit": true
}
}
-22
View File
@@ -1,22 +0,0 @@
The MIT License (MIT)
Copyright (c) 2015 Jordan Harband
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.
-52
View File
@@ -1,52 +0,0 @@
# is-number-object <sup>[![Version Badge][2]][1]</sup>
[![Build Status][3]][4]
[![dependency status][5]][6]
[![dev dependency status][7]][8]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][11]][1]
Is this value a JS Number object? This module works cross-realm/iframe, and despite ES6 @@toStringTag.
## Example
```js
var isNumber = require('is-number-object');
var assert = require('assert');
assert.notOk(isNumber(undefined));
assert.notOk(isNumber(null));
assert.notOk(isNumber(false));
assert.notOk(isNumber(true));
assert.notOk(isNumber('foo'));
assert.notOk(isNumber(function () {}));
assert.notOk(isNumber([]));
assert.notOk(isNumber({}));
assert.notOk(isNumber(/a/g));
assert.notOk(isNumber(new RegExp('a', 'g')));
assert.notOk(isNumber(new Date()));
assert.ok(isNumber(42));
assert.ok(isNumber(NaN));
assert.ok(isNumber(Infinity));
assert.ok(isNumber(new Number(42)));
```
## Tests
Simply clone the repo, `npm install`, and run `npm test`
[1]: https://npmjs.org/package/is-number-object
[2]: http://versionbadg.es/inspect-js/is-number-object.svg
[3]: https://travis-ci.org/inspect-js/is-number-object.svg
[4]: https://travis-ci.org/inspect-js/is-number-object
[5]: https://david-dm.org/inspect-js/is-number-object.svg
[6]: https://david-dm.org/inspect-js/is-number-object
[7]: https://david-dm.org/inspect-js/is-number-object/dev-status.svg
[8]: https://david-dm.org/inspect-js/is-number-object#info=devDependencies
[11]: https://nodei.co/npm/is-number-object.png?downloads=true&stars=true
[license-image]: http://img.shields.io/npm/l/is-number-object.svg
[license-url]: LICENSE
[downloads-image]: http://img.shields.io/npm/dm/is-number-object.svg
[downloads-url]: http://npm-stat.com/charts.html?package=is-number-object
-24
View File
@@ -1,24 +0,0 @@
'use strict';
var numToStr = Number.prototype.toString;
var tryNumberObject = function tryNumberObject(value) {
try {
numToStr.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr = Object.prototype.toString;
var numClass = '[object Number]';
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
module.exports = function isNumberObject(value) {
if (typeof value === 'number') {
return true;
}
if (typeof value !== 'object') {
return false;
}
return hasToStringTag ? tryNumberObject(value) : toStr.call(value) === numClass;
};
-76
View File
@@ -1,76 +0,0 @@
{
"name": "is-number-object",
"version": "1.0.4",
"author": "Jordan Harband <ljharb@gmail.com>",
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"description": "Is this value a JS Number object? This module works cross-realm/iframe, and despite ES6 @@toStringTag.",
"license": "MIT",
"main": "index.js",
"scripts": {
"prepublish": "safe-publish-latest",
"pretest": "npm run lint",
"tests-only": "node --harmony --es-staging test",
"test": "npm run tests-only",
"posttest": "npx aud",
"coverage": "covert test/index.js",
"lint": "eslint .",
"eccheck": "eclint check *.js **/*.js > /dev/null",
"version": "auto-changelog && git add CHANGELOG.md",
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
},
"repository": {
"type": "git",
"url": "git://github.com/inspect-js/is-number-object.git"
},
"keywords": [
"Number",
"ES6",
"toStringTag",
"@@toStringTag",
"Number object"
],
"dependencies": {},
"devDependencies": {
"@ljharb/eslint-config": "^15.0.2",
"auto-changelog": "^1.16.2",
"covert": "^1.1.1",
"eclint": "^2.8.1",
"eslint": "^6.7.2",
"foreach": "^2.0.5",
"has-symbols": "^1.0.1",
"indexof": "^0.0.1",
"is": "^3.3.0",
"safe-publish-latest": "^1.1.4",
"tape": "^4.12.0"
},
"testling": {
"files": "test/index.js",
"browsers": [
"iexplore/6.0..latest",
"firefox/3.0..6.0",
"firefox/15.0..latest",
"firefox/nightly",
"chrome/4.0..10.0",
"chrome/20.0..latest",
"chrome/canary",
"opera/10.0..latest",
"opera/next",
"safari/4.0..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2"
]
},
"engines": {
"node": ">= 0.4"
},
"auto-changelog": {
"output": "CHANGELOG.md",
"template": "keepachangelog",
"unreleased": false,
"commitLimit": false,
"backfillLimit": false
}
}
-22
View File
@@ -1,22 +0,0 @@
The MIT License (MIT)
Copyright (c) 2015 Jordan Harband
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.
-57
View File
@@ -1,57 +0,0 @@
# is-string <sup>[![Version Badge][2]][1]</sup>
[![Build Status][3]][4]
[![dependency status][5]][6]
[![dev dependency status][7]][8]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][11]][1]
[![browser support][9]][10]
Is this value a JS String object or primitive? This module works cross-realm/iframe, and despite ES6 @@toStringTag.
## Example
```js
var isString = require('is-string');
var assert = require('assert');
assert.notOk(isString(undefined));
assert.notOk(isString(null));
assert.notOk(isString(false));
assert.notOk(isString(true));
assert.notOk(isString(function () {}));
assert.notOk(isString([]));
assert.notOk(isString({}));
assert.notOk(isString(/a/g));
assert.notOk(isString(new RegExp('a', 'g')));
assert.notOk(isString(new Date()));
assert.notOk(isString(42));
assert.notOk(isString(NaN));
assert.notOk(isString(Infinity));
assert.notOk(isString(new Number(42)));
assert.ok(isString('foo'));
assert.ok(isString(Object('foo')));
```
## Tests
Simply clone the repo, `npm install`, and run `npm test`
[1]: https://npmjs.org/package/is-string
[2]: http://versionbadg.es/ljharb/is-string.svg
[3]: https://travis-ci.org/ljharb/is-string.svg
[4]: https://travis-ci.org/ljharb/is-string
[5]: https://david-dm.org/ljharb/is-string.svg
[6]: https://david-dm.org/ljharb/is-string
[7]: https://david-dm.org/ljharb/is-string/dev-status.svg
[8]: https://david-dm.org/ljharb/is-string#info=devDependencies
[9]: https://ci.testling.com/ljharb/is-string.png
[10]: https://ci.testling.com/ljharb/is-string
[11]: https://nodei.co/npm/is-string.png?downloads=true&stars=true
[license-image]: http://img.shields.io/npm/l/is-string.svg
[license-url]: LICENSE
[downloads-image]: http://img.shields.io/npm/dm/is-string.svg
[downloads-url]: http://npm-stat.com/charts.html?package=is-string
-24
View File
@@ -1,24 +0,0 @@
'use strict';
var strValue = String.prototype.valueOf;
var tryStringObject = function tryStringObject(value) {
try {
strValue.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr = Object.prototype.toString;
var strClass = '[object String]';
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
module.exports = function isString(value) {
if (typeof value === 'string') {
return true;
}
if (typeof value !== 'object') {
return false;
}
return hasToStringTag ? tryStringObject(value) : toStr.call(value) === strClass;
};
-76
View File
@@ -1,76 +0,0 @@
{
"name": "is-string",
"version": "1.0.5",
"author": "Jordan Harband <ljharb@gmail.com>",
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"description": "Is this value a JS String object or primitive? This module works cross-realm/iframe, and despite ES6 @@toStringTag.",
"license": "MIT",
"main": "index.js",
"scripts": {
"prepublish": "safe-publish-latest",
"pretest": "npm run lint",
"tests-only": "node --harmony --es-staging test",
"test": "npm run tests-only",
"posttest": "npx aud",
"coverage": "covert test/index.js",
"lint": "eslint .",
"eccheck": "eclint check *.js **/*.js > /dev/null",
"version": "auto-changelog && git add CHANGELOG.md",
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
},
"repository": {
"type": "git",
"url": "git://github.com/ljharb/is-string.git"
},
"keywords": [
"String",
"string",
"ES6",
"toStringTag",
"@@toStringTag",
"String object"
],
"dependencies": {},
"devDependencies": {
"@ljharb/eslint-config": "^15.0.2",
"auto-changelog": "^1.16.2",
"covert": "^1.1.1",
"eclint": "^2.8.1",
"eslint": "^6.7.2",
"foreach": "^2.0.5",
"indexof": "^0.0.1",
"is": "^3.3.0",
"safe-publish-latest": "^1.1.4",
"tape": "^4.12.0"
},
"testling": {
"files": "test/index.js",
"browsers": [
"iexplore/6.0..latest",
"firefox/3.0..6.0",
"firefox/15.0..latest",
"firefox/nightly",
"chrome/4.0..10.0",
"chrome/20.0..latest",
"chrome/canary",
"opera/10.0..latest",
"opera/next",
"safari/4.0..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2"
]
},
"engines": {
"node": ">= 0.4"
},
"auto-changelog": {
"output": "CHANGELOG.md",
"template": "keepachangelog",
"unreleased": false,
"commitLimit": false,
"backfillLimit": false
}
}
+53 -1
View File
@@ -14,6 +14,7 @@
* [Cell Content Alignment](#table-usage-cell-content-alignment)
* [Column Width](#table-usage-column-width)
* [Custom Border](#table-usage-custom-border)
* [Draw Vertical Line](#table-usage-draw-vertical-line)
* [Draw Horizontal Line](#table-usage-draw-horizontal-line)
* [Single Line Mode](#table-usage-single-line-mode)
* [Padding Cell Content](#table-usage-padding-cell-content)
@@ -292,6 +293,57 @@ console.log(output);
└────┴────┴────┘
```
<a name="table-usage-draw-vertical-line"></a>
### Draw Vertical Line
`{function} config.drawVerticalLine` property is a function that is called for every non-content column in the table. The result of the function `{boolean}` determines whether a border is drawn.
```js
let data,
output,
options;
data = [
['0A', '0B', '0C'],
['1A', '1B', '1C'],
['2A', '2B', '2C'],
['3A', '3B', '3C'],
['4A', '4B', '4C']
];
options = {
/**
* @typedef {function} drawVerticalLine
* @param {number} index
* @param {number} size
* @return {boolean}
*/
drawVerticalLine: (index, size) => {
return index === 0 || index === size;
}
};
output = table(data, options);
console.log(output);
```
```
╔════════════╗
║ 0A 0B 0C ║
╟────────────╢
║ 1A 1B 1C ║
╟────────────╢
║ 2A 2B 2C ║
╟────────────╢
║ 3A 3B 3C ║
╟────────────╢
║ 4A 4B 4C ║
╚════════════╝
```
<a name="table-usage-draw-horizontal-line"></a>
### Draw Horizontal Line
@@ -647,7 +699,7 @@ console.log(output);
║ t amet, consectetur ║
║ adipiscing elit. Pha ║
║ sellus pulvinar nibh ║
║ sed mauris conva... ║
║ sed mauris convall… ║
╚══════════════════════╝
```
+35 -95
View File
@@ -1,107 +1,47 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _isNumberObject = _interopRequireDefault(require("is-number-object"));
var _isString = _interopRequireDefault(require("is-string"));
var _stringWidth = _interopRequireDefault(require("string-width"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const alignments = ['left', 'right', 'center'];
/**
* @param {string} subject
* @param {number} width
* @returns {string}
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const string_width_1 = __importDefault(require("string-width"));
const alignLeft = (subject, width) => {
return subject + ' '.repeat(width);
return subject + ' '.repeat(width);
};
/**
* @param {string} subject
* @param {number} width
* @returns {string}
*/
const alignRight = (subject, width) => {
return ' '.repeat(width) + subject;
return ' '.repeat(width) + subject;
};
/**
* @param {string} subject
* @param {number} width
* @returns {string}
*/
const alignCenter = (subject, width) => {
let halfWidth;
halfWidth = width / 2;
if (width % 2 === 0) {
return ' '.repeat(halfWidth) + subject + ' '.repeat(halfWidth);
} else {
halfWidth = Math.floor(halfWidth);
return ' '.repeat(halfWidth) + subject + ' '.repeat(halfWidth + 1);
}
let halfWidth;
halfWidth = width / 2;
if (width % 2 === 0) {
return ' '.repeat(halfWidth) + subject + ' '.repeat(halfWidth);
}
else {
halfWidth = Math.floor(halfWidth);
return ' '.repeat(halfWidth) + subject + ' '.repeat(halfWidth + 1);
}
};
/**
* Pads a string to the left and/or right to position the subject
* text in a desired alignment within a container.
*
* @param {string} subject
* @param {number} containerWidth
* @param {string} alignment One of the valid options (left, right, center).
* @returns {string}
*/
const alignString = (subject, containerWidth, alignment) => {
if (!(0, _isString.default)(subject)) {
throw new TypeError('Subject parameter value must be a string.');
}
if (!(0, _isNumberObject.default)(containerWidth)) {
throw new TypeError('Container width parameter value must be a number.');
}
const subjectWidth = (0, _stringWidth.default)(subject);
if (subjectWidth > containerWidth) {
// console.log('subjectWidth', subjectWidth, 'containerWidth', containerWidth, 'subject', subject);
throw new Error('Subject parameter value width cannot be greater than the container width.');
}
if (!(0, _isString.default)(alignment)) {
throw new TypeError('Alignment parameter value must be a string.');
}
if (!alignments.includes(alignment)) {
throw new Error('Alignment parameter value must be a known alignment parameter value (left, right, center).');
}
if (subjectWidth === 0) {
return ' '.repeat(containerWidth);
}
const availableWidth = containerWidth - subjectWidth;
if (alignment === 'left') {
return alignLeft(subject, availableWidth);
}
if (alignment === 'right') {
return alignRight(subject, availableWidth);
}
return alignCenter(subject, availableWidth);
exports.default = (subject, containerWidth, alignment) => {
if (typeof subject !== 'string') {
throw new TypeError('Subject parameter value must be a string.');
}
const subjectWidth = string_width_1.default(subject);
if (subjectWidth > containerWidth) {
throw new Error('Subject parameter value width cannot be greater than the container width.');
}
if (subjectWidth === 0) {
return ' '.repeat(containerWidth);
}
const availableWidth = containerWidth - subjectWidth;
if (alignment === 'left') {
return alignLeft(subject, availableWidth);
}
if (alignment === 'right') {
return alignRight(subject, availableWidth);
}
return alignCenter(subject, availableWidth);
};
var _default = alignString;
exports.default = _default;
-97
View File
@@ -1,97 +0,0 @@
import isNumber from 'is-number-object';
import isString from 'is-string';
import stringWidth from 'string-width';
const alignments = [
'left',
'right',
'center',
];
/**
* @param {string} subject
* @param {number} width
* @returns {string}
*/
const alignLeft = (subject, width) => {
return subject + ' '.repeat(width);
};
/**
* @param {string} subject
* @param {number} width
* @returns {string}
*/
const alignRight = (subject, width) => {
return ' '.repeat(width) + subject;
};
/**
* @param {string} subject
* @param {number} width
* @returns {string}
*/
const alignCenter = (subject, width) => {
let halfWidth;
halfWidth = width / 2;
if (width % 2 === 0) {
return ' '.repeat(halfWidth) + subject + ' '.repeat(halfWidth);
} else {
halfWidth = Math.floor(halfWidth);
return ' '.repeat(halfWidth) + subject + ' '.repeat(halfWidth + 1);
}
};
/**
* Pads a string to the left and/or right to position the subject
* text in a desired alignment within a container.
*
* @param {string} subject
* @param {number} containerWidth
* @param {string} alignment One of the valid options (left, right, center).
* @returns {string}
*/
export default (subject, containerWidth, alignment) => {
if (!isString(subject)) {
throw new TypeError('Subject parameter value must be a string.');
}
if (!isNumber(containerWidth)) {
throw new TypeError('Container width parameter value must be a number.');
}
const subjectWidth = stringWidth(subject);
if (subjectWidth > containerWidth) {
// console.log('subjectWidth', subjectWidth, 'containerWidth', containerWidth, 'subject', subject);
throw new Error('Subject parameter value width cannot be greater than the container width.');
}
if (!isString(alignment)) {
throw new TypeError('Alignment parameter value must be a string.');
}
if (!alignments.includes(alignment)) {
throw new Error('Alignment parameter value must be a known alignment parameter value (left, right, center).');
}
if (subjectWidth === 0) {
return ' '.repeat(containerWidth);
}
const availableWidth = containerWidth - subjectWidth;
if (alignment === 'left') {
return alignLeft(subject, availableWidth);
}
if (alignment === 'right') {
return alignRight(subject, availableWidth);
}
return alignCenter(subject, availableWidth);
};
+17 -31
View File
@@ -1,34 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _stringWidth = _interopRequireDefault(require("string-width"));
var _alignString = _interopRequireDefault(require("./alignString"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @param {table~row[]} rows
* @param {object} config
* @returns {table~row[]}
*/
const alignTableData = (rows, config) => {
return rows.map(cells => {
return cells.map((value, index1) => {
const column = config.columns[index1];
if ((0, _stringWidth.default)(value) === column.width) {
return value;
} else {
return (0, _alignString.default)(value, column.width, column.alignment);
}
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const string_width_1 = __importDefault(require("string-width"));
const alignString_1 = __importDefault(require("./alignString"));
exports.default = (rows, config) => {
return rows.map((row) => {
return row.map((cell, index) => {
const column = config.columns[index];
if (string_width_1.default(cell) === column.width) {
return cell;
}
else {
return alignString_1.default(cell, column.width, column.alignment);
}
});
});
});
};
var _default = alignTableData;
exports.default = _default;
@@ -1,21 +0,0 @@
import stringWidth from 'string-width';
import alignString from './alignString';
/**
* @param {table~row[]} rows
* @param {object} config
* @returns {table~row[]}
*/
export default (rows, config) => {
return rows.map((cells) => {
return cells.map((value, index1) => {
const column = config.columns[index1];
if (stringWidth(value) === column.width) {
return value;
} else {
return alignString(value, column.width, column.alignment);
}
});
});
};
+10 -35
View File
@@ -1,37 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _isString = _interopRequireDefault(require("is-string"));
var _wrapCell = _interopRequireDefault(require("./wrapCell"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @param {string} value
* @param {number} columnWidth
* @param {boolean} useWrapWord
* @returns {number}
*/
const calculateCellHeight = (value, columnWidth, useWrapWord = false) => {
if (!(0, _isString.default)(value)) {
throw new TypeError('Value must be a string.');
}
if (!Number.isInteger(columnWidth)) {
throw new TypeError('Column width must be an integer.');
}
if (columnWidth < 1) {
throw new Error('Column width must be greater than 0.');
}
return (0, _wrapCell.default)(value, columnWidth, useWrapWord).length;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const wrapCell_1 = __importDefault(require("./wrapCell"));
exports.default = (value, columnWidth, useWrapWord = false) => {
if (typeof value !== 'string') {
throw new TypeError('Value must be a string.');
}
return wrapCell_1.default(value, columnWidth, useWrapWord).length;
};
var _default = calculateCellHeight;
exports.default = _default;
@@ -1,24 +0,0 @@
import isString from 'is-string';
import wrapCell from './wrapCell';
/**
* @param {string} value
* @param {number} columnWidth
* @param {boolean} useWrapWord
* @returns {number}
*/
export default (value, columnWidth, useWrapWord = false) => {
if (!isString(value)) {
throw new TypeError('Value must be a string.');
}
if (!Number.isInteger(columnWidth)) {
throw new TypeError('Column width must be an integer.');
}
if (columnWidth < 1) {
throw new Error('Column width must be greater than 0.');
}
return wrapCell(value, columnWidth, useWrapWord).length;
};
+11 -22
View File
@@ -1,27 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _stringWidth = _interopRequireDefault(require("string-width"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const string_width_1 = __importDefault(require("string-width"));
/**
* Calculates width of each cell contents.
*
* @param {string[]} cells
* @returns {number[]}
*/
const calculateCellWidthIndex = cells => {
return cells.map(value => {
return Math.max(...value.split('\n').map(line => {
return (0, _stringWidth.default)(line);
}));
});
exports.default = (cells) => {
return cells.map((value) => {
return Math.max(...value.split('\n').map((line) => {
return string_width_1.default(line);
}));
});
};
var _default = calculateCellWidthIndex;
exports.default = _default;
@@ -1,17 +0,0 @@
import stringWidth from 'string-width';
/**
* Calculates width of each cell contents.
*
* @param {string[]} cells
* @returns {number[]}
*/
export default (cells) => {
return cells.map((value) => {
return Math.max(
...value.split('\n').map((line) => {
return stringWidth(line);
}),
);
});
};
@@ -1,36 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _calculateCellWidthIndex = _interopRequireDefault(require("./calculateCellWidthIndex"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const calculateCellWidthIndex_1 = __importDefault(require("./calculateCellWidthIndex"));
/**
* Produces an array of values that describe the largest value length (width) in every column.
*
* @param {Array[]} rows
* @returns {number[]}
*/
const calculateMaximumColumnWidthIndex = rows => {
if (!rows[0]) {
throw new Error('Dataset must have at least one row.');
}
const columns = new Array(rows[0].length).fill(0);
rows.forEach(row => {
const columnWidthIndex = (0, _calculateCellWidthIndex.default)(row);
columnWidthIndex.forEach((valueWidth, index0) => {
if (columns[index0] < valueWidth) {
columns[index0] = valueWidth;
}
exports.default = (rows) => {
if (!rows[0]) {
throw new Error('Dataset must have at least one row.');
}
const columns = new Array(rows[0].length).fill(0);
rows.forEach((row) => {
const columnWidthIndex = calculateCellWidthIndex_1.default(row);
columnWidthIndex.forEach((valueWidth, index0) => {
if (columns[index0] < valueWidth) {
columns[index0] = valueWidth;
}
});
});
});
return columns;
return columns;
};
var _default = calculateMaximumColumnWidthIndex;
exports.default = _default;
@@ -1,27 +0,0 @@
import calculateCellWidthIndex from './calculateCellWidthIndex';
/**
* Produces an array of values that describe the largest value length (width) in every column.
*
* @param {Array[]} rows
* @returns {number[]}
*/
export default (rows) => {
if (!rows[0]) {
throw new Error('Dataset must have at least one row.');
}
const columns = new Array(rows[0].length).fill(0);
rows.forEach((row) => {
const columnWidthIndex = calculateCellWidthIndex(row);
columnWidthIndex.forEach((valueWidth, index0) => {
if (columns[index0] < valueWidth) {
columns[index0] = valueWidth;
}
});
});
return columns;
};
+15 -39
View File
@@ -1,45 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _isBooleanObject = _interopRequireDefault(require("is-boolean-object"));
var _isNumberObject = _interopRequireDefault(require("is-number-object"));
var _calculateCellHeight = _interopRequireDefault(require("./calculateCellHeight"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const calculateCellHeight_1 = __importDefault(require("./calculateCellHeight"));
/**
* Calculates the vertical row span index.
*
* @param {Array[]} rows
* @param {object} config
* @returns {number[]}
*/
const calculateRowHeightIndex = (rows, config) => {
const tableWidth = rows[0].length;
const rowSpanIndex = [];
rows.forEach(cells => {
const cellHeightIndex = new Array(tableWidth).fill(1);
cells.forEach((value, index1) => {
if (!(0, _isNumberObject.default)(config.columns[index1].width)) {
throw new TypeError('column[index].width must be a number.');
}
if (!(0, _isBooleanObject.default)(config.columns[index1].wrapWord)) {
throw new TypeError('column[index].wrapWord must be a boolean.');
}
cellHeightIndex[index1] = (0, _calculateCellHeight.default)(value, config.columns[index1].width, config.columns[index1].wrapWord);
exports.default = (rows, config) => {
const tableWidth = rows[0].length;
const rowSpanIndex = [];
rows.forEach((cells) => {
const cellHeightIndex = new Array(tableWidth).fill(1);
cells.forEach((value, index1) => {
cellHeightIndex[index1] = calculateCellHeight_1.default(value, config.columns[index1].width, config.columns[index1].wrapWord);
});
rowSpanIndex.push(Math.max(...cellHeightIndex));
});
rowSpanIndex.push(Math.max(...cellHeightIndex));
});
return rowSpanIndex;
return rowSpanIndex;
};
var _default = calculateRowHeightIndex;
exports.default = _default;
@@ -1,36 +0,0 @@
import isBoolean from 'is-boolean-object';
import isNumber from 'is-number-object';
import calculateCellHeight from './calculateCellHeight';
/**
* Calculates the vertical row span index.
*
* @param {Array[]} rows
* @param {object} config
* @returns {number[]}
*/
export default (rows, config) => {
const tableWidth = rows[0].length;
const rowSpanIndex = [];
rows.forEach((cells) => {
const cellHeightIndex = new Array(tableWidth).fill(1);
cells.forEach((value, index1) => {
if (!isNumber(config.columns[index1].width)) {
throw new TypeError('column[index].width must be a number.');
}
if (!isBoolean(config.columns[index1].wrapWord)) {
throw new TypeError('column[index].wrapWord must be a boolean.');
}
cellHeightIndex[index1] = calculateCellHeight(value, config.columns[index1].width, config.columns[index1].wrapWord);
});
rowSpanIndex.push(Math.max(...cellHeightIndex));
});
return rowSpanIndex;
};
+65 -116
View File
@@ -1,124 +1,73 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _alignTableData = _interopRequireDefault(require("./alignTableData"));
var _calculateRowHeightIndex = _interopRequireDefault(require("./calculateRowHeightIndex"));
var _drawBorder = require("./drawBorder");
var _drawRow = _interopRequireDefault(require("./drawRow"));
var _makeStreamConfig = _interopRequireDefault(require("./makeStreamConfig"));
var _mapDataUsingRowHeightIndex = _interopRequireDefault(require("./mapDataUsingRowHeightIndex"));
var _padTableData = _interopRequireDefault(require("./padTableData"));
var _stringifyTableData = _interopRequireDefault(require("./stringifyTableData"));
var _truncateTableData = _interopRequireDefault(require("./truncateTableData"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @param {Array} data
* @param {object} config
* @returns {Array}
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const alignTableData_1 = __importDefault(require("./alignTableData"));
const calculateRowHeightIndex_1 = __importDefault(require("./calculateRowHeightIndex"));
const drawBorder_1 = require("./drawBorder");
const drawRow_1 = __importDefault(require("./drawRow"));
const makeStreamConfig_1 = __importDefault(require("./makeStreamConfig"));
const mapDataUsingRowHeightIndex_1 = __importDefault(require("./mapDataUsingRowHeightIndex"));
const padTableData_1 = __importDefault(require("./padTableData"));
const stringifyTableData_1 = __importDefault(require("./stringifyTableData"));
const truncateTableData_1 = __importDefault(require("./truncateTableData"));
const prepareData = (data, config) => {
let rows;
rows = (0, _stringifyTableData.default)(data);
rows = (0, _truncateTableData.default)(data, config);
const rowHeightIndex = (0, _calculateRowHeightIndex.default)(rows, config);
rows = (0, _mapDataUsingRowHeightIndex.default)(rows, rowHeightIndex, config);
rows = (0, _alignTableData.default)(rows, config);
rows = (0, _padTableData.default)(rows, config);
return rows;
let rows = stringifyTableData_1.default(data);
rows = truncateTableData_1.default(rows, config);
const rowHeightIndex = calculateRowHeightIndex_1.default(rows, config);
rows = mapDataUsingRowHeightIndex_1.default(rows, rowHeightIndex, config);
rows = alignTableData_1.default(rows, config);
rows = padTableData_1.default(rows, config);
return rows;
};
/**
* @param {string[]} row
* @param {number[]} columnWidthIndex
* @param {object} config
* @returns {undefined}
*/
const create = (row, columnWidthIndex, config) => {
const rows = prepareData([row], config);
const body = rows.map(literalRow => {
return (0, _drawRow.default)(literalRow, config.border);
}).join('');
let output;
output = '';
output += (0, _drawBorder.drawBorderTop)(columnWidthIndex, config.border);
output += body;
output += (0, _drawBorder.drawBorderBottom)(columnWidthIndex, config.border);
output = output.trimEnd();
process.stdout.write(output);
const rows = prepareData([row], config);
const body = rows.map((literalRow) => {
return drawRow_1.default(literalRow, config);
}).join('');
let output;
output = '';
output += drawBorder_1.drawBorderTop(columnWidthIndex, config);
output += body;
output += drawBorder_1.drawBorderBottom(columnWidthIndex, config);
output = output.trimEnd();
process.stdout.write(output);
};
/**
* @param {string[]} row
* @param {number[]} columnWidthIndex
* @param {object} config
* @returns {undefined}
*/
const append = (row, columnWidthIndex, config) => {
const rows = prepareData([row], config);
const body = rows.map(literalRow => {
return (0, _drawRow.default)(literalRow, config.border);
}).join('');
let output = '';
const bottom = (0, _drawBorder.drawBorderBottom)(columnWidthIndex, config.border);
if (bottom !== '\n') {
output = '\r\u001B[K';
}
output += (0, _drawBorder.drawBorderJoin)(columnWidthIndex, config.border);
output += body;
output += bottom;
output = output.trimEnd();
process.stdout.write(output);
};
/**
* @param {object} userConfig
* @returns {object}
*/
const createStream = (userConfig = {}) => {
const config = (0, _makeStreamConfig.default)(userConfig);
const columnWidthIndex = Object.values(config.columns).map(column => {
return column.width + column.paddingLeft + column.paddingRight;
});
let empty;
empty = true;
return {
/**
* @param {string[]} row
* @returns {undefined}
*/
write: row => {
if (row.length !== config.columnCount) {
throw new Error('Row cell count does not match the config.columnCount.');
}
if (empty) {
empty = false;
return create(row, columnWidthIndex, config);
} else {
return append(row, columnWidthIndex, config);
}
const rows = prepareData([row], config);
const body = rows.map((literalRow) => {
return drawRow_1.default(literalRow, config);
}).join('');
let output = '';
const bottom = drawBorder_1.drawBorderBottom(columnWidthIndex, config);
if (bottom !== '\n') {
output = '\r\u001B[K';
}
};
output += drawBorder_1.drawBorderJoin(columnWidthIndex, config);
output += body;
output += bottom;
output = output.trimEnd();
process.stdout.write(output);
};
exports.default = (userConfig) => {
const config = makeStreamConfig_1.default(userConfig);
const columnWidthIndex = Object.values(config.columns).map((column) => {
return column.width + column.paddingLeft + column.paddingRight;
});
let empty = true;
return {
write: (row) => {
if (row.length !== config.columnCount) {
throw new Error('Row cell count does not match the config.columnCount.');
}
if (empty) {
empty = false;
create(row, columnWidthIndex, config);
}
else {
append(row, columnWidthIndex, config);
}
},
};
};
var _default = createStream;
exports.default = _default;
-125
View File
@@ -1,125 +0,0 @@
import alignTableData from './alignTableData';
import calculateRowHeightIndex from './calculateRowHeightIndex';
import {
drawBorderBottom,
drawBorderJoin,
drawBorderTop,
} from './drawBorder';
import drawRow from './drawRow';
import makeStreamConfig from './makeStreamConfig';
import mapDataUsingRowHeightIndex from './mapDataUsingRowHeightIndex';
import padTableData from './padTableData';
import stringifyTableData from './stringifyTableData';
import truncateTableData from './truncateTableData';
/**
* @param {Array} data
* @param {object} config
* @returns {Array}
*/
const prepareData = (data, config) => {
let rows;
rows = stringifyTableData(data);
rows = truncateTableData(data, config);
const rowHeightIndex = calculateRowHeightIndex(rows, config);
rows = mapDataUsingRowHeightIndex(rows, rowHeightIndex, config);
rows = alignTableData(rows, config);
rows = padTableData(rows, config);
return rows;
};
/**
* @param {string[]} row
* @param {number[]} columnWidthIndex
* @param {object} config
* @returns {undefined}
*/
const create = (row, columnWidthIndex, config) => {
const rows = prepareData([row], config);
const body = rows.map((literalRow) => {
return drawRow(literalRow, config.border);
}).join('');
let output;
output = '';
output += drawBorderTop(columnWidthIndex, config.border);
output += body;
output += drawBorderBottom(columnWidthIndex, config.border);
output = output.trimEnd();
process.stdout.write(output);
};
/**
* @param {string[]} row
* @param {number[]} columnWidthIndex
* @param {object} config
* @returns {undefined}
*/
const append = (row, columnWidthIndex, config) => {
const rows = prepareData([row], config);
const body = rows.map((literalRow) => {
return drawRow(literalRow, config.border);
}).join('');
let output = '';
const bottom = drawBorderBottom(columnWidthIndex, config.border);
if (bottom !== '\n') {
output = '\r\u001B[K';
}
output += drawBorderJoin(columnWidthIndex, config.border);
output += body;
output += bottom;
output = output.trimEnd();
process.stdout.write(output);
};
/**
* @param {object} userConfig
* @returns {object}
*/
export default (userConfig = {}) => {
const config = makeStreamConfig(userConfig);
const columnWidthIndex = Object.values(config.columns).map((column) => {
return column.width + column.paddingLeft + column.paddingRight;
});
let empty;
empty = true;
return {
/**
* @param {string[]} row
* @returns {undefined}
*/
write: (row) => {
if (row.length !== config.columnCount) {
throw new Error('Row cell count does not match the config.columnCount.');
}
if (empty) {
empty = false;
return create(row, columnWidthIndex, config);
} else {
return append(row, columnWidthIndex, config);
}
},
};
};
+45 -100
View File
@@ -1,109 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.drawBorderTop = exports.drawBorderJoin = exports.drawBorderBottom = exports.drawBorder = void 0;
/**
* @typedef drawBorder~parts
* @property {string} left
* @property {string} right
* @property {string} body
* @property {string} join
*/
/**
* @param {number[]} columnSizeIndex
* @param {drawBorder~parts} parts
* @returns {string}
*/
const drawBorder = (columnSizeIndex, parts) => {
const columns = columnSizeIndex.map(size => {
return parts.body.repeat(size);
}).join(parts.join);
return parts.left + columns + parts.right + '\n';
const drawHorizontalContent_1 = __importDefault(require("./drawHorizontalContent"));
const drawBorder = (columnSizeIndex, config) => {
const columns = columnSizeIndex.map((size) => {
return config.separator.body.repeat(size);
});
return drawHorizontalContent_1.default(columns, config);
};
/**
* @typedef drawBorderTop~parts
* @property {string} topLeft
* @property {string} topRight
* @property {string} topBody
* @property {string} topJoin
*/
/**
* @param {number[]} columnSizeIndex
* @param {drawBorderTop~parts} parts
* @returns {string}
*/
exports.drawBorder = drawBorder;
const drawBorderTop = (columnSizeIndex, parts) => {
const border = drawBorder(columnSizeIndex, {
body: parts.topBody,
join: parts.topJoin,
left: parts.topLeft,
right: parts.topRight
});
if (border === '\n') {
return '';
}
return border;
const drawBorderTop = (columnSizeIndex, config) => {
const result = drawBorder(columnSizeIndex, {
...config,
separator: {
body: config.border.topBody,
join: config.border.topJoin,
left: config.border.topLeft,
right: config.border.topRight,
},
});
if (result === '\n') {
return '';
}
return result;
};
/**
* @typedef drawBorderJoin~parts
* @property {string} joinLeft
* @property {string} joinRight
* @property {string} joinBody
* @property {string} joinJoin
*/
/**
* @param {number[]} columnSizeIndex
* @param {drawBorderJoin~parts} parts
* @returns {string}
*/
exports.drawBorderTop = drawBorderTop;
const drawBorderJoin = (columnSizeIndex, parts) => {
return drawBorder(columnSizeIndex, {
body: parts.joinBody,
join: parts.joinJoin,
left: parts.joinLeft,
right: parts.joinRight
});
const drawBorderJoin = (columnSizeIndex, config) => {
return drawBorder(columnSizeIndex, {
...config,
separator: {
body: config.border.joinBody,
join: config.border.joinJoin,
left: config.border.joinLeft,
right: config.border.joinRight,
},
});
};
/**
* @typedef drawBorderBottom~parts
* @property {string} topLeft
* @property {string} topRight
* @property {string} topBody
* @property {string} topJoin
*/
/**
* @param {number[]} columnSizeIndex
* @param {drawBorderBottom~parts} parts
* @returns {string}
*/
exports.drawBorderJoin = drawBorderJoin;
const drawBorderBottom = (columnSizeIndex, parts) => {
return drawBorder(columnSizeIndex, {
body: parts.bottomBody,
join: parts.bottomJoin,
left: parts.bottomLeft,
right: parts.bottomRight
});
const drawBorderBottom = (columnSizeIndex, config) => {
return drawBorder(columnSizeIndex, {
...config,
separator: {
body: config.border.bottomBody,
join: config.border.bottomJoin,
left: config.border.bottomLeft,
right: config.border.bottomRight,
},
});
};
exports.drawBorderBottom = drawBorderBottom;
exports.drawBorderBottom = drawBorderBottom;
-101
View File
@@ -1,101 +0,0 @@
/**
* @typedef drawBorder~parts
* @property {string} left
* @property {string} right
* @property {string} body
* @property {string} join
*/
/**
* @param {number[]} columnSizeIndex
* @param {drawBorder~parts} parts
* @returns {string}
*/
const drawBorder = (columnSizeIndex, parts) => {
const columns = columnSizeIndex
.map((size) => {
return parts.body.repeat(size);
})
.join(parts.join);
return parts.left + columns + parts.right + '\n';
};
/**
* @typedef drawBorderTop~parts
* @property {string} topLeft
* @property {string} topRight
* @property {string} topBody
* @property {string} topJoin
*/
/**
* @param {number[]} columnSizeIndex
* @param {drawBorderTop~parts} parts
* @returns {string}
*/
const drawBorderTop = (columnSizeIndex, parts) => {
const border = drawBorder(columnSizeIndex, {
body: parts.topBody,
join: parts.topJoin,
left: parts.topLeft,
right: parts.topRight,
});
if (border === '\n') {
return '';
}
return border;
};
/**
* @typedef drawBorderJoin~parts
* @property {string} joinLeft
* @property {string} joinRight
* @property {string} joinBody
* @property {string} joinJoin
*/
/**
* @param {number[]} columnSizeIndex
* @param {drawBorderJoin~parts} parts
* @returns {string}
*/
const drawBorderJoin = (columnSizeIndex, parts) => {
return drawBorder(columnSizeIndex, {
body: parts.joinBody,
join: parts.joinJoin,
left: parts.joinLeft,
right: parts.joinRight,
});
};
/**
* @typedef drawBorderBottom~parts
* @property {string} topLeft
* @property {string} topRight
* @property {string} topBody
* @property {string} topJoin
*/
/**
* @param {number[]} columnSizeIndex
* @param {drawBorderBottom~parts} parts
* @returns {string}
*/
const drawBorderBottom = (columnSizeIndex, parts) => {
return drawBorder(columnSizeIndex, {
body: parts.bottomBody,
join: parts.bottomJoin,
left: parts.bottomLeft,
right: parts.bottomRight,
});
};
export {
drawBorder,
drawBorderBottom,
drawBorderJoin,
drawBorderTop,
};
@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function drawHorizontalContent(contents, config) {
const { separator, drawVerticalLine } = config;
const contentSize = contents.length;
const result = [];
result.push(drawVerticalLine(0, contentSize) ? separator.left : '');
contents.forEach((content, index) => {
result.push(content);
// Only append the join separator if it is not the last content
if (index + 1 < contentSize) {
result.push(drawVerticalLine(index + 1, contentSize) ? separator.join : '');
}
});
result.push(drawVerticalLine(contentSize, contentSize) ? separator.right : '');
return result.join('') + '\n';
}
exports.default = drawHorizontalContent;
+14 -23
View File
@@ -1,25 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @typedef {object} drawRow~border
* @property {string} bodyLeft
* @property {string} bodyRight
* @property {string} bodyJoin
*/
/**
* @param {number[]} columns
* @param {drawRow~border} border
* @returns {string}
*/
const drawRow = (columns, border) => {
return border.bodyLeft + columns.join(border.bodyJoin) + border.bodyRight + '\n';
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const drawHorizontalContent_1 = __importDefault(require("./drawHorizontalContent"));
exports.default = (row, config) => {
return drawHorizontalContent_1.default(row, {
...config,
separator: {
join: config.border.bodyJoin,
left: config.border.bodyLeft,
right: config.border.bodyRight,
},
});
};
var _default = drawRow;
exports.default = _default;
-15
View File
@@ -1,15 +0,0 @@
/**
* @typedef {object} drawRow~border
* @property {string} bodyLeft
* @property {string} bodyRight
* @property {string} bodyJoin
*/
/**
* @param {number[]} columns
* @param {drawRow~border} border
* @returns {string}
*/
export default (columns, border) => {
return border.bodyLeft + columns.join(border.bodyJoin) + border.bodyRight + '\n';
};
+42 -52
View File
@@ -1,58 +1,48 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _drawBorder = require("./drawBorder");
var _drawRow = _interopRequireDefault(require("./drawRow"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const drawBorder_1 = require("./drawBorder");
const drawRow_1 = __importDefault(require("./drawRow"));
/**
* @param {Array} rows
* @param {object} border
* @param {Array} columnSizeIndex
* @param {Array} rowSpanIndex
* @param {Function} drawHorizontalLine
* @param {boolean} singleLine
* @returns {string}
* Group the array into sub-arrays by sizes.
*
* @example
* chunkBySizes(['a', 'b', 'c', 'd', 'e'], [2, 1, 2]) = [ ['a', 'b'], ['c'], ['d', 'e'] ]
*/
const drawTable = (rows, border, columnSizeIndex, rowSpanIndex, drawHorizontalLine, singleLine) => {
let output;
let realRowIndex;
let rowHeight;
const rowCount = rows.length;
realRowIndex = 0;
output = '';
if (drawHorizontalLine(realRowIndex, rowCount)) {
output += (0, _drawBorder.drawBorderTop)(columnSizeIndex, border);
}
rows.forEach((row, index0) => {
output += (0, _drawRow.default)(row, border);
if (!rowHeight) {
rowHeight = rowSpanIndex[realRowIndex];
realRowIndex++;
const groupBySizes = (array, sizes) => {
let startIndex = 0;
return sizes.map((rowHeight) => {
const chunk = array.slice(startIndex, startIndex + rowHeight);
startIndex += rowHeight;
return chunk;
});
};
const shouldDrawBorderJoin = (rowIndex, rowCount, config) => {
const { singleLine, drawHorizontalLine } = config;
return !singleLine && rowIndex + 1 < rowCount && drawHorizontalLine(rowIndex + 1, rowCount);
};
exports.default = (rows, columnWidths, rowHeights, config) => {
const { drawHorizontalLine, } = config;
const groupedRows = groupBySizes(rows, rowHeights).map((group) => {
return group.map((row) => {
return drawRow_1.default(row, config);
}).join('');
});
const rowCount = groupedRows.length;
let output = '';
if (drawHorizontalLine(0, rowCount)) {
output += drawBorder_1.drawBorderTop(columnWidths, config);
}
rowHeight--;
if (!singleLine && rowHeight === 0 && index0 !== rowCount - 1 && drawHorizontalLine(realRowIndex, rowCount)) {
output += (0, _drawBorder.drawBorderJoin)(columnSizeIndex, border);
groupedRows.forEach((row, rowIndex) => {
output += row;
if (shouldDrawBorderJoin(rowIndex, rowCount, config)) {
output += drawBorder_1.drawBorderJoin(columnWidths, config);
}
});
if (drawHorizontalLine(rowCount, rowCount)) {
output += drawBorder_1.drawBorderBottom(columnWidths, config);
}
});
if (drawHorizontalLine(realRowIndex, rowCount)) {
output += (0, _drawBorder.drawBorderBottom)(columnSizeIndex, border);
}
return output;
return output;
};
var _default = drawTable;
exports.default = _default;
-53
View File
@@ -1,53 +0,0 @@
import {
drawBorderTop,
drawBorderJoin,
drawBorderBottom,
} from './drawBorder';
import drawRow from './drawRow';
/**
* @param {Array} rows
* @param {object} border
* @param {Array} columnSizeIndex
* @param {Array} rowSpanIndex
* @param {Function} drawHorizontalLine
* @param {boolean} singleLine
* @returns {string}
*/
export default (rows, border, columnSizeIndex, rowSpanIndex, drawHorizontalLine, singleLine) => {
let output;
let realRowIndex;
let rowHeight;
const rowCount = rows.length;
realRowIndex = 0;
output = '';
if (drawHorizontalLine(realRowIndex, rowCount)) {
output += drawBorderTop(columnSizeIndex, border);
}
rows.forEach((row, index0) => {
output += drawRow(row, border);
if (!rowHeight) {
rowHeight = rowSpanIndex[realRowIndex];
realRowIndex++;
}
rowHeight--;
if (!singleLine && rowHeight === 0 && index0 !== rowCount - 1 && drawHorizontalLine(realRowIndex, rowCount)) {
output += drawBorderJoin(columnSizeIndex, border);
}
});
if (drawHorizontalLine(realRowIndex, rowCount)) {
output += drawBorderBottom(columnSizeIndex, border);
}
return output;
};
+79 -115
View File
@@ -1,118 +1,82 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/* eslint-disable sort-keys-fix/sort-keys-fix */
/**
* @typedef border
* @property {string} topBody
* @property {string} topJoin
* @property {string} topLeft
* @property {string} topRight
* @property {string} bottomBody
* @property {string} bottomJoin
* @property {string} bottomLeft
* @property {string} bottomRight
* @property {string} bodyLeft
* @property {string} bodyRight
* @property {string} bodyJoin
* @property {string} joinBody
* @property {string} joinLeft
* @property {string} joinRight
* @property {string} joinJoin
*/
/**
* @param {string} name
* @returns {border}
*/
const getBorderCharacters = name => {
if (name === 'honeywell') {
return {
topBody: '═',
topJoin: '╤',
topLeft: '╔',
topRight: '╗',
bottomBody: '═',
bottomJoin: '╧',
bottomLeft: '╚',
bottomRight: '╝',
bodyLeft: '║',
bodyRight: '║',
bodyJoin: '│',
joinBody: '─',
joinLeft: '╟',
joinRight: '╢',
joinJoin: '┼'
};
}
if (name === 'norc') {
return {
topBody: '─',
topJoin: '┬',
topLeft: '┌',
topRight: '┐',
bottomBody: '─',
bottomJoin: '┴',
bottomLeft: '└',
bottomRight: '┘',
bodyLeft: '│',
bodyRight: '│',
bodyJoin: '│',
joinBody: '─',
joinLeft: '├',
joinRight: '┤',
joinJoin: '┼'
};
}
if (name === 'ramac') {
return {
topBody: '-',
topJoin: '+',
topLeft: '+',
topRight: '+',
bottomBody: '-',
bottomJoin: '+',
bottomLeft: '+',
bottomRight: '+',
bodyLeft: '|',
bodyRight: '|',
bodyJoin: '|',
joinBody: '-',
joinLeft: '|',
joinRight: '|',
joinJoin: '|'
};
}
if (name === 'void') {
return {
topBody: '',
topJoin: '',
topLeft: '',
topRight: '',
bottomBody: '',
bottomJoin: '',
bottomLeft: '',
bottomRight: '',
bodyLeft: '',
bodyRight: '',
bodyJoin: '',
joinBody: '',
joinLeft: '',
joinRight: '',
joinJoin: ''
};
}
throw new Error('Unknown border template "' + name + '".');
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = (name) => {
if (name === 'honeywell') {
return {
topBody: '═',
topJoin: '╤',
topLeft: '╔',
topRight: '╗',
bottomBody: '═',
bottomJoin: '╧',
bottomLeft: '╚',
bottomRight: '╝',
bodyLeft: '║',
bodyRight: '║',
bodyJoin: '│',
joinBody: '─',
joinLeft: '╟',
joinRight: '╢',
joinJoin: '┼',
};
}
if (name === 'norc') {
return {
topBody: '─',
topJoin: '┬',
topLeft: '┌',
topRight: '┐',
bottomBody: '─',
bottomJoin: '┴',
bottomLeft: '└',
bottomRight: '┘',
bodyLeft: '│',
bodyRight: '│',
bodyJoin: '│',
joinBody: '─',
joinLeft: '├',
joinRight: '┤',
joinJoin: '┼',
};
}
if (name === 'ramac') {
return {
topBody: '-',
topJoin: '+',
topLeft: '+',
topRight: '+',
bottomBody: '-',
bottomJoin: '+',
bottomLeft: '+',
bottomRight: '+',
bodyLeft: '|',
bodyRight: '|',
bodyJoin: '|',
joinBody: '-',
joinLeft: '|',
joinRight: '|',
joinJoin: '|',
};
}
if (name === 'void') {
return {
topBody: '',
topJoin: '',
topLeft: '',
topRight: '',
bottomBody: '',
bottomJoin: '',
bottomLeft: '',
bottomRight: '',
bodyLeft: '',
bodyRight: '',
bodyJoin: '',
joinBody: '',
joinLeft: '',
joinRight: '',
joinJoin: '',
};
}
throw new Error('Unknown border template "' + name + '".');
};
var _default = getBorderCharacters;
exports.default = _default;
@@ -1,120 +0,0 @@
/* eslint-disable sort-keys-fix/sort-keys-fix */
/**
* @typedef border
* @property {string} topBody
* @property {string} topJoin
* @property {string} topLeft
* @property {string} topRight
* @property {string} bottomBody
* @property {string} bottomJoin
* @property {string} bottomLeft
* @property {string} bottomRight
* @property {string} bodyLeft
* @property {string} bodyRight
* @property {string} bodyJoin
* @property {string} joinBody
* @property {string} joinLeft
* @property {string} joinRight
* @property {string} joinJoin
*/
/**
* @param {string} name
* @returns {border}
*/
export default (name) => {
if (name === 'honeywell') {
return {
topBody: '═',
topJoin: '╤',
topLeft: '╔',
topRight: '╗',
bottomBody: '═',
bottomJoin: '╧',
bottomLeft: '╚',
bottomRight: '╝',
bodyLeft: '║',
bodyRight: '║',
bodyJoin: '│',
joinBody: '─',
joinLeft: '╟',
joinRight: '╢',
joinJoin: '┼',
};
}
if (name === 'norc') {
return {
topBody: '─',
topJoin: '┬',
topLeft: '┌',
topRight: '┐',
bottomBody: '─',
bottomJoin: '┴',
bottomLeft: '└',
bottomRight: '┘',
bodyLeft: '│',
bodyRight: '│',
bodyJoin: '│',
joinBody: '─',
joinLeft: '├',
joinRight: '┤',
joinJoin: '┼',
};
}
if (name === 'ramac') {
return {
topBody: '-',
topJoin: '+',
topLeft: '+',
topRight: '+',
bottomBody: '-',
bottomJoin: '+',
bottomLeft: '+',
bottomRight: '+',
bodyLeft: '|',
bodyRight: '|',
bodyJoin: '|',
joinBody: '-',
joinLeft: '|',
joinRight: '|',
joinJoin: '|',
};
}
if (name === 'void') {
return {
topBody: '',
topJoin: '',
topLeft: '',
topRight: '',
bottomBody: '',
bottomJoin: '',
bottomLeft: '',
bottomRight: '',
bodyLeft: '',
bodyRight: '',
bodyJoin: '',
joinBody: '',
joinLeft: '',
joinRight: '',
joinJoin: '',
};
}
throw new Error('Unknown border template "' + name + '".');
};
+22 -30
View File
@@ -1,31 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "createStream", {
enumerable: true,
get: function () {
return _createStream.default;
}
});
Object.defineProperty(exports, "getBorderCharacters", {
enumerable: true,
get: function () {
return _getBorderCharacters.default;
}
});
Object.defineProperty(exports, "table", {
enumerable: true,
get: function () {
return _table.default;
}
});
var _createStream = _interopRequireDefault(require("./createStream"));
var _getBorderCharacters = _interopRequireDefault(require("./getBorderCharacters"));
var _table = _interopRequireDefault(require("./table"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getBorderCharacters = exports.createStream = exports.table = void 0;
const createStream_1 = __importDefault(require("./createStream"));
exports.createStream = createStream_1.default;
const getBorderCharacters_1 = __importDefault(require("./getBorderCharacters"));
exports.getBorderCharacters = getBorderCharacters_1.default;
const table_1 = __importDefault(require("./table"));
exports.table = table_1.default;
__exportStar(require("./types/api"), exports);
-9
View File
@@ -1,9 +0,0 @@
import createStream from './createStream';
import getBorderCharacters from './getBorderCharacters';
import table from './table';
export {
table,
createStream,
getBorderCharacters,
};
+42 -75
View File
@@ -1,91 +1,58 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _lodash = _interopRequireDefault(require("lodash.clonedeep"));
var _calculateMaximumColumnWidthIndex = _interopRequireDefault(require("./calculateMaximumColumnWidthIndex"));
var _getBorderCharacters = _interopRequireDefault(require("./getBorderCharacters"));
var _validateConfig = _interopRequireDefault(require("./validateConfig"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const lodash_clonedeep_1 = __importDefault(require("lodash.clonedeep"));
const calculateMaximumColumnWidthIndex_1 = __importDefault(require("./calculateMaximumColumnWidthIndex"));
const getBorderCharacters_1 = __importDefault(require("./getBorderCharacters"));
const validateConfig_1 = __importDefault(require("./validateConfig"));
/**
* Merges user provided border characters with the default border ("honeywell") characters.
*
* @param {object} border
* @returns {object}
*/
const makeBorder = (border = {}) => {
return Object.assign({}, (0, _getBorderCharacters.default)('honeywell'), border);
const makeBorder = (border) => {
return {
...getBorderCharacters_1.default('honeywell'),
...border,
};
};
/**
* Creates a configuration for every column using default
* values for the missing configuration properties.
*
* @param {Array[]} rows
* @param {object} columns
* @param {object} columnDefault
* @returns {object}
*/
const makeColumns = (rows, columns = {}, columnDefault = {}) => {
const maximumColumnWidthIndex = (0, _calculateMaximumColumnWidthIndex.default)(rows);
for (let index = 0; index < rows[0].length; index++) {
if (typeof columns[index] === 'undefined') {
columns[index] = {};
}
columns[index] = Object.assign({
alignment: 'left',
paddingLeft: 1,
paddingRight: 1,
truncate: Number.POSITIVE_INFINITY,
width: maximumColumnWidthIndex[index],
wrapWord: false
}, columnDefault, columns[index]);
}
return columns;
const makeColumns = (rows, columns, columnDefault) => {
const maximumColumnWidthIndex = calculateMaximumColumnWidthIndex_1.default(rows);
return rows[0].map((_cell, index) => {
return {
alignment: 'left',
paddingLeft: 1,
paddingRight: 1,
truncate: Number.POSITIVE_INFINITY,
width: maximumColumnWidthIndex[index],
wrapWord: false,
...columnDefault,
...columns === null || columns === void 0 ? void 0 : columns[index],
};
});
};
/**
* Makes a new configuration object out of the userConfig object
* using default values for the missing configuration properties.
*
* @param {Array[]} rows
* @param {object} userConfig
* @returns {object}
*/
const makeConfig = (rows, userConfig = {}) => {
(0, _validateConfig.default)('config.json', userConfig);
const config = (0, _lodash.default)(userConfig);
config.border = makeBorder(config.border);
config.columns = makeColumns(rows, config.columns, config.columnDefault);
if (!config.drawHorizontalLine) {
/**
* @returns {boolean}
*/
config.drawHorizontalLine = () => {
return true;
exports.default = (rows, userConfig = {}) => {
var _a, _b, _c;
validateConfig_1.default('config.json', userConfig);
const config = lodash_clonedeep_1.default(userConfig);
return {
...config,
border: makeBorder(config.border),
columns: makeColumns(rows, config.columns, config.columnDefault),
drawHorizontalLine: (_a = config.drawHorizontalLine) !== null && _a !== void 0 ? _a : (() => {
return true;
}),
drawVerticalLine: (_b = config.drawVerticalLine) !== null && _b !== void 0 ? _b : (() => {
return true;
}),
singleLine: (_c = config.singleLine) !== null && _c !== void 0 ? _c : false,
};
}
if (config.singleLine === undefined) {
config.singleLine = false;
}
return config;
};
var _default = makeConfig;
exports.default = _default;
-76
View File
@@ -1,76 +0,0 @@
import cloneDeep from 'lodash.clonedeep';
import calculateMaximumColumnWidthIndex from './calculateMaximumColumnWidthIndex';
import getBorderCharacters from './getBorderCharacters';
import validateConfig from './validateConfig';
/**
* Merges user provided border characters with the default border ("honeywell") characters.
*
* @param {object} border
* @returns {object}
*/
const makeBorder = (border = {}) => {
return Object.assign({}, getBorderCharacters('honeywell'), border);
};
/**
* Creates a configuration for every column using default
* values for the missing configuration properties.
*
* @param {Array[]} rows
* @param {object} columns
* @param {object} columnDefault
* @returns {object}
*/
const makeColumns = (rows, columns = {}, columnDefault = {}) => {
const maximumColumnWidthIndex = calculateMaximumColumnWidthIndex(rows);
for (let index = 0; index < rows[0].length; index++) {
if (typeof columns[index] === 'undefined') {
columns[index] = {};
}
columns[index] = Object.assign({
alignment: 'left',
paddingLeft: 1,
paddingRight: 1,
truncate: Number.POSITIVE_INFINITY,
width: maximumColumnWidthIndex[index],
wrapWord: false,
}, columnDefault, columns[index]);
}
return columns;
};
/**
* Makes a new configuration object out of the userConfig object
* using default values for the missing configuration properties.
*
* @param {Array[]} rows
* @param {object} userConfig
* @returns {object}
*/
export default (rows, userConfig = {}) => {
validateConfig('config.json', userConfig);
const config = cloneDeep(userConfig);
config.border = makeBorder(config.border);
config.columns = makeColumns(rows, config.columns, config.columnDefault);
if (!config.drawHorizontalLine) {
/**
* @returns {boolean}
*/
config.drawHorizontalLine = () => {
return true;
};
}
if (config.singleLine === undefined) {
config.singleLine = false;
}
return config;
};
+43 -81
View File
@@ -1,97 +1,59 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _lodash = _interopRequireDefault(require("lodash.clonedeep"));
var _getBorderCharacters = _interopRequireDefault(require("./getBorderCharacters"));
var _validateConfig = _interopRequireDefault(require("./validateConfig"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const lodash_clonedeep_1 = __importDefault(require("lodash.clonedeep"));
const getBorderCharacters_1 = __importDefault(require("./getBorderCharacters"));
const validateConfig_1 = __importDefault(require("./validateConfig"));
/**
* Merges user provided border characters with the default border ("honeywell") characters.
*
* @param {object} border
* @returns {object}
*/
const makeBorder = (border = {}) => {
return Object.assign({}, (0, _getBorderCharacters.default)('honeywell'), border);
const makeBorder = (border) => {
return {
...getBorderCharacters_1.default('honeywell'),
...border,
};
};
/**
* Creates a configuration for every column using default
* values for the missing configuration properties.
*
* @param {number} columnCount
* @param {object} columns
* @param {object} columnDefault
* @returns {object}
*/
const makeColumns = (columnCount, columns = {}, columnDefault = {}) => {
for (let index = 0; index < columnCount; index++) {
if (typeof columns[index] === 'undefined') {
columns[index] = {};
}
columns[index] = Object.assign({
alignment: 'left',
paddingLeft: 1,
paddingRight: 1,
truncate: Number.POSITIVE_INFINITY,
wrapWord: false
}, columnDefault, columns[index]);
}
return columns;
const makeColumns = (columnCount, columns = {}, columnDefault) => {
return Array.from({ length: columnCount }).map((_, index) => {
return {
alignment: 'left',
paddingLeft: 1,
paddingRight: 1,
truncate: Number.POSITIVE_INFINITY,
wrapWord: false,
...columnDefault,
...columns[index],
};
});
};
/**
* @typedef {object} columnConfig
* @property {string} alignment
* @property {number} width
* @property {number} truncate
* @property {number} paddingLeft
* @property {number} paddingRight
*/
/**
* @typedef {object} streamConfig
* @property {columnConfig} columnDefault
* @property {object} border
* @property {columnConfig[]}
* @property {number} columnCount Number of columns in the table (required).
*/
/**
* Makes a new configuration object out of the userConfig object
* using default values for the missing configuration properties.
*
* @param {streamConfig} userConfig
* @returns {object}
*/
const makeStreamConfig = (userConfig = {}) => {
(0, _validateConfig.default)('streamConfig.json', userConfig);
const config = (0, _lodash.default)(userConfig);
if (!config.columnDefault || !config.columnDefault.width) {
throw new Error('Must provide config.columnDefault.width when creating a stream.');
}
if (!config.columnCount) {
throw new Error('Must provide config.columnCount.');
}
config.border = makeBorder(config.border);
config.columns = makeColumns(config.columnCount, config.columns, config.columnDefault);
return config;
exports.default = (userConfig) => {
var _a;
validateConfig_1.default('streamConfig.json', userConfig);
const config = lodash_clonedeep_1.default(userConfig);
if (!config.columnDefault || !config.columnDefault.width) {
throw new Error('Must provide config.columnDefault.width when creating a stream.');
}
if (!config.columnCount) {
throw new Error('Must provide config.columnCount.');
}
return {
...config,
border: makeBorder(config.border),
columnCount: config.columnCount,
columns: makeColumns(config.columnCount, config.columns, config.columnDefault),
drawVerticalLine: (_a = config.drawVerticalLine) !== null && _a !== void 0 ? _a : (() => {
return true;
}),
};
};
var _default = makeStreamConfig;
exports.default = _default;
@@ -1,83 +0,0 @@
import cloneDeep from 'lodash.clonedeep';
import getBorderCharacters from './getBorderCharacters';
import validateConfig from './validateConfig';
/**
* Merges user provided border characters with the default border ("honeywell") characters.
*
* @param {object} border
* @returns {object}
*/
const makeBorder = (border = {}) => {
return Object.assign({}, getBorderCharacters('honeywell'), border);
};
/**
* Creates a configuration for every column using default
* values for the missing configuration properties.
*
* @param {number} columnCount
* @param {object} columns
* @param {object} columnDefault
* @returns {object}
*/
const makeColumns = (columnCount, columns = {}, columnDefault = {}) => {
for (let index = 0; index < columnCount; index++) {
if (typeof columns[index] === 'undefined') {
columns[index] = {};
}
columns[index] = Object.assign({
alignment: 'left',
paddingLeft: 1,
paddingRight: 1,
truncate: Number.POSITIVE_INFINITY,
wrapWord: false,
}, columnDefault, columns[index]);
}
return columns;
};
/**
* @typedef {object} columnConfig
* @property {string} alignment
* @property {number} width
* @property {number} truncate
* @property {number} paddingLeft
* @property {number} paddingRight
*/
/**
* @typedef {object} streamConfig
* @property {columnConfig} columnDefault
* @property {object} border
* @property {columnConfig[]}
* @property {number} columnCount Number of columns in the table (required).
*/
/**
* Makes a new configuration object out of the userConfig object
* using default values for the missing configuration properties.
*
* @param {streamConfig} userConfig
* @returns {object}
*/
export default (userConfig = {}) => {
validateConfig('streamConfig.json', userConfig);
const config = cloneDeep(userConfig);
if (!config.columnDefault || !config.columnDefault.width) {
throw new Error('Must provide config.columnDefault.width when creating a stream.');
}
if (!config.columnCount) {
throw new Error('Must provide config.columnCount.');
}
config.border = makeBorder(config.border);
config.columns = makeColumns(config.columnCount, config.columns, config.columnDefault);
return config;
};
@@ -1,41 +1,26 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _lodash = _interopRequireDefault(require("lodash.flatten"));
var _wrapCell = _interopRequireDefault(require("./wrapCell"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @param {Array} unmappedRows
* @param {number[]} rowHeightIndex
* @param {object} config
* @returns {Array}
*/
const mapDataUsingRowHeightIndex = (unmappedRows, rowHeightIndex, config) => {
const tableWidth = unmappedRows[0].length;
const mappedRows = unmappedRows.map((cells, index0) => {
const rowHeight = Array.from(new Array(rowHeightIndex[index0]), () => {
return new Array(tableWidth).fill('');
}); // rowHeight
// [{row index within rowSaw; index2}]
// [{cell index within a virtual row; index1}]
cells.forEach((value, index1) => {
const cellLines = (0, _wrapCell.default)(value, config.columns[index1].width, config.columns[index1].wrapWord);
cellLines.forEach((cellLine, index2) => {
rowHeight[index2][index1] = cellLine;
});
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const lodash_flatten_1 = __importDefault(require("lodash.flatten"));
const wrapCell_1 = __importDefault(require("./wrapCell"));
exports.default = (unmappedRows, rowHeightIndex, config) => {
const tableWidth = unmappedRows[0].length;
const mappedRows = unmappedRows.map((row, index0) => {
const rowHeight = Array.from({ length: rowHeightIndex[index0] }, () => {
return new Array(tableWidth).fill('');
});
// rowHeight
// [{row index within rowSaw; index2}]
// [{cell index within a virtual row; index1}]
row.forEach((cell, index1) => {
const cellLines = wrapCell_1.default(cell, config.columns[index1].width, config.columns[index1].wrapWord);
cellLines.forEach((cellLine, index2) => {
rowHeight[index2][index1] = cellLine;
});
});
return rowHeight;
});
return rowHeight;
});
return (0, _lodash.default)(mappedRows);
return lodash_flatten_1.default(mappedRows);
};
var _default = mapDataUsingRowHeightIndex;
exports.default = _default;
@@ -1,34 +0,0 @@
import flatten from 'lodash.flatten';
import wrapCell from './wrapCell';
/**
* @param {Array} unmappedRows
* @param {number[]} rowHeightIndex
* @param {object} config
* @returns {Array}
*/
export default (unmappedRows, rowHeightIndex, config) => {
const tableWidth = unmappedRows[0].length;
const mappedRows = unmappedRows.map((cells, index0) => {
const rowHeight = Array.from(new Array(rowHeightIndex[index0]), () => {
return new Array(tableWidth).fill('');
});
// rowHeight
// [{row index within rowSaw; index2}]
// [{cell index within a virtual row; index1}]
cells.forEach((value, index1) => {
const cellLines = wrapCell(value, config.columns[index1].width, config.columns[index1].wrapWord);
cellLines.forEach((cellLine, index2) => {
rowHeight[index2][index1] = cellLine;
});
});
return rowHeight;
});
return flatten(mappedRows);
};
+7 -20
View File
@@ -1,23 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @param {table~row[]} rows
* @param {object} config
* @returns {table~row[]}
*/
const padTableData = (rows, config) => {
return rows.map(cells => {
return cells.map((value, index1) => {
const column = config.columns[index1];
return ' '.repeat(column.paddingLeft) + value + ' '.repeat(column.paddingRight);
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = (rows, config) => {
return rows.map((cells) => {
return cells.map((value, index1) => {
const column = config.columns[index1];
return ' '.repeat(column.paddingLeft) + value + ' '.repeat(column.paddingRight);
});
});
});
};
var _default = padTableData;
exports.default = _default;
-14
View File
@@ -1,14 +0,0 @@
/**
* @param {table~row[]} rows
* @param {object} config
* @returns {table~row[]}
*/
export default (rows, config) => {
return rows.map((cells) => {
return cells.map((value, index1) => {
const column = config.columns[index1];
return ' '.repeat(column.paddingLeft) + value + ' '.repeat(column.paddingRight);
});
});
};
-23
View File
@@ -1,23 +0,0 @@
{
"$id": "config.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"border": {
"$ref": "shared.json#/definitions/borders"
},
"columns": {
"$ref": "shared.json#/definitions/columns"
},
"columnDefault": {
"$ref": "shared.json#/definitions/column"
},
"drawHorizontalLine": {
"typeof": "function"
},
"singleLine": {
"typeof": "boolean"
}
},
"additionalProperties": false
}
-98
View File
@@ -1,98 +0,0 @@
{
"$id": "shared.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"columns": {
"type": "object",
"patternProperties": {
"^[0-9]+$": {
"$ref": "#/definitions/column"
}
},
"additionalProperties": false
},
"column": {
"type": "object",
"properties": {
"alignment": {
"type": "string",
"enum": [
"left",
"right",
"center"
]
},
"width": {
"type": "number"
},
"wrapWord": {
"type": "boolean"
},
"truncate": {
"type": "number"
},
"paddingLeft": {
"type": "number"
},
"paddingRight": {
"type": "number"
}
},
"additionalProperties": false
},
"borders": {
"type": "object",
"properties": {
"topBody": {
"$ref": "#/definitions/border"
},
"topJoin": {
"$ref": "#/definitions/border"
},
"topLeft": {
"$ref": "#/definitions/border"
},
"topRight": {
"$ref": "#/definitions/border"
},
"bottomBody": {
"$ref": "#/definitions/border"
},
"bottomJoin": {
"$ref": "#/definitions/border"
},
"bottomLeft": {
"$ref": "#/definitions/border"
},
"bottomRight": {
"$ref": "#/definitions/border"
},
"bodyLeft": {
"$ref": "#/definitions/border"
},
"bodyRight": {
"$ref": "#/definitions/border"
},
"bodyJoin": {
"$ref": "#/definitions/border"
},
"joinBody": {
"$ref": "#/definitions/border"
},
"joinLeft": {
"$ref": "#/definitions/border"
},
"joinRight": {
"$ref": "#/definitions/border"
},
"joinJoin": {
"$ref": "#/definitions/border"
}
},
"additionalProperties": false
},
"border": {
"type": "string"
}
}
}
@@ -1,20 +0,0 @@
{
"$id": "streamConfig.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"border": {
"$ref": "shared.json#/definitions/borders"
},
"columns": {
"$ref": "shared.json#/definitions/columns"
},
"columnDefault": {
"$ref": "shared.json#/definitions/column"
},
"columnCount": {
"type": "number"
}
},
"additionalProperties": false
}
+5 -19
View File
@@ -1,21 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* Casts all cell values to a string.
*
* @param {table~row[]} rows
* @returns {table~row[]}
*/
const stringifyTableData = rows => {
return rows.map(cells => {
return cells.map(String);
});
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = (rows) => {
return rows.map((cells) => {
return cells.map(String);
});
};
var _default = stringifyTableData;
exports.default = _default;
@@ -1,11 +0,0 @@
/**
* Casts all cell values to a string.
*
* @param {table~row[]} rows
* @returns {table~row[]}
*/
export default (rows) => {
return rows.map((cells) => {
return cells.map(String);
});
};
+25 -107
View File
@@ -1,109 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _alignTableData = _interopRequireDefault(require("./alignTableData"));
var _calculateCellWidthIndex = _interopRequireDefault(require("./calculateCellWidthIndex"));
var _calculateRowHeightIndex = _interopRequireDefault(require("./calculateRowHeightIndex"));
var _drawTable = _interopRequireDefault(require("./drawTable"));
var _makeConfig = _interopRequireDefault(require("./makeConfig"));
var _mapDataUsingRowHeightIndex = _interopRequireDefault(require("./mapDataUsingRowHeightIndex"));
var _padTableData = _interopRequireDefault(require("./padTableData"));
var _stringifyTableData = _interopRequireDefault(require("./stringifyTableData"));
var _truncateTableData = _interopRequireDefault(require("./truncateTableData"));
var _validateTableData = _interopRequireDefault(require("./validateTableData"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @typedef {string} table~cell
*/
/**
* @typedef {table~cell[]} table~row
*/
/**
* @typedef {object} table~columns
* @property {string} alignment Cell content alignment (enum: left, center, right) (default: left).
* @property {number} width Column width (default: auto).
* @property {number} truncate Number of characters are which the content will be truncated (default: Infinity).
* @property {boolean} wrapWord When true the text is broken at the nearest space or one of the special characters
* @property {number} paddingLeft Cell content padding width left (default: 1).
* @property {number} paddingRight Cell content padding width right (default: 1).
*/
/**
* @typedef {object} table~border
* @property {string} topBody
* @property {string} topJoin
* @property {string} topLeft
* @property {string} topRight
* @property {string} bottomBody
* @property {string} bottomJoin
* @property {string} bottomLeft
* @property {string} bottomRight
* @property {string} bodyLeft
* @property {string} bodyRight
* @property {string} bodyJoin
* @property {string} joinBody
* @property {string} joinLeft
* @property {string} joinRight
* @property {string} joinJoin
*/
/**
* Used to tell whether to draw a horizontal line.
* This callback is called for each non-content line of the table.
* The default behavior is to always return true.
*
* @typedef {Function} drawHorizontalLine
* @param {number} index
* @param {number} size
* @returns {boolean}
*/
/**
* @typedef {object} table~config
* @property {table~border} border
* @property {table~columns[]} columns Column specific configuration.
* @property {table~columns} columnDefault Default values for all columns. Column specific settings overwrite the default values.
* @property {table~drawHorizontalLine} drawHorizontalLine
* @property {table~singleLine} singleLine Horizontal lines inside the table are not drawn.
*/
/**
* Generates a text table.
*
* @param {table~row[]} data
* @param {table~config} userConfig
* @returns {string}
*/
const table = (data, userConfig = {}) => {
let rows;
(0, _validateTableData.default)(data);
rows = (0, _stringifyTableData.default)(data);
const config = (0, _makeConfig.default)(rows, userConfig);
rows = (0, _truncateTableData.default)(data, config);
const rowHeightIndex = (0, _calculateRowHeightIndex.default)(rows, config);
rows = (0, _mapDataUsingRowHeightIndex.default)(rows, rowHeightIndex, config);
rows = (0, _alignTableData.default)(rows, config);
rows = (0, _padTableData.default)(rows, config);
const cellWidthIndex = (0, _calculateCellWidthIndex.default)(rows[0]);
return (0, _drawTable.default)(rows, config.border, cellWidthIndex, rowHeightIndex, config.drawHorizontalLine, config.singleLine);
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const alignTableData_1 = __importDefault(require("./alignTableData"));
const calculateCellWidthIndex_1 = __importDefault(require("./calculateCellWidthIndex"));
const calculateRowHeightIndex_1 = __importDefault(require("./calculateRowHeightIndex"));
const drawTable_1 = __importDefault(require("./drawTable"));
const makeConfig_1 = __importDefault(require("./makeConfig"));
const mapDataUsingRowHeightIndex_1 = __importDefault(require("./mapDataUsingRowHeightIndex"));
const padTableData_1 = __importDefault(require("./padTableData"));
const stringifyTableData_1 = __importDefault(require("./stringifyTableData"));
const truncateTableData_1 = __importDefault(require("./truncateTableData"));
const validateTableData_1 = __importDefault(require("./validateTableData"));
exports.default = (data, userConfig = {}) => {
validateTableData_1.default(data);
let rows = stringifyTableData_1.default(data);
const config = makeConfig_1.default(rows, userConfig);
rows = truncateTableData_1.default(rows, config);
const rowHeightIndex = calculateRowHeightIndex_1.default(rows, config);
rows = mapDataUsingRowHeightIndex_1.default(rows, rowHeightIndex, config);
rows = alignTableData_1.default(rows, config);
rows = padTableData_1.default(rows, config);
const cellWidthIndex = calculateCellWidthIndex_1.default(rows[0]);
return drawTable_1.default(rows, cellWidthIndex, rowHeightIndex, config);
};
var _default = table;
exports.default = _default;
-96
View File
@@ -1,96 +0,0 @@
import alignTableData from './alignTableData';
import calculateCellWidthIndex from './calculateCellWidthIndex';
import calculateRowHeightIndex from './calculateRowHeightIndex';
import drawTable from './drawTable';
import makeConfig from './makeConfig';
import mapDataUsingRowHeightIndex from './mapDataUsingRowHeightIndex';
import padTableData from './padTableData';
import stringifyTableData from './stringifyTableData';
import truncateTableData from './truncateTableData';
import validateTableData from './validateTableData';
/**
* @typedef {string} table~cell
*/
/**
* @typedef {table~cell[]} table~row
*/
/**
* @typedef {object} table~columns
* @property {string} alignment Cell content alignment (enum: left, center, right) (default: left).
* @property {number} width Column width (default: auto).
* @property {number} truncate Number of characters are which the content will be truncated (default: Infinity).
* @property {boolean} wrapWord When true the text is broken at the nearest space or one of the special characters
* @property {number} paddingLeft Cell content padding width left (default: 1).
* @property {number} paddingRight Cell content padding width right (default: 1).
*/
/**
* @typedef {object} table~border
* @property {string} topBody
* @property {string} topJoin
* @property {string} topLeft
* @property {string} topRight
* @property {string} bottomBody
* @property {string} bottomJoin
* @property {string} bottomLeft
* @property {string} bottomRight
* @property {string} bodyLeft
* @property {string} bodyRight
* @property {string} bodyJoin
* @property {string} joinBody
* @property {string} joinLeft
* @property {string} joinRight
* @property {string} joinJoin
*/
/**
* Used to tell whether to draw a horizontal line.
* This callback is called for each non-content line of the table.
* The default behavior is to always return true.
*
* @typedef {Function} drawHorizontalLine
* @param {number} index
* @param {number} size
* @returns {boolean}
*/
/**
* @typedef {object} table~config
* @property {table~border} border
* @property {table~columns[]} columns Column specific configuration.
* @property {table~columns} columnDefault Default values for all columns. Column specific settings overwrite the default values.
* @property {table~drawHorizontalLine} drawHorizontalLine
* @property {table~singleLine} singleLine Horizontal lines inside the table are not drawn.
*/
/**
* Generates a text table.
*
* @param {table~row[]} data
* @param {table~config} userConfig
* @returns {string}
*/
export default (data, userConfig = {}) => {
let rows;
validateTableData(data);
rows = stringifyTableData(data);
const config = makeConfig(rows, userConfig);
rows = truncateTableData(data, config);
const rowHeightIndex = calculateRowHeightIndex(rows, config);
rows = mapDataUsingRowHeightIndex(rows, rowHeightIndex, config);
rows = alignTableData(rows, config);
rows = padTableData(rows, config);
const cellWidthIndex = calculateCellWidthIndex(rows[0]);
return drawTable(rows, config.border, cellWidthIndex, rowHeightIndex, config.drawHorizontalLine, config.singleLine);
};
+13 -23
View File
@@ -1,29 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _lodash = _interopRequireDefault(require("lodash.truncate"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const lodash_truncate_1 = __importDefault(require("lodash.truncate"));
/**
* @todo Make it work with ASCII content.
* @param {table~row[]} rows
* @param {object} config
* @returns {table~row[]}
*/
const truncateTableData = (rows, config) => {
return rows.map(cells => {
return cells.map((content, index) => {
return (0, _lodash.default)(content, {
length: config.columns[index].truncate
});
exports.default = (rows, config) => {
return rows.map((cells) => {
return cells.map((content, index) => {
return lodash_truncate_1.default(content, {
length: config.columns[index].truncate,
omission: '…',
});
});
});
});
};
var _default = truncateTableData;
exports.default = _default;
@@ -1,17 +0,0 @@
import truncate from 'lodash.truncate';
/**
* @todo Make it work with ASCII content.
* @param {table~row[]} rows
* @param {object} config
* @returns {table~row[]}
*/
export default (rows, config) => {
return rows.map((cells) => {
return cells.map((content, index) => {
return truncate(content, {
length: config.columns[index].truncate,
});
});
});
};
+2
View File
@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
+2
View File
@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
+21 -38
View File
@@ -1,40 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _validators = _interopRequireDefault(require("../dist/validators"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @param {string} schemaId
* @param {formatData~config} config
* @returns {undefined}
*/
const validateConfig = (schemaId, config = {}) => {
const validate = _validators.default[schemaId];
if (!validate(config)) {
const errors = validate.errors.map(error => {
return {
dataPath: error.dataPath,
message: error.message,
params: error.params,
schemaPath: error.schemaPath
};
});
/* eslint-disable no-console */
console.log('config', config);
console.log('errors', errors);
/* eslint-enable no-console */
throw new Error('Invalid config.');
}
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const validators_1 = __importDefault(require("./generated/validators"));
exports.default = (schemaId, config) => {
const validate = validators_1.default[schemaId];
if (!validate(config) && validate.errors) {
const errors = validate.errors.map((error) => {
return {
message: error.message,
params: error.params,
schemaPath: error.schemaPath,
};
});
/* eslint-disable no-console */
console.log('config', config);
console.log('errors', errors);
/* eslint-enable no-console */
throw new Error('Invalid config.');
}
};
var _default = validateConfig;
exports.default = _default;
@@ -1,27 +0,0 @@
import validators from '../dist/validators';
/**
* @param {string} schemaId
* @param {formatData~config} config
* @returns {undefined}
*/
export default (schemaId, config = {}) => {
const validate = validators[schemaId];
if (!validate(config)) {
const errors = validate.errors.map((error) => {
return {
dataPath: error.dataPath,
message: error.message,
params: error.params,
schemaPath: error.schemaPath,
};
});
/* eslint-disable no-console */
console.log('config', config);
console.log('errors', errors);
/* eslint-enable no-console */
throw new Error('Invalid config.');
}
};
+23 -49
View File
@@ -1,54 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @typedef {string} cell
*/
/**
* @typedef {cell[]} validateData~column
*/
/**
* @param {column[]} rows
* @returns {undefined}
*/
const validateTableData = rows => {
if (!Array.isArray(rows)) {
throw new TypeError('Table data must be an array.');
}
if (rows.length === 0) {
throw new Error('Table must define at least one row.');
}
if (rows[0].length === 0) {
throw new Error('Table must define at least one column.');
}
const columnNumber = rows[0].length;
for (const cells of rows) {
if (!Array.isArray(cells)) {
throw new TypeError('Table row data must be an array.');
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = (rows) => {
if (!Array.isArray(rows)) {
throw new TypeError('Table data must be an array.');
}
if (cells.length !== columnNumber) {
throw new Error('Table must have a consistent number of cells.');
if (rows.length === 0) {
throw new Error('Table must define at least one row.');
}
for (const cell of cells) {
// eslint-disable-next-line no-control-regex
if (/[\u0001-\u0006\u0008\u0009\u000B-\u001A]/.test(cell)) {
throw new Error('Table data must not contain control characters.');
}
if (rows[0].length === 0) {
throw new Error('Table must define at least one column.');
}
const columnNumber = rows[0].length;
for (const row of rows) {
if (!Array.isArray(row)) {
throw new TypeError('Table row data must be an array.');
}
if (row.length !== columnNumber) {
throw new Error('Table must have a consistent number of cells.');
}
for (const cell of row) {
// eslint-disable-next-line no-control-regex
if (/[\u0001-\u0006\u0008\u0009\u000B-\u001A]/.test(cell)) {
throw new Error('Table data must not contain control characters.');
}
}
}
}
};
var _default = validateTableData;
exports.default = _default;
@@ -1,44 +0,0 @@
/**
* @typedef {string} cell
*/
/**
* @typedef {cell[]} validateData~column
*/
/**
* @param {column[]} rows
* @returns {undefined}
*/
export default (rows) => {
if (!Array.isArray(rows)) {
throw new TypeError('Table data must be an array.');
}
if (rows.length === 0) {
throw new Error('Table must define at least one row.');
}
if (rows[0].length === 0) {
throw new Error('Table must define at least one column.');
}
const columnNumber = rows[0].length;
for (const cells of rows) {
if (!Array.isArray(cells)) {
throw new TypeError('Table row data must be an array.');
}
if (cells.length !== columnNumber) {
throw new Error('Table must have a consistent number of cells.');
}
for (const cell of cells) {
// eslint-disable-next-line no-control-regex
if (/[\u0001-\u0006\u0008\u0009\u000B-\u001A]/.test(cell)) {
throw new Error('Table data must not contain control characters.');
}
}
}
};
+38 -38
View File
@@ -1,47 +1,47 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _wrapString = _interopRequireDefault(require("./wrapString"));
var _wrapWord = _interopRequireDefault(require("./wrapWord"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const slice_ansi_1 = __importDefault(require("slice-ansi"));
const strip_ansi_1 = __importDefault(require("strip-ansi"));
const wrapString_1 = __importDefault(require("./wrapString"));
const wrapWord_1 = __importDefault(require("./wrapWord"));
const splitAnsi = (input) => {
const lengths = strip_ansi_1.default(input).split('\n').map(({ length }) => {
return length;
});
const result = [];
let startIndex = 0;
lengths.forEach((length) => {
result.push(length === 0 ? '' : slice_ansi_1.default(input, startIndex, startIndex + length));
// Plus 1 for the newline character itself
startIndex += length + 1;
});
return result;
};
/**
* Wrap a single cell value into a list of lines
*
* Always wraps on newlines, for the remainder uses either word or string wrapping
* depending on user configuration.
*
* @param {string} cellValue
* @param {number} columnWidth
* @param {boolean} useWrapWord
* @returns {Array}
*/
const wrapCell = (cellValue, columnWidth, useWrapWord) => {
// First split on literal newlines
const cellLines = cellValue.split('\n'); // Then iterate over the list and word-wrap every remaining line if necessary.
for (let lineNr = 0; lineNr < cellLines.length;) {
let lineChunks;
if (useWrapWord) {
lineChunks = (0, _wrapWord.default)(cellLines[lineNr], columnWidth);
} else {
lineChunks = (0, _wrapString.default)(cellLines[lineNr], columnWidth);
} // Replace our original array element with whatever the wrapping returned
cellLines.splice(lineNr, 1, ...lineChunks);
lineNr += lineChunks.length;
}
return cellLines;
exports.default = (cellValue, columnWidth, useWrapWord) => {
// First split on literal newlines
const cellLines = splitAnsi(cellValue);
// Then iterate over the list and word-wrap every remaining line if necessary.
for (let lineNr = 0; lineNr < cellLines.length;) {
let lineChunks;
if (useWrapWord) {
lineChunks = wrapWord_1.default(cellLines[lineNr], columnWidth);
}
else {
lineChunks = wrapString_1.default(cellLines[lineNr], columnWidth);
}
// Replace our original array element with whatever the wrapping returned
cellLines.splice(lineNr, 1, ...lineChunks);
lineNr += lineChunks.length;
}
return cellLines;
};
var _default = wrapCell;
exports.default = _default;
-35
View File
@@ -1,35 +0,0 @@
import wrapString from './wrapString';
import wrapWord from './wrapWord';
/**
* Wrap a single cell value into a list of lines
*
* Always wraps on newlines, for the remainder uses either word or string wrapping
* depending on user configuration.
*
* @param {string} cellValue
* @param {number} columnWidth
* @param {boolean} useWrapWord
* @returns {Array}
*/
export default (cellValue, columnWidth, useWrapWord) => {
// First split on literal newlines
const cellLines = cellValue.split('\n');
// Then iterate over the list and word-wrap every remaining line if necessary.
for (let lineNr = 0; lineNr < cellLines.length;) {
let lineChunks;
if (useWrapWord) {
lineChunks = wrapWord(cellLines[lineNr], columnWidth);
} else {
lineChunks = wrapString(cellLines[lineNr], columnWidth);
}
// Replace our original array element with whatever the wrapping returned
cellLines.splice(lineNr, 1, ...lineChunks);
lineNr += lineChunks.length;
}
return cellLines;
};
+14 -29
View File
@@ -1,16 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _sliceAnsi = _interopRequireDefault(require("slice-ansi"));
var _stringWidth = _interopRequireDefault(require("string-width"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const slice_ansi_1 = __importDefault(require("slice-ansi"));
const string_width_1 = __importDefault(require("string-width"));
/**
* Creates an array of strings split into groups the length of size.
* This function works with strings that contain ASCII characters.
@@ -18,22 +12,13 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
* wrapText is different from would-be "chunk" implementation
* in that whitespace characters that occur on a chunk size limit are trimmed.
*
* @param {string} subject
* @param {number} size
* @returns {Array}
*/
const wrapString = (subject, size) => {
let subjectSlice;
subjectSlice = subject;
const chunks = [];
do {
chunks.push((0, _sliceAnsi.default)(subjectSlice, 0, size));
subjectSlice = (0, _sliceAnsi.default)(subjectSlice, size).trim();
} while ((0, _stringWidth.default)(subjectSlice));
return chunks;
exports.default = (subject, size) => {
let subjectSlice = subject;
const chunks = [];
do {
chunks.push(slice_ansi_1.default(subjectSlice, 0, size));
subjectSlice = slice_ansi_1.default(subjectSlice, size).trim();
} while (string_width_1.default(subjectSlice));
return chunks;
};
var _default = wrapString;
exports.default = _default;
-29
View File
@@ -1,29 +0,0 @@
import slice from 'slice-ansi';
import stringWidth from 'string-width';
/**
* Creates an array of strings split into groups the length of size.
* This function works with strings that contain ASCII characters.
*
* wrapText is different from would-be "chunk" implementation
* in that whitespace characters that occur on a chunk size limit are trimmed.
*
* @param {string} subject
* @param {number} size
* @returns {Array}
*/
export default (subject, size) => {
let subjectSlice;
subjectSlice = subject;
const chunks = [];
do {
chunks.push(slice(subjectSlice, 0, size));
subjectSlice = slice(subjectSlice, size).trim();
} while (stringWidth(subjectSlice));
return chunks;
};
+37 -44
View File
@@ -1,46 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _sliceAnsi = _interopRequireDefault(require("slice-ansi"));
var _stringWidth = _interopRequireDefault(require("string-width"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @param {string} input
* @param {number} size
* @returns {Array}
*/
const wrapWord = (input, size) => {
let subject;
subject = input;
const chunks = []; // https://regex101.com/r/gY5kZ1/1
const re = new RegExp('(^.{1,' + size + '}(\\s+|$))|(^.{1,' + (size - 1) + '}(\\\\|/|_|\\.|,|;|-))');
do {
let chunk;
chunk = subject.match(re);
if (chunk) {
chunk = chunk[0];
subject = (0, _sliceAnsi.default)(subject, (0, _stringWidth.default)(chunk));
chunk = chunk.trim();
} else {
chunk = (0, _sliceAnsi.default)(subject, 0, size);
subject = (0, _sliceAnsi.default)(subject, size);
}
chunks.push(chunk);
} while ((0, _stringWidth.default)(subject));
return chunks;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const slice_ansi_1 = __importDefault(require("slice-ansi"));
const strip_ansi_1 = __importDefault(require("strip-ansi"));
const calculateStringLengths = (input, size) => {
let subject = strip_ansi_1.default(input);
const chunks = [];
// https://regex101.com/r/gY5kZ1/1
const re = new RegExp('(^.{1,' + String(size) + '}(\\s+|$))|(^.{1,' + String(size - 1) + '}(\\\\|/|_|\\.|,|;|-))');
do {
let chunk;
const match = re.exec(subject);
if (match) {
chunk = match[0];
subject = subject.slice(chunk.length);
const trimmedLength = chunk.trim().length;
const offset = chunk.length - trimmedLength;
chunks.push([trimmedLength, offset]);
}
else {
chunk = subject.slice(0, size);
subject = subject.slice(size);
chunks.push([chunk.length, 0]);
}
} while (subject.length);
return chunks;
};
exports.default = (input, size) => {
const result = [];
let startIndex = 0;
calculateStringLengths(input, size).forEach(([length, offset]) => {
result.push(slice_ansi_1.default(input, startIndex, startIndex + length));
startIndex += length + offset;
});
return result;
};
var _default = wrapWord;
exports.default = _default;
-39
View File
@@ -1,39 +0,0 @@
import slice from 'slice-ansi';
import stringWidth from 'string-width';
/**
* @param {string} input
* @param {number} size
* @returns {Array}
*/
export default (input, size) => {
let subject;
subject = input;
const chunks = [];
// https://regex101.com/r/gY5kZ1/1
const re = new RegExp('(^.{1,' + size + '}(\\s+|$))|(^.{1,' + (size - 1) + '}(\\\\|/|_|\\.|,|;|-))');
do {
let chunk;
chunk = subject.match(re);
if (chunk) {
chunk = chunk[0];
subject = slice(subject, stringWidth(chunk));
chunk = chunk.trim();
} else {
chunk = slice(subject, 0, size);
subject = slice(subject, size);
}
chunks.push(chunk);
} while (stringWidth(subject));
return chunks;
};
@@ -99,7 +99,7 @@ function validSchemaType(schema, schemaType, allowUndefined = false) {
: typeof schema == st || (allowUndefined && typeof schema == "undefined")));
}
exports.validSchemaType = validSchemaType;
function validateKeywordUsage({ schema, opts, self }, def, keyword) {
function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {
/* istanbul ignore if */
if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
throw new Error("ajv implementation error");
@@ -111,7 +111,8 @@ function validateKeywordUsage({ schema, opts, self }, def, keyword) {
if (def.validateSchema) {
const valid = def.validateSchema(schema[keyword]);
if (!valid) {
const msg = "keyword value is invalid: " + self.errorsText(def.validateSchema.errors);
const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` +
self.errorsText(def.validateSchema.errors);
if (opts.validateSchema === "log")
self.logger.error(msg);
else
@@ -61,7 +61,7 @@ const deprecatedOptions = {
const MAX_EXPRESSION = 200;
// eslint-disable-next-line complexity
function requiredOptions(o) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u;
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v;
const s = o.strict;
const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
@@ -80,6 +80,7 @@ function requiredOptions(o) {
addUsedSchema: (_s = o.addUsedSchema) !== null && _s !== void 0 ? _s : true,
validateSchema: (_t = o.validateSchema) !== null && _t !== void 0 ? _t : true,
validateFormats: (_u = o.validateFormats) !== null && _u !== void 0 ? _u : true,
unicodeRegExp: (_v = o.unicodeRegExp) !== null && _v !== void 0 ? _v : true,
};
}
class Ajv {
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more