WIP - add extractor, generate snippet_data

This commit is contained in:
Stefan Fejes
2019-08-20 15:52:05 +02:00
parent 88084d3d30
commit cc8f1d8a7a
37396 changed files with 4588842 additions and 133 deletions

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2016 Geoffroy Warin
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.

View File

@ -0,0 +1 @@
This is forked version of [`friendly-errors-webpack-plugin`](https://www.npmjs.com/package/friendly-errors-webpack-plugin) with only change being bumped [`chalk`](https://www.npmjs.com/package/chalk) version from `^1.1.3` to `^2.4.2` and using [`strip-ansi`](https://www.npmjs.com/package/strip-ansi) instead of `chalk.stripColor` because it was removed in `chalk@^2`.

View File

@ -0,0 +1,4 @@
const FriendlyErrorsWebpackPlugin = require('./src/friendly-errors-plugin');
module.exports = FriendlyErrorsWebpackPlugin;

View File

@ -0,0 +1,10 @@
'use strict';
module.exports = () => {
const pattern = [
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)',
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))'
].join('|');
return new RegExp(pattern, 'g');
};

View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.

View File

@ -0,0 +1,85 @@
{
"_from": "ansi-regex@^3.0.0",
"_id": "ansi-regex@3.0.0",
"_inBundle": false,
"_integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=",
"_location": "/@pieh/friendly-errors-webpack-plugin/ansi-regex",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "ansi-regex@^3.0.0",
"name": "ansi-regex",
"escapedName": "ansi-regex",
"rawSpec": "^3.0.0",
"saveSpec": null,
"fetchSpec": "^3.0.0"
},
"_requiredBy": [
"/@pieh/friendly-errors-webpack-plugin/string-width/strip-ansi"
],
"_resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz",
"_shasum": "ed0317c322064f79466c02966bddb605ab37d998",
"_spec": "ansi-regex@^3.0.0",
"_where": "/Users/stefanfejes/Projects/30-seconds-of-python-code/node_modules/@pieh/friendly-errors-webpack-plugin/node_modules/string-width/node_modules/strip-ansi",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/chalk/ansi-regex/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Regular expression for matching ANSI escape codes",
"devDependencies": {
"ava": "*",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/chalk/ansi-regex#readme",
"keywords": [
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"command-line",
"text",
"regex",
"regexp",
"re",
"match",
"test",
"find",
"pattern"
],
"license": "MIT",
"name": "ansi-regex",
"repository": {
"type": "git",
"url": "git+https://github.com/chalk/ansi-regex.git"
},
"scripts": {
"test": "xo && ava",
"view-supported": "node fixtures/view-codes.js"
},
"version": "3.0.0"
}

View File

@ -0,0 +1,46 @@
# ansi-regex [![Build Status](https://travis-ci.org/chalk/ansi-regex.svg?branch=master)](https://travis-ci.org/chalk/ansi-regex)
> Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code)
## Install
```
$ npm install ansi-regex
```
## Usage
```js
const ansiRegex = require('ansi-regex');
ansiRegex().test('\u001B[4mcake\u001B[0m');
//=> true
ansiRegex().test('cake');
//=> false
'\u001B[4mcake\u001B[0m'.match(ansiRegex());
//=> ['\u001B[4m', '\u001B[0m']
```
## FAQ
### Why do you test for codes not in the ECMA 48 standard?
Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them.
On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out.
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)
## License
MIT

View File

@ -0,0 +1,46 @@
'use strict';
/* eslint-disable yoda */
module.exports = x => {
if (Number.isNaN(x)) {
return false;
}
// code points are derived from:
// http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
if (
x >= 0x1100 && (
x <= 0x115f || // Hangul Jamo
x === 0x2329 || // LEFT-POINTING ANGLE BRACKET
x === 0x232a || // RIGHT-POINTING ANGLE BRACKET
// CJK Radicals Supplement .. Enclosed CJK Letters and Months
(0x2e80 <= x && x <= 0x3247 && x !== 0x303f) ||
// Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
(0x3250 <= x && x <= 0x4dbf) ||
// CJK Unified Ideographs .. Yi Radicals
(0x4e00 <= x && x <= 0xa4c6) ||
// Hangul Jamo Extended-A
(0xa960 <= x && x <= 0xa97c) ||
// Hangul Syllables
(0xac00 <= x && x <= 0xd7a3) ||
// CJK Compatibility Ideographs
(0xf900 <= x && x <= 0xfaff) ||
// Vertical Forms
(0xfe10 <= x && x <= 0xfe19) ||
// CJK Compatibility Forms .. Small Form Variants
(0xfe30 <= x && x <= 0xfe6b) ||
// Halfwidth and Fullwidth Forms
(0xff01 <= x && x <= 0xff60) ||
(0xffe0 <= x && x <= 0xffe6) ||
// Kana Supplement
(0x1b000 <= x && x <= 0x1b001) ||
// Enclosed Ideographic Supplement
(0x1f200 <= x && x <= 0x1f251) ||
// CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
(0x20000 <= x && x <= 0x3fffd)
)
) {
return true;
}
return false;
};

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.

View File

@ -0,0 +1,77 @@
{
"_from": "is-fullwidth-code-point@^2.0.0",
"_id": "is-fullwidth-code-point@2.0.0",
"_inBundle": false,
"_integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=",
"_location": "/@pieh/friendly-errors-webpack-plugin/is-fullwidth-code-point",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "is-fullwidth-code-point@^2.0.0",
"name": "is-fullwidth-code-point",
"escapedName": "is-fullwidth-code-point",
"rawSpec": "^2.0.0",
"saveSpec": null,
"fetchSpec": "^2.0.0"
},
"_requiredBy": [
"/@pieh/friendly-errors-webpack-plugin/string-width"
],
"_resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz",
"_shasum": "a3b30a5c4f199183167aaab93beefae3ddfb654f",
"_spec": "is-fullwidth-code-point@^2.0.0",
"_where": "/Users/stefanfejes/Projects/30-seconds-of-python-code/node_modules/@pieh/friendly-errors-webpack-plugin/node_modules/string-width",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/is-fullwidth-code-point/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Check if the character represented by a given Unicode code point is fullwidth",
"devDependencies": {
"ava": "*",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/is-fullwidth-code-point#readme",
"keywords": [
"fullwidth",
"full-width",
"full",
"width",
"unicode",
"character",
"char",
"string",
"str",
"codepoint",
"code",
"point",
"is",
"detect",
"check"
],
"license": "MIT",
"name": "is-fullwidth-code-point",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/is-fullwidth-code-point.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "2.0.0",
"xo": {
"esnext": true
}
}

View File

@ -0,0 +1,39 @@
# is-fullwidth-code-point [![Build Status](https://travis-ci.org/sindresorhus/is-fullwidth-code-point.svg?branch=master)](https://travis-ci.org/sindresorhus/is-fullwidth-code-point)
> Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms)
## Install
```
$ npm install --save is-fullwidth-code-point
```
## Usage
```js
const isFullwidthCodePoint = require('is-fullwidth-code-point');
isFullwidthCodePoint('谢'.codePointAt());
//=> true
isFullwidthCodePoint('a'.codePointAt());
//=> false
```
## API
### isFullwidthCodePoint(input)
#### input
Type: `number`
[Code point](https://en.wikipedia.org/wiki/Code_point) of a character.
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)

View File

@ -0,0 +1,36 @@
'use strict';
const stripAnsi = require('strip-ansi');
const isFullwidthCodePoint = require('is-fullwidth-code-point');
module.exports = str => {
if (typeof str !== 'string' || str.length === 0) {
return 0;
}
str = stripAnsi(str);
let width = 0;
for (let i = 0; i < str.length; i++) {
const code = str.codePointAt(i);
// Ignore control characters
if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) {
continue;
}
// Ignore combining characters
if (code >= 0x300 && code <= 0x36F) {
continue;
}
// Surrogates
if (code > 0xFFFF) {
i++;
}
width += isFullwidthCodePoint(code) ? 2 : 1;
}
return width;
};

View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.

View File

@ -0,0 +1,4 @@
'use strict';
const ansiRegex = require('ansi-regex');
module.exports = input => typeof input === 'string' ? input.replace(ansiRegex(), '') : input;

View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.

View File

@ -0,0 +1,84 @@
{
"_from": "strip-ansi@^4.0.0",
"_id": "strip-ansi@4.0.0",
"_inBundle": false,
"_integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=",
"_location": "/@pieh/friendly-errors-webpack-plugin/string-width/strip-ansi",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "strip-ansi@^4.0.0",
"name": "strip-ansi",
"escapedName": "strip-ansi",
"rawSpec": "^4.0.0",
"saveSpec": null,
"fetchSpec": "^4.0.0"
},
"_requiredBy": [
"/@pieh/friendly-errors-webpack-plugin/string-width"
],
"_resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz",
"_shasum": "a8479022eb1ac368a871389b635262c505ee368f",
"_spec": "strip-ansi@^4.0.0",
"_where": "/Users/stefanfejes/Projects/30-seconds-of-python-code/node_modules/@pieh/friendly-errors-webpack-plugin/node_modules/string-width",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/chalk/strip-ansi/issues"
},
"bundleDependencies": false,
"dependencies": {
"ansi-regex": "^3.0.0"
},
"deprecated": false,
"description": "Strip ANSI escape codes",
"devDependencies": {
"ava": "*",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/chalk/strip-ansi#readme",
"keywords": [
"strip",
"trim",
"remove",
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"license": "MIT",
"name": "strip-ansi",
"repository": {
"type": "git",
"url": "git+https://github.com/chalk/strip-ansi.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "4.0.0"
}

View File

@ -0,0 +1,39 @@
# strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi)
> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code)
## Install
```
$ npm install strip-ansi
```
## Usage
```js
const stripAnsi = require('strip-ansi');
stripAnsi('\u001B[4mUnicorn\u001B[0m');
//=> 'Unicorn'
```
## Related
- [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)
## License
MIT

View File

@ -0,0 +1,89 @@
{
"_from": "string-width@^2.0.0",
"_id": "string-width@2.1.1",
"_inBundle": false,
"_integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==",
"_location": "/@pieh/friendly-errors-webpack-plugin/string-width",
"_phantomChildren": {
"ansi-regex": "3.0.0"
},
"_requested": {
"type": "range",
"registry": true,
"raw": "string-width@^2.0.0",
"name": "string-width",
"escapedName": "string-width",
"rawSpec": "^2.0.0",
"saveSpec": null,
"fetchSpec": "^2.0.0"
},
"_requiredBy": [
"/@pieh/friendly-errors-webpack-plugin"
],
"_resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz",
"_shasum": "ab93f27a8dc13d28cac815c462143a6d9012ae9e",
"_spec": "string-width@^2.0.0",
"_where": "/Users/stefanfejes/Projects/30-seconds-of-python-code/node_modules/@pieh/friendly-errors-webpack-plugin",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/string-width/issues"
},
"bundleDependencies": false,
"dependencies": {
"is-fullwidth-code-point": "^2.0.0",
"strip-ansi": "^4.0.0"
},
"deprecated": false,
"description": "Get the visual width of a string - the number of columns required to display it",
"devDependencies": {
"ava": "*",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/string-width#readme",
"keywords": [
"string",
"str",
"character",
"char",
"unicode",
"width",
"visual",
"column",
"columns",
"fullwidth",
"full-width",
"full",
"ansi",
"escape",
"codes",
"cli",
"command-line",
"terminal",
"console",
"cjk",
"chinese",
"japanese",
"korean",
"fixed-width"
],
"license": "MIT",
"name": "string-width",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/string-width.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "2.1.1"
}

View File

@ -0,0 +1,42 @@
# string-width [![Build Status](https://travis-ci.org/sindresorhus/string-width.svg?branch=master)](https://travis-ci.org/sindresorhus/string-width)
> Get the visual width of a string - the number of columns required to display it
Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width.
Useful to be able to measure the actual width of command-line output.
## Install
```
$ npm install string-width
```
## Usage
```js
const stringWidth = require('string-width');
stringWidth('古');
//=> 2
stringWidth('\u001b[1m古\u001b[22m');
//=> 2
stringWidth('a');
//=> 1
```
## Related
- [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module
- [string-length](https://github.com/sindresorhus/string-length) - Get the real length of a string
- [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)

View File

@ -0,0 +1,79 @@
{
"_from": "@pieh/friendly-errors-webpack-plugin@1.7.0-chalk-2",
"_id": "@pieh/friendly-errors-webpack-plugin@1.7.0-chalk-2",
"_inBundle": false,
"_integrity": "sha512-65+vYGuDkHBCWWjqzzR/Ck318+d6yTI00EqII9qe3aPD1J3Olhvw0X38uM5moQb1PK/ksDXwSoPGt/5QhCiotw==",
"_location": "/@pieh/friendly-errors-webpack-plugin",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@pieh/friendly-errors-webpack-plugin@1.7.0-chalk-2",
"name": "@pieh/friendly-errors-webpack-plugin",
"escapedName": "@pieh%2ffriendly-errors-webpack-plugin",
"scope": "@pieh",
"rawSpec": "1.7.0-chalk-2",
"saveSpec": null,
"fetchSpec": "1.7.0-chalk-2"
},
"_requiredBy": [
"/gatsby"
],
"_resolved": "https://registry.npmjs.org/@pieh/friendly-errors-webpack-plugin/-/friendly-errors-webpack-plugin-1.7.0-chalk-2.tgz",
"_shasum": "2e9da9d3ade9d18d013333eb408c457d04eabac0",
"_spec": "@pieh/friendly-errors-webpack-plugin@1.7.0-chalk-2",
"_where": "/Users/stefanfejes/Projects/30-seconds-of-python-code/node_modules/gatsby",
"author": {
"name": "Geoffroy Warin"
},
"bugs": {
"url": "https://github.com/pieh/friendly-errors-webpack-plugin/issues"
},
"bundleDependencies": false,
"dependencies": {
"chalk": "^2.4.2",
"error-stack-parser": "^2.0.0",
"string-width": "^2.0.0",
"strip-ansi": "^3"
},
"deprecated": false,
"description": "Recognizes certain classes of webpack errors and cleans, aggregates and prioritizes them to provide a better Developer Experience",
"devDependencies": {
"babel-core": "^6.23.1",
"babel-eslint": "^7.1.1",
"babel-loader": "^6.3.0",
"babel-plugin-transform-async-to-generator": "^6.22.0",
"babel-preset-react": "^6.23.0",
"eslint": "^3.16.1",
"eslint-loader": "^1.6.1",
"expect": "^1.20.2",
"jest": "^18.1.0",
"memory-fs": "^0.4.1",
"webpack": "^2.2.1"
},
"files": [
"src",
"index.js"
],
"homepage": "https://github.com/pieh/friendly-errors-webpack-plugin#readme",
"keywords": [
"friendly",
"errors",
"webpack",
"plugin"
],
"license": "MIT",
"main": "index.js",
"name": "@pieh/friendly-errors-webpack-plugin",
"peerDependencies": {
"webpack": "^2.0.0 || ^3.0.0 || ^4.0.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/pieh/friendly-errors-webpack-plugin.git"
},
"scripts": {
"test": "eslint --ignore-pattern test/* && jest"
},
"version": "1.7.0-chalk-2"
}

View File

@ -0,0 +1,65 @@
'use strict';
const ErrorStackParser = require('error-stack-parser');
const RequestShortener = require("webpack/lib/RequestShortener");
// TODO: allow the location to be customized in options
const requestShortener = new RequestShortener(process.cwd());
/*
This logic is mostly duplicated from webpack/lib/Stats.js#toJson()
See: https://github.com/webpack/webpack/blob/2f618e733aab4755deb42e9d8e859609005607c0/lib/Stats.js#L89
*/
function extractError (e) {
return {
message: e.message,
file: getFile(e),
origin: getOrigin(e),
name: e.name,
severity: 0,
webpackError: e,
originalStack: getOriginalErrorStack(e)
};
}
function getOriginalErrorStack(e) {
while (e.error != null) {
e = e.error;
}
if (e.stack) {
return ErrorStackParser.parse(e);
}
return [];
}
function getFile (e) {
if (e.file) {
return e.file;
} else if (e.module && e.module.readableIdentifier && typeof e.module.readableIdentifier === "function") {
return e.module.readableIdentifier(requestShortener);
}
}
function getOrigin (e) {
let origin = '';
if (e.dependencies && e.origin) {
origin += '\n @ ' + e.origin.readableIdentifier(requestShortener);
e.dependencies.forEach(function (dep) {
if (!dep.loc) return;
if (typeof dep.loc === "string") return;
if (!dep.loc.start) return;
if (!dep.loc.end) return;
origin += ' ' + dep.loc.start.line + ':' + dep.loc.start.column + '-' +
(dep.loc.start.line !== dep.loc.end.line ? dep.loc.end.line + ':' : '') + dep.loc.end.column;
});
var current = e.origin;
while (current.issuer && typeof current.issuer.readableIdentifier === 'function') {
current = current.issuer;
origin += '\n @ ' + current.readableIdentifier(requestShortener);
}
}
return origin;
}
module.exports = extractError;

View File

@ -0,0 +1,18 @@
'use strict';
/**
* Applies formatters to all AnnotatedErrors.
*
* A formatter has the following signature: FormattedError => Array<String>.
* It takes a formatted error produced by a transformer and returns a list
* of log statements to print.
*
*/
function formatErrors(errors, formatters, errorType) {
const format = (formatter) => formatter(errors, errorType) || [];
const flatten = (accum, curr) => accum.concat(curr);
return formatters.map(format).reduce(flatten, [])
}
module.exports = formatErrors;

View File

@ -0,0 +1,34 @@
'use strict';
const extractError = require('./extractWebpackError');
/**
* Applies all transformers to all errors and returns "annotated"
* errors.
*
* Each transformer should have the following signature WebpackError => AnnotatedError
*
* A WebpackError has the following fields:
* - message
* - file
* - origin
* - name
* - severity
* - webpackError (original error)
*
* An AnnotatedError should be an extension (Object.assign) of the WebpackError
* and add whatever information is convenient for formatting.
* In particular, they should have a 'priority' field.
*
* The plugin will only display errors having maximum priority at the same time.
*
* If they don't have a 'type' field, the will be handled by the default formatter.
*/
function processErrors (errors, transformers) {
const transform = (error, transformer) => transformer(error);
const applyTransformations = (error) => transformers.reduce(transform, error);
return errors.map(extractError).map(applyTransformations);
}
module.exports = processErrors;

View File

@ -0,0 +1,43 @@
'use strict';
const concat = require('../utils').concat;
const formatTitle = require('../utils/colors').formatTitle;
function displayError(severity, error) {
const baseError = formatTitle(severity, severity);
return concat(
`${baseError} ${removeLoaders(error.file)}`,
'',
error.message,
(error.origin ? error.origin : undefined),
'',
error.infos
);
}
function removeLoaders(file) {
if (!file) {
return "";
}
const split = file.split('!');
const filePath = split[split.length - 1];
return `in ${filePath}`;
}
function isDefaultError(error) {
return !error.type;
}
/**
* Format errors without a type
*/
function format(errors, type) {
return errors
.filter(isDefaultError)
.reduce((accum, error) => (
accum.concat(displayError(type, error))
), []);
}
module.exports = format;

View File

@ -0,0 +1,31 @@
'use strict';
const concat = require('../utils').concat;
const chalk = require('chalk');
const infos = [
'You may use special comments to disable some warnings.',
'Use ' + chalk.yellow('// eslint-disable-next-line') + ' to ignore the next line.',
'Use ' + chalk.yellow('/* eslint-disable */') + ' to ignore all warnings in a file.'
];
function displayError(error) {
return [error.message, '']
}
function format(errors, type) {
const lintErrors = errors.filter(e => e.type === 'lint-error');
if (lintErrors.length > 0) {
const flatten = (accum, curr) => accum.concat(curr);
return concat(
lintErrors
.map(error => displayError(error))
.reduce(flatten, []),
infos
)
}
return [];
}
module.exports = format;

View File

@ -0,0 +1,92 @@
'use strict';
const concat = require('../utils').concat;
function isRelative (module) {
return module.startsWith('./') || module.startsWith('../');
}
function formatFileList (files) {
const length = files.length;
if (!length) return '';
return ` in ${files[0]}${files[1] ? `, ${files[1]}` : ''}${length > 2 ? ` and ${length - 2} other${length === 3 ? '' : 's'}` : ''}`;
}
function formatGroup (group) {
const files = group.errors.map(e => e.file).filter(Boolean);
return `* ${group.module}${formatFileList(files)}`;
}
function forgetToInstall (missingDependencies) {
const moduleNames = missingDependencies.map(missingDependency => missingDependency.module);
if (missingDependencies.length === 1) {
return `To install it, you can run: npm install --save ${moduleNames.join(' ')}`;
}
return `To install them, you can run: npm install --save ${moduleNames.join(' ')}`;
}
function dependenciesNotFound (dependencies) {
if (dependencies.length === 0) return;
return concat(
dependencies.length === 1 ? 'This dependency was not found:' : 'These dependencies were not found:',
'',
dependencies.map(formatGroup),
'',
forgetToInstall(dependencies)
);
}
function relativeModulesNotFound (modules) {
if (modules.length === 0) return;
return concat(
modules.length === 1 ? 'This relative module was not found:' : 'These relative modules were not found:',
'',
modules.map(formatGroup)
);
}
function groupModules (errors) {
const missingModule = new Map();
errors.forEach((error) => {
if (!missingModule.has(error.module)) {
missingModule.set(error.module, [])
}
missingModule.get(error.module).push(error);
});
return Array.from(missingModule.keys()).map(module => ({
module: module,
relative: isRelative(module),
errors: missingModule.get(module),
}));
}
function formatErrors (errors) {
if (errors.length === 0) {
return [];
}
const groups = groupModules(errors);
const dependencies = groups.filter(group => !group.relative);
const relativeModules = groups.filter(group => group.relative);
return concat(
dependenciesNotFound(dependencies),
dependencies.length && relativeModules.length ? ['', ''] : null,
relativeModulesNotFound(relativeModules)
);
}
function format (errors) {
return formatErrors(errors.filter((e) => (
e.type === 'module-not-found'
)));
}
module.exports = format;

View File

@ -0,0 +1,163 @@
'use strict';
const path = require('path');
const chalk = require('chalk');
const os = require('os');
const transformErrors = require('./core/transformErrors');
const formatErrors = require('./core/formatErrors');
const output = require('./output');
const utils = require('./utils');
const concat = utils.concat;
const uniqueBy = utils.uniqueBy;
const defaultTransformers = [
require('./transformers/babelSyntax'),
require('./transformers/moduleNotFound'),
require('./transformers/esLintError'),
];
const defaultFormatters = [
require('./formatters/moduleNotFound'),
require('./formatters/eslintError'),
require('./formatters/defaultError'),
];
class FriendlyErrorsWebpackPlugin {
constructor(options) {
options = options || {};
this.compilationSuccessInfo = options.compilationSuccessInfo || {};
this.onErrors = options.onErrors;
this.shouldClearConsole = options.clearConsole == null ? true : Boolean(options.clearConsole);
this.formatters = concat(defaultFormatters, options.additionalFormatters);
this.transformers = concat(defaultTransformers, options.additionalTransformers);
this.previousEndTimes = {};
}
apply(compiler) {
const doneFn = stats => {
this.clearConsole();
const hasErrors = stats.hasErrors();
const hasWarnings = stats.hasWarnings();
if (!hasErrors && !hasWarnings) {
this.displaySuccess(stats);
return;
}
if (hasErrors) {
this.displayErrors(extractErrorsFromStats(stats, 'errors'), 'error');
return;
}
if (hasWarnings) {
this.displayErrors(extractErrorsFromStats(stats, 'warnings'), 'warning');
}
};
const invalidFn = () => {
this.clearConsole();
output.title('info', 'WAIT', 'Compiling...');
};
if (compiler.hooks) {
const plugin = { name: 'FriendlyErrorsWebpackPlugin' };
compiler.hooks.done.tap(plugin, doneFn);
compiler.hooks.invalid.tap(plugin, invalidFn);
} else {
compiler.plugin('done', doneFn);
compiler.plugin('invalid', invalidFn);
}
}
clearConsole() {
if (this.shouldClearConsole) {
output.clearConsole();
}
}
displaySuccess(stats) {
const time = isMultiStats(stats) ? this.getMultiStatsCompileTime(stats) : this.getStatsCompileTime(stats);
output.title('success', 'DONE', 'Compiled successfully in ' + time + 'ms');
if (this.compilationSuccessInfo.messages) {
this.compilationSuccessInfo.messages.forEach(message => output.info(message));
}
if (this.compilationSuccessInfo.notes) {
output.log();
this.compilationSuccessInfo.notes.forEach(note => output.note(note));
}
}
displayErrors(errors, severity) {
const processedErrors = transformErrors(errors, this.transformers);
const topErrors = getMaxSeverityErrors(processedErrors);
const nbErrors = topErrors.length;
const subtitle = severity === 'error' ?
`Failed to compile with ${nbErrors} ${severity}s` :
`Compiled with ${nbErrors} ${severity}s`;
output.title(severity, severity.toUpperCase(), subtitle);
if (this.onErrors) {
this.onErrors(severity, topErrors);
}
formatErrors(topErrors, this.formatters, severity)
.forEach(chunk => output.log(chunk));
}
getStatsCompileTime(stats, statsIndex) {
// When we have multi compilations but only one of them is rebuilt, we need to skip the
// unchanged compilers to report the true rebuild time.
if (statsIndex !== undefined) {
if (this.previousEndTimes[statsIndex] === stats.endTime) {
return 0;
}
this.previousEndTimes[statsIndex] = stats.endTime;
}
return stats.endTime - stats.startTime;
}
getMultiStatsCompileTime(stats) {
// Webpack multi compilations run in parallel so using the longest duration.
// https://webpack.github.io/docs/configuration.html#multiple-configurations
return stats.stats
.reduce((time, stats, index) => Math.max(time, this.getStatsCompileTime(stats, index)), 0);
}
}
function extractErrorsFromStats(stats, type) {
if (isMultiStats(stats)) {
const errors = stats.stats
.reduce((errors, stats) => errors.concat(extractErrorsFromStats(stats, type)), []);
// Dedupe to avoid showing the same error many times when multiple
// compilers depend on the same module.
return uniqueBy(errors, error => error.message);
}
return stats.compilation[type];
}
function isMultiStats(stats) {
return stats.stats;
}
function getMaxSeverityErrors(errors) {
const maxSeverity = getMaxInt(errors, 'severity');
return errors.filter(e => e.severity === maxSeverity);
}
function getMaxInt(collection, propertyName) {
return collection.reduce((res, curr) => {
return curr[propertyName] > res ? curr[propertyName] : res;
}, 0)
}
module.exports = FriendlyErrorsWebpackPlugin;

View File

@ -0,0 +1,113 @@
'use strict';
const colors = require('./utils/colors');
const chalk = require('chalk');
const stringWidth = require('string-width');
const readline = require('readline');
const stripAnsi = require('strip-ansi');
class Debugger {
constructor () {
this.enabled = true;
this.capturing = false;
this.capturedMessages = [];
}
enable () {
this.enabled = true;
}
capture () {
this.enabled = true;
this.capturing = true;
}
endCapture () {
this.enabled = false;
this.capturing = false;
this.capturedMessages = [];
}
log () {
if (this.enabled) {
this.captureConsole(Array.from(arguments), console.log);
}
}
info (message) {
if (this.enabled) {
const titleFormatted = colors.formatTitle('info', 'I');
this.log(titleFormatted, message);
}
}
note (message) {
if (this.enabled) {
const titleFormatted = colors.formatTitle('note', 'N');
this.log(titleFormatted, message);
}
}
title (severity, title, subtitle) {
if (this.enabled) {
const date = new Date();
const dateString = chalk.grey(date.toLocaleTimeString());
const titleFormatted = colors.formatTitle(severity, title);
const subTitleFormatted = colors.formatText(severity, subtitle);
const message = `${titleFormatted} ${subTitleFormatted}`
// In test environment we don't include timestamp
if(process.env.NODE_ENV === 'test') {
this.log(message);
this.log();
return;
}
// Make timestamp appear at the end of the line
let logSpace = process.stdout.columns - stringWidth(message) - stringWidth(dateString)
if (logSpace <= 0) {
logSpace = 10
}
this.log(`${message}${' '.repeat(logSpace)}${dateString}`);
this.log();
}
}
clearConsole () {
if (!this.capturing && this.enabled && process.stdout.isTTY) {
// Fill screen with blank lines. Then move to 0 (beginning of visible part) and clear it
const blank = '\n'.repeat(process.stdout.rows)
console.log(blank)
readline.cursorTo(process.stdout, 0, 0)
readline.clearScreenDown(process.stdout)
}
}
captureLogs (fun) {
try {
this.capture();
fun.call();
return this.capturedMessages;
} catch (e) {
throw e;
} finally {
this.endCapture();
}
}
captureConsole (args, method) {
if (this.capturing) {
this.capturedMessages.push(stripAnsi(args.join(' ')).trim());
} else {
method.apply(console, args);
}
}
}
function capitalizeFirstLetter (string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
module.exports = new Debugger();

View File

@ -0,0 +1,38 @@
'use strict';
/**
* This will be removed in next versions as it is not handled in the babel-loader
* See: https://github.com/geowarin/friendly-errors-webpack-plugin/issues/2
*/
function cleanStackTrace(message) {
return message
.replace(/^\s*at\s.*:\d+:\d+[\s\)]*\n/gm, ''); // at ... ...:x:y
}
function cleanMessage(message) {
return message
// match until the last semicolon followed by a space
// this should match
// linux => "(SyntaxError: )Unexpected token (5:11)"
// windows => "(SyntaxError: C:/projects/index.js: )Unexpected token (5:11)"
.replace(/^Module build failed.*:\s/, 'Syntax Error: ');
}
function isBabelSyntaxError(e) {
return e.name === 'ModuleBuildError' &&
e.message.indexOf('SyntaxError') >= 0;
}
function transform(error) {
if (isBabelSyntaxError(error)) {
return Object.assign({}, error, {
message: cleanStackTrace(cleanMessage(error.message) + '\n'),
severity: 1000,
name: 'Syntax Error',
});
}
return error;
}
module.exports = transform;

View File

@ -0,0 +1,19 @@
'use strict';
function isEslintError (e) {
return e.originalStack
.some(stackframe => stackframe.fileName && stackframe.fileName.indexOf('eslint-loader') > 0);
}
function transform(error) {
if (isEslintError(error)) {
return Object.assign({}, error, {
name: 'Lint error',
type: 'lint-error',
});
}
return error;
}
module.exports = transform;

View File

@ -0,0 +1,30 @@
'use strict';
const TYPE = 'module-not-found';
function isModuleNotFoundError (e) {
const webpackError = e.webpackError || {};
return webpackError.dependencies
&& webpackError.dependencies.length > 0
&& e.name === 'ModuleNotFoundError'
&& e.message.indexOf('Module not found') === 0;
}
function transform(error) {
const webpackError = error.webpackError;
if (isModuleNotFoundError(error)) {
const dependency = webpackError.dependencies[0];
const module = dependency.request || dependency.options.request;
return Object.assign({}, error, {
message: `Module not found ${module}`,
type: TYPE,
severity: 900,
module,
name: 'Module not found'
});
}
return error;
}
module.exports = transform;

View File

@ -0,0 +1,38 @@
'use strict';
const chalk = require('chalk');
function formatTitle(severity, message) {
return chalk[bgColor(severity)].black('', message, '');
}
function formatText(severity, message) {
return chalk[textColor(severity)](message);
}
function bgColor(severity) {
const color = textColor(severity);
return 'bg'+ capitalizeFirstLetter(color)
}
function textColor(severity) {
switch (severity.toLowerCase()) {
case 'success': return 'green';
case 'info': return 'blue';
case 'note': return 'white';
case 'warning': return 'yellow';
case 'error': return 'red';
default: return 'red';
}
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
module.exports = {
bgColor: bgColor,
textColor: textColor,
formatTitle: formatTitle,
formatText: formatText
};

View File

@ -0,0 +1,31 @@
'use strict';
/**
* Concat and flattens non-null values.
* Ex: concat(1, undefined, 2, [3, 4]) = [1, 2, 3, 4]
*/
function concat() {
const args = Array.from(arguments).filter(e => e != null);
const baseArray = Array.isArray(args[0]) ? args[0] : [args[0]];
return Array.prototype.concat.apply(baseArray, args.slice(1));
}
/**
* Dedupes array based on criterion returned from iteratee function.
* Ex: uniqueBy(
* [{ id: 1 }, { id: 1 }, { id: 2 }],
* val => val.id
* ) = [{ id: 1 }, { id: 2 }]
*/
function uniqueBy(arr, fun) {
const seen = {};
return arr.filter(el => {
const e = fun(el);
return !(e in seen) && (seen[e] = 1);
})
}
module.exports = {
concat: concat,
uniqueBy: uniqueBy
};