node_modules

This commit is contained in:
Florian Dold 2017-12-27 19:33:54 +01:00
parent ceda0da31a
commit 0e6de2c31d
No known key found for this signature in database
GPG Key ID: D2E4F00F29D02A4B
3516 changed files with 3653 additions and 158692 deletions

View File

@ -1,10 +0,0 @@
'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

@ -1,9 +0,0 @@
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

@ -1,53 +0,0 @@
{
"name": "ansi-regex",
"version": "3.0.0",
"description": "Regular expression for matching ANSI escape codes",
"license": "MIT",
"repository": "chalk/ansi-regex",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=4"
},
"scripts": {
"test": "xo && ava",
"view-supported": "node fixtures/view-codes.js"
},
"files": [
"index.js"
],
"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"
],
"devDependencies": {
"ava": "*",
"xo": "*"
}
}

View File

@ -1,46 +0,0 @@
# 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

@ -1,36 +0,0 @@
'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

@ -1,9 +0,0 @@
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

@ -1,55 +0,0 @@
{
"name": "string-width",
"version": "2.1.1",
"description": "Get the visual width of a string - the number of columns required to display it",
"license": "MIT",
"repository": "sindresorhus/string-width",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=4"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js"
],
"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"
],
"dependencies": {
"is-fullwidth-code-point": "^2.0.0",
"strip-ansi": "^4.0.0"
},
"devDependencies": {
"ava": "*",
"xo": "*"
}
}

View File

@ -1,42 +0,0 @@
# 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

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

View File

@ -1,9 +0,0 @@
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

@ -1,52 +0,0 @@
{
"name": "strip-ansi",
"version": "4.0.0",
"description": "Strip ANSI escape codes",
"license": "MIT",
"repository": "chalk/strip-ansi",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=4"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js"
],
"keywords": [
"strip",
"trim",
"remove",
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"dependencies": {
"ansi-regex": "^3.0.0"
},
"devDependencies": {
"ava": "*",
"xo": "*"
}
}

View File

@ -1,39 +0,0 @@
# 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

12
node_modules/ansi-escapes/index.js generated vendored
View File

@ -3,12 +3,12 @@ const x = module.exports;
const ESC = '\u001B[';
const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal';
x.cursorTo = function (x, y) {
if (arguments.length === 0) {
return ESC + 'H';
x.cursorTo = (x, y) => {
if (typeof x !== 'number') {
throw new TypeError('The `x` argument is required');
}
if (arguments.length === 1) {
if (typeof y !== 'number') {
return ESC + (x + 1) + 'G';
}
@ -16,6 +16,10 @@ x.cursorTo = function (x, y) {
};
x.cursorMove = (x, y) => {
if (typeof x !== 'number') {
throw new TypeError('The `x` argument is required');
}
let ret = '';
if (x < 0) {

20
node_modules/ansi-escapes/license generated vendored
View File

@ -1,21 +1,9 @@
The MIT License (MIT)
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:
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 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.
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

@ -1,50 +1,50 @@
{
"name": "ansi-escapes",
"version": "2.0.0",
"description": "ANSI escape codes for manipulating the terminal",
"license": "MIT",
"repository": "sindresorhus/ansi-escapes",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=4"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js"
],
"keywords": [
"ansi",
"terminal",
"console",
"cli",
"string",
"tty",
"escape",
"escapes",
"formatting",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text",
"vt100",
"sequence",
"control",
"code",
"codes",
"cursor",
"iterm",
"iterm2"
],
"devDependencies": {
"ava": "*",
"xo": "*"
}
"name": "ansi-escapes",
"version": "3.0.0",
"description": "ANSI escape codes for manipulating the terminal",
"license": "MIT",
"repository": "sindresorhus/ansi-escapes",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=4"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js"
],
"keywords": [
"ansi",
"terminal",
"console",
"cli",
"string",
"tty",
"escape",
"escapes",
"formatting",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text",
"vt100",
"sequence",
"control",
"code",
"codes",
"cursor",
"iterm",
"iterm2"
],
"devDependencies": {
"ava": "*",
"xo": "*"
}
}

10
node_modules/ansi-escapes/readme.md generated vendored
View File

@ -6,7 +6,7 @@
## Install
```
$ npm install --save ansi-escapes
$ npm install ansi-escapes
```
@ -23,12 +23,10 @@ process.stdout.write(ansiEscapes.cursorUp(2) + ansiEscapes.cursorLeft);
## API
### cursorTo([x, [y]])
### cursorTo(x, [y])
Set the absolute position of the cursor. `x0` `y0` is the top left of the screen.
Specify either both `x` & `y`, only `x`, or nothing.
### cursorMove(x, [y])
Set the position of the cursor relative to its current position.
@ -129,7 +127,7 @@ Output a beeping sound.
Display an image.
*Currently only supported on iTerm >=2.9.*
*Currently only supported on iTerm2 >=3*
See [term-img](https://github.com/sindresorhus/term-img) for a higher-level module.
@ -163,7 +161,7 @@ Default: `true`
Type: `string`<br>
Default: `process.cwd()`
[Inform iTerm](https://www.iterm2.com/documentation-escape-codes.html) of the current directory to help semantic history and enable [Cmd-clicking relative paths](https://coderwall.com/p/b7e82q/quickly-open-files-in-iterm-with-cmd-click).
[Inform iTerm2](https://www.iterm2.com/documentation-escape-codes.html) of the current directory to help semantic history and enable [Cmd-clicking relative paths](https://coderwall.com/p/b7e82q/quickly-open-files-in-iterm-with-cmd-click).
## Related

99
node_modules/ava/api.js generated vendored
View File

@ -2,9 +2,11 @@
const EventEmitter = require('events');
const path = require('path');
const fs = require('fs');
const os = require('os');
const commonPathPrefix = require('common-path-prefix');
const uniqueTempDir = require('unique-temp-dir');
const findCacheDir = require('find-cache-dir');
const isCi = require('is-ci');
const resolveCwd = require('resolve-cwd');
const debounce = require('lodash.debounce');
const autoBind = require('auto-bind');
@ -53,6 +55,7 @@ class Api extends EventEmitter {
this.options = Object.assign({match: []}, options);
this.options.require = resolveModules(this.options.require);
}
_runFile(file, runStatus, execArgv) {
const hash = this.precompiler.precompileFile(file);
const precompiled = Object.assign({}, this._precompiledHelpers);
@ -69,17 +72,20 @@ class Api extends EventEmitter {
return emitter;
}
run(files, options) {
return new AvaFiles({cwd: this.options.resolveTestsFrom, files})
.findTestFiles()
.then(files => this._run(files, options));
}
_onTimeout(runStatus) {
const timeout = ms(this.options.timeout);
const err = new AvaError(`Exited because no new tests completed within the last ${timeout}ms of inactivity`);
this._handleError(runStatus, err);
runStatus.emit('timeout');
}
_setupTimeout(runStatus) {
const timeout = ms(this.options.timeout);
@ -90,9 +96,11 @@ class Api extends EventEmitter {
runStatus._restartTimer();
runStatus.on('test', runStatus._restartTimer);
}
_cancelTimeout(runStatus) {
runStatus._restartTimer.cancel();
}
_setupPrecompiler(files) {
const isCacheEnabled = this.options.cacheEnabled !== false;
let cacheDir = uniqueTempDir();
@ -119,6 +127,7 @@ class Api extends EventEmitter {
});
});
}
_precompileHelpers() {
this._precompiledHelpers = {};
@ -134,6 +143,7 @@ class Api extends EventEmitter {
this._precompiledHelpers[file] = hash;
});
}
_run(files, options) {
options = options || {};
@ -160,18 +170,20 @@ class Api extends EventEmitter {
this._setupTimeout(runStatus);
}
let overwatch;
let concurrency = Math.min(os.cpus().length, isCi ? 2 : Infinity);
if (this.options.concurrency > 0) {
const concurrency = this.options.serial ? 1 : this.options.concurrency;
overwatch = this._runWithPool(files, runStatus, concurrency);
} else {
// _runWithoutPool exists to preserve legacy behavior, specifically around `.only`
overwatch = this._runWithoutPool(files, runStatus);
concurrency = this.options.concurrency;
}
return overwatch;
if (this.options.serial) {
concurrency = 1;
}
return this._runWithPool(files, runStatus, concurrency);
});
}
_computeForkExecArgs(files) {
const execArgv = this.options.testOnlyExecArgv || process.execArgv;
let debugArgIndex = -1;
@ -217,85 +229,14 @@ class Api extends EventEmitter {
return forkExecArgv;
});
}
_handleError(runStatus, err) {
runStatus.handleExceptions({
exception: err,
file: err.file ? path.relative(process.cwd(), err.file) : undefined
});
}
_runWithoutPool(files, runStatus) {
const tests = [];
let execArgvList;
// TODO: This should be cleared at the end of the run
runStatus.on('timeout', () => {
tests.forEach(fork => {
fork.exit();
});
});
return this._computeForkExecArgs(files)
.then(argvList => {
execArgvList = argvList;
})
.return(files)
.each((file, index) => {
return new Promise(resolve => {
const forkArgs = execArgvList[index];
const test = this._runFile(file, runStatus, forkArgs);
tests.push(test);
test.on('stats', resolve);
test.catch(resolve);
}).catch(err => {
err.results = [];
err.file = file;
return Promise.reject(err);
});
})
.then(() => {
if (this.options.match.length > 0 && !runStatus.hasExclusive) {
const err = new AvaError('Couldn\'t find any matching tests');
err.file = undefined;
err.results = [];
return Promise.reject(err);
}
const method = this.options.serial ? 'mapSeries' : 'map';
const options = {
runOnlyExclusive: runStatus.hasExclusive
};
return Promise[method](files, (file, index) => {
return tests[index].run(options).catch(err => {
err.file = file;
this._handleError(runStatus, err);
return getBlankResults();
});
});
})
.catch(err => {
this._handleError(runStatus, err);
return err.results;
})
.tap(results => {
// If no tests ran, make sure to tear down the child processes
if (results.length === 0) {
tests.forEach(test => {
test.send('teardown');
});
}
})
.then(results => {
// Cancel debounced _onTimeout() from firing
if (this.options.timeout) {
this._cancelTimeout(runStatus);
}
runStatus.processResults(results);
return runStatus;
});
}
_runWithPool(files, runStatus, concurrency) {
const tests = [];
let execArgvList;

4
node_modules/ava/index.js.flow generated vendored
View File

@ -69,7 +69,7 @@ type AssertContext = {
// Assert that contents matches regex.
regex(contents: string, regex: RegExp, message?: string): void;
// Assert that contents matches a snapshot.
snapshot(contents: any, message?: string): void;
snapshot: ((contents: any, message?: string) => void) & ((contents: any, options: {id: string}, message?: string) => void);
// Assert that contents does not match regex.
notRegex(contents: string, regex: RegExp, message?: string): void;
// Assert that error is falsy.
@ -81,8 +81,10 @@ type AssertContext = {
*/
type TestContext = AssertContext & {
title: string;
plan(count: number): void;
skip: AssertContext;
log(message: string): void;
};
type ContextualTestContext = TestContext & { context: any; };
type ContextualCallbackTestContext = TestContext & { context: any; end(): void; };

32
node_modules/ava/lib/assert.js generated vendored
View File

@ -64,6 +64,7 @@ function wrapAssertions(callbacks) {
const pass = callbacks.pass;
const pending = callbacks.pending;
const fail = callbacks.fail;
const log = callbacks.log;
const noop = () => {};
const makeRethrow = reason => () => {
@ -86,14 +87,25 @@ function wrapAssertions(callbacks) {
if (Object.is(actual, expected)) {
pass(this);
} else {
const actualDescriptor = concordance.describe(actual, concordanceOptions);
const expectedDescriptor = concordance.describe(expected, concordanceOptions);
fail(this, new AssertionError({
assertion: 'is',
message,
raw: {actual, expected},
values: [formatDescriptorDiff(actualDescriptor, expectedDescriptor)]
}));
const result = concordance.compare(actual, expected, concordanceOptions);
const actualDescriptor = result.actual || concordance.describe(actual, concordanceOptions);
const expectedDescriptor = result.expected || concordance.describe(expected, concordanceOptions);
if (result.pass) {
fail(this, new AssertionError({
assertion: 'is',
message,
raw: {actual, expected},
values: [formatDescriptorWithLabel('Values are deeply equal to each other, but they are not the same:', actualDescriptor)]
}));
} else {
fail(this, new AssertionError({
assertion: 'is',
message,
raw: {actual, expected},
values: [formatDescriptorDiff(actualDescriptor, expectedDescriptor)]
}));
}
}
},
@ -110,6 +122,10 @@ function wrapAssertions(callbacks) {
}
},
log(text) {
log(this, text);
},
deepEqual(actual, expected, message) {
const result = concordance.compare(actual, expected, concordanceOptions);
if (result.pass) {

5
node_modules/ava/lib/ava-files.js generated vendored
View File

@ -125,6 +125,7 @@ class AvaFiles {
autoBind(this);
}
findTestFiles() {
return handlePaths(this.files, this.excludePatterns, {
cwd: this.cwd,
@ -134,6 +135,7 @@ class AvaFiles {
symlinks: Object.create(null)
});
}
findTestHelpers() {
return handlePaths(defaultHelperPatterns(), ['!**/node_modules/**'], {
cwd: this.cwd,
@ -144,6 +146,7 @@ class AvaFiles {
symlinks: Object.create(null)
});
}
isSource(filePath) {
let mixedPatterns = [];
const defaultIgnorePatterns = getDefaultIgnorePatterns();
@ -195,6 +198,7 @@ class AvaFiles {
return false;
}
isTest(filePath) {
const excludePatterns = this.excludePatterns;
const initialPatterns = this.files.concat(excludePatterns);
@ -241,6 +245,7 @@ class AvaFiles {
// excludePatterns into account. This mimicks the behavior in api.js
return multimatch(matchable(filePath), recursivePatterns.concat(excludePatterns)).length === 1;
}
getChokidarPatterns() {
let paths = [];
let ignored = [];

View File

@ -6,6 +6,7 @@ const figures = require('figures');
const configManager = require('hullabaloo-config-manager');
const md5Hex = require('md5-hex');
const makeDir = require('make-dir');
const semver = require('semver');
const colors = require('./colors');
function validate(conf) {
@ -99,6 +100,7 @@ function build(projectDir, cacheDir, userOptions, powerAssert) {
const baseOptions = {
babelrc: false,
plugins: [],
presets: [
['@ava/transform-test-files', {powerAssert}]
]
@ -107,6 +109,12 @@ function build(projectDir, cacheDir, userOptions, powerAssert) {
baseOptions.presets.unshift('@ava/stage-4');
}
// Include object rest spread support for node versions that support it
// natively.
if (userOptions === 'default' && semver.satisfies(process.versions.node, '>= 8.3.0')) {
baseOptions.plugins.push('babel-plugin-syntax-object-rest-spread');
}
const baseConfig = configManager.createConfig({
dir: AVA_DIR, // Presets are resolved relative to this directory
hash: md5Hex(JSON.stringify(baseOptions)),

View File

@ -8,6 +8,7 @@ let ignoreStackLines = [];
const avaInternals = /\/ava\/(?:lib\/)?[\w-]+\.js:\d+:\d+\)?$/;
const avaDependencies = /\/node_modules\/(?:bluebird|empower-core|(?:ava\/node_modules\/)?(?:babel-runtime|core-js))\//;
const stackFrameLine = /^.+( \(.+:\d+:\d+\)|:\d+:\d+)$/;
if (!debug.enabled) {
ignoreStackLines = StackUtils.nodeInternals();
@ -17,21 +18,55 @@ if (!debug.enabled) {
const stackUtils = new StackUtils({internals: ignoreStackLines});
function extractFrames(stack) {
return stack
.split('\n')
.map(line => line.trim())
.filter(line => stackFrameLine.test(line))
.join('\n');
}
/**
* Given a string value of the format generated for the `stack` property of a
* V8 error object, return a string that contains only stack frame information
* for frames that have relevance to the consumer.
*
* For example, given the following string value:
*
* ```
* Error
* at inner (/home/ava/ex.js:7:12)
* at /home/ava/ex.js:12:5
* at outer (/home/ava/ex.js:13:4)
* at Object.<anonymous> (/home/ava/ex.js:14:3)
* at Module._compile (module.js:570:32)
* at Object.Module._extensions..js (module.js:579:10)
* at Module.load (module.js:487:32)
* at tryModuleLoad (module.js:446:12)
* at Function.Module._load (module.js:438:3)
* at Module.runMain (module.js:604:10)
* ```
*
* ...this function returns the following string value:
*
* ```
* inner (/home/ava/ex.js:7:12)
* /home/ava/ex.js:12:5
* outer (/home/ava/ex.js:13:4)
* Object.<anonymous> (/home/ava/ex.js:14:3)
* ```
*/
module.exports = stack => {
if (!stack) {
return '';
}
stack = extractFrames(stack);
// Workaround for https://github.com/tapjs/stack-utils/issues/14
// TODO: fix it in `stack-utils`
stack = cleanStack(stack);
const title = stack.split('\n')[0];
const lines = stackUtils
.clean(stack)
.split('\n')
.map(x => ` ${x}`)
.join('\n');
return `${title}\n${lines}`;
return stackUtils.clean(stack)
// Remove the trailing newline inserted by the `stack-utils` module
.trim();
};

View File

@ -33,6 +33,7 @@ class CachingPrecompiler {
this.fileHashes = {};
this.transform = this._createTransform();
}
precompileFile(filePath) {
if (!this.fileHashes[filePath]) {
const source = stripBomBuf(fs.readFileSync(filePath));
@ -41,11 +42,13 @@ class CachingPrecompiler {
return this.fileHashes[filePath];
}
// Conditionally called by caching-transform when precompiling is required
_init() {
this.babel = require('babel-core');
return this._transform;
}
_transform(code, filePath, hash) {
code = code.toString();
@ -79,6 +82,7 @@ class CachingPrecompiler {
return `${result.code}\n${comment}`;
}
_createTransform() {
const salt = packageHash.sync([
require.resolve('../package.json'),
@ -93,6 +97,7 @@ class CachingPrecompiler {
ext: '.js'
});
}
_generateHash(code, filePath, salt) {
const hash = md5Hex([code, filePath, salt]);
this.fileHashes[filePath] = hash;

14
node_modules/ava/lib/cli.js generated vendored
View File

@ -43,7 +43,7 @@ exports.run = () => {
--match, -m Only run tests with matching title (Can be repeated)
--watch, -w Re-run tests when tests and source files change
--timeout, -T Set global timeout
--concurrency, -c Maximum number of test files running at the same time (EXPERIMENTAL)
--concurrency, -c Max number of test files running at the same time (Default: CPU cores)
--update-snapshots, -u Update snapshots
Examples
@ -75,7 +75,7 @@ exports.run = () => {
],
default: {
cache: conf.cache,
color: 'color' in conf ? conf.color : require('supports-color') !== false,
color: 'color' in conf ? conf.color : require('supports-color').stdout !== false,
concurrency: conf.concurrency,
failFast: conf.failFast,
init: conf.init,
@ -119,7 +119,12 @@ exports.run = () => {
}
if (cli.flags.concurrency === '') {
throw new Error(colors.error(figures.cross) + ' The --concurrency and -c flags must be provided the maximum number of test files to run at once.');
throw new Error(colors.error(figures.cross) + ' The --concurrency and -c flags must be provided.');
}
if (cli.flags.concurrency &&
(!Number.isInteger(Number.parseFloat(cli.flags.concurrency)) || parseInt(cli.flags.concurrency, 10) < 0)) {
throw new Error(colors.error(figures.cross) + ' The --concurrency and -c flags must be a nonnegative integer.');
}
if (hasFlag('--require') || hasFlag('-r')) {
@ -144,6 +149,7 @@ exports.run = () => {
timeout: conf.timeout,
concurrency: conf.concurrency ? parseInt(conf.concurrency, 10) : 0,
updateSnapshots: conf.updateSnapshots,
snapshotDir: conf.snapshotDir ? path.resolve(projectDir, conf.snapshotDir) : null,
color: conf.color
});
@ -152,7 +158,7 @@ exports.run = () => {
if (conf.tap && !conf.watch) {
reporter = new TapReporter();
} else if (conf.verbose || isCi) {
reporter = new VerboseReporter({color: conf.color});
reporter = new VerboseReporter({color: conf.color, watching: conf.watch});
} else {
reporter = new MiniReporter({color: conf.color, watching: conf.watch});
}

1
node_modules/ava/lib/colors.js generated vendored
View File

@ -2,6 +2,7 @@
const chalk = require('chalk');
module.exports = {
log: chalk.gray,
title: chalk.bold.white,
error: chalk.red,
skip: chalk.yellow,

View File

@ -1,6 +1,7 @@
'use strict';
const concordance = require('concordance');
const dotProp = require('dot-prop');
const generate = require('babel-generator').default;
const concordanceOptions = require('./concordance-options').default;
// When adding patterns, don't forget to add to
@ -15,31 +16,16 @@ const PATTERNS = [
't.notRegex(contents, regex, [message])'
];
const isRangeMatch = (a, b) => {
return (a[0] === b[0] && a[1] === b[1]) ||
(a[0] > b[0] && a[0] < b[1]) ||
(a[1] > b[0] && a[1] < b[1]);
};
const computeStatement = (tokens, range) => {
return tokens
.filter(token => isRangeMatch(token.range, range))
.map(token => token.value === undefined ? token.type.label : token.value)
.join('');
};
const computeStatement = node => generate(node, {quotes: 'single'}).code;
const getNode = (ast, path) => dotProp.get(ast, path.replace(/\//g, '.'));
const formatter = context => {
const ast = JSON.parse(context.source.ast);
const tokens = JSON.parse(context.source.tokens);
const args = context.args[0].events;
return args
.map(arg => {
const range = getNode(ast, arg.espath).range;
const statement = computeStatement(tokens, range);
const node = getNode(ast, arg.espath);
const statement = computeStatement(node);
const formatted = concordance.format(arg.value, concordanceOptions);
return [statement, formatted];
})

View File

@ -1,10 +0,0 @@
'use strict';
const stackLineRegex = /^.+ \(.+:[0-9]+:[0-9]+\)$/;
module.exports = stack => {
return stack
.split('\n')
.filter(line => stackLineRegex.test(line))
.map(line => line.trim())
.join('\n');
};

4
node_modules/ava/lib/fork.js generated vendored
View File

@ -10,12 +10,10 @@ if (fs.realpathSync(__filename) !== __filename) {
console.warn('WARNING: `npm link ava` and the `--preserve-symlink` flag are incompatible. We have detected that AVA is linked via `npm link`, and that you are using either an early version of Node 6, or the `--preserve-symlink` flag. This breaks AVA. You should upgrade to Node 6.2.0+, avoid the `--preserve-symlink` flag, or avoid using `npm link ava`.');
}
let env = process.env;
const env = Object.assign({NODE_ENV: 'test'}, process.env);
// Ensure NODE_PATH paths are absolute
if (env.NODE_PATH) {
env = Object.assign({}, env);
env.NODE_PATH = env.NODE_PATH
.split(path.delimiter)
.map(x => path.resolve(x))

11
node_modules/ava/lib/logger.js generated vendored
View File

@ -6,6 +6,7 @@ class Logger {
this.reporter = reporter;
autoBind(this);
}
start(runStatus) {
if (!this.reporter.start) {
return;
@ -13,6 +14,7 @@ class Logger {
this.write(this.reporter.start(runStatus), runStatus);
}
reset(runStatus) {
if (!this.reporter.reset) {
return;
@ -20,9 +22,11 @@ class Logger {
this.write(this.reporter.reset(runStatus), runStatus);
}
test(test, runStatus) {
this.write(this.reporter.test(test, runStatus), runStatus);
}
unhandledError(err, runStatus) {
if (!this.reporter.unhandledError) {
return;
@ -30,6 +34,7 @@ class Logger {
this.write(this.reporter.unhandledError(err, runStatus), runStatus);
}
finish(runStatus) {
if (!this.reporter.finish) {
return;
@ -37,6 +42,7 @@ class Logger {
this.write(this.reporter.finish(runStatus), runStatus);
}
section() {
if (!this.reporter.section) {
return;
@ -44,6 +50,7 @@ class Logger {
this.write(this.reporter.section());
}
clear() {
if (!this.reporter.clear) {
return false;
@ -52,6 +59,7 @@ class Logger {
this.write(this.reporter.clear());
return true;
}
write(str, runStatus) {
if (typeof str === 'undefined') {
return;
@ -59,6 +67,7 @@ class Logger {
this.reporter.write(str, runStatus);
}
stdout(data, runStatus) {
if (!this.reporter.stdout) {
return;
@ -66,6 +75,7 @@ class Logger {
this.reporter.stdout(data, runStatus);
}
stderr(data, runStatus) {
if (!this.reporter.stderr) {
return;
@ -73,6 +83,7 @@ class Logger {
this.reporter.stderr(data, runStatus);
}
exit(code) {
process.exit(code); // eslint-disable-line unicorn/no-process-exit
}

3
node_modules/ava/lib/main.js generated vendored
View File

@ -13,7 +13,8 @@ const runner = new Runner({
match: opts.match,
projectDir: opts.projectDir,
serial: opts.serial,
updateSnapshots: opts.updateSnapshots
updateSnapshots: opts.updateSnapshots,
snapshotDir: opts.snapshotDir
});
worker.setRunner(runner);

View File

@ -15,7 +15,9 @@ exports.forError = error => {
Visit the following URL for more details:
${chalk.blue.underline('https://github.com/avajs/ava#throwsfunctionpromise-error-message')}`;
} else if (assertion === 'snapshot') {
}
if (assertion === 'snapshot') {
const name = error.improperUsage.name;
const snapPath = error.improperUsage.snapPath;

View File

@ -5,12 +5,12 @@ const lastLineTracker = require('last-line-stream/tracker');
const plur = require('plur');
const spinners = require('cli-spinners');
const chalk = require('chalk');
const figures = require('figures');
const cliTruncate = require('cli-truncate');
const cross = require('figures').cross;
const indentString = require('indent-string');
const ansiEscapes = require('ansi-escapes');
const trimOffNewlines = require('trim-off-newlines');
const extractStack = require('../extract-stack');
const codeExcerpt = require('../code-excerpt');
const colors = require('../colors');
const formatSerializedError = require('./format-serialized-error');
@ -33,6 +33,7 @@ class MiniReporter {
this.stream = process.stderr;
this.stringDecoder = new StringDecoder();
}
start() {
this.interval = setInterval(() => {
this.spinnerIndex = (this.spinnerIndex + 1) % this.spinnerFrames.length;
@ -41,6 +42,7 @@ class MiniReporter {
return this.prefix('');
}
reset() {
this.clearInterval();
this.passCount = 0;
@ -56,13 +58,16 @@ class MiniReporter {
this.spinnerIndex = 0;
this.lastLineTracker = lastLineTracker();
}
spinnerChar() {
return this.spinnerFrames[this.spinnerIndex];
}
clearInterval() {
clearInterval(this.interval);
this.interval = null;
}
test(test) {
if (test.todo) {
this.todoCount++;
@ -83,6 +88,7 @@ class MiniReporter {
return this.prefix(this._test(test));
}
prefix(str) {
str = str || this.currentTest;
this.currentTest = str;
@ -91,6 +97,7 @@ class MiniReporter {
// TODO(jamestalmage): Figure out why it's needed and document it here
return ` \n ${this.spinnerChar()} ${str}`;
}
_test(test) {
const SPINNER_WIDTH = 3;
const PADDING = 1;
@ -102,6 +109,7 @@ class MiniReporter {
return title + '\n' + this.reportCounts();
}
unhandledError(err) {
if (err.type === 'exception') {
this.exceptionCount++;
@ -109,6 +117,7 @@ class MiniReporter {
this.rejectionCount++;
}
}
reportCounts(time) {
const lines = [
this.passCount > 0 ? '\n ' + colors.pass(this.passCount, 'passed') : '',
@ -124,6 +133,7 @@ class MiniReporter {
return lines.join('');
}
finish(runStatus) {
this.clearInterval();
let time;
@ -163,6 +173,21 @@ class MiniReporter {
}
status += ' ' + colors.title(test.title) + '\n';
if (test.logs) {
test.logs.forEach(log => {
const logLines = indentString(colors.log(log), 6);
const logLinesWithLeadingFigure = logLines.replace(
/^ {6}/,
` ${colors.information(figures.info)} `
);
status += logLinesWithLeadingFigure + '\n';
});
status += '\n';
}
if (test.error.source) {
status += ' ' + colors.errorSource(test.error.source.file + ':' + test.error.source.line) + '\n';
@ -191,9 +216,9 @@ class MiniReporter {
}
if (test.error.stack) {
const extracted = extractStack(test.error.stack);
if (extracted.includes('\n')) {
status += '\n' + indentString(colors.errorStack(extracted), 2) + '\n';
const stack = test.error.stack;
if (stack.includes('\n')) {
status += '\n' + indentString(colors.errorStack(stack), 2) + '\n';
}
}
@ -212,14 +237,14 @@ class MiniReporter {
status += ' ' + colors.error(cross + ' ' + err.message) + '\n\n';
} else {
const title = err.type === 'rejection' ? 'Unhandled Rejection' : 'Uncaught Exception';
let description = err.stack ? err.stack.trimRight() : JSON.stringify(err);
description = description.split('\n');
const errorTitle = err.name ? description[0] : 'Threw non-error: ' + description[0];
const errorStack = description.slice(1).join('\n');
status += ' ' + colors.title(title) + '\n';
status += ' ' + colors.stack(errorTitle) + '\n';
status += colors.errorStack(errorStack) + '\n\n';
if (err.name) {
status += ' ' + colors.stack(err.summary) + '\n';
status += colors.errorStack(err.stack) + '\n\n';
} else {
status += ' Threw non-error: ' + err.summary + '\n';
}
}
});
}
@ -235,24 +260,30 @@ class MiniReporter {
return '\n' + trimOffNewlines(status) + '\n';
}
section() {
return '\n' + chalk.gray.dim('\u2500'.repeat(process.stdout.columns || 80));
}
clear() {
return '';
}
write(str) {
cliCursor.hide();
this.currentStatus = str;
this._update();
this.statusLineCount = this.currentStatus.split('\n').length;
}
stdout(data) {
this._update(data);
}
stderr(data) {
this._update(data);
}
_update(data) {
let str = '';
let ct = this.statusLineCount;

View File

@ -3,12 +3,6 @@ const format = require('util').format;
const indentString = require('indent-string');
const stripAnsi = require('strip-ansi');
const yaml = require('js-yaml');
const extractStack = require('../extract-stack');
// Parses stack trace and extracts original function name, file name and line
function getSourceFromStack(stack) {
return extractStack(stack).split('\n')[0];
}
function dumpError(error, includeMessage) {
const obj = Object.assign({}, error.object);
@ -35,7 +29,7 @@ function dumpError(error, includeMessage) {
}
if (error.stack) {
obj.at = getSourceFromStack(error.stack);
obj.at = error.stack.split('\n')[0];
}
return ` ---\n${indentString(yaml.safeDump(obj).trim(), 4)}\n ...`;
@ -45,11 +39,13 @@ class TapReporter {
constructor() {
this.i = 0;
}
start() {
return 'TAP version 13';
}
test(test) {
let output;
const output = [];
let directive = '';
const passed = test.todo ? 'not ok' : 'ok';
@ -62,21 +58,34 @@ class TapReporter {
const title = stripAnsi(test.title);
const appendLogs = () => {
if (test.logs) {
test.logs.forEach(log => {
const logLines = indentString(log, 4);
const logLinesWithLeadingFigure = logLines.replace(
/^ {4}/,
' * '
);
output.push(logLinesWithLeadingFigure);
});
}
};
output.push(`# ${title}`);
if (test.error) {
output = [
'# ' + title,
format('not ok %d - %s', ++this.i, title),
dumpError(test.error, true)
];
output.push(format('not ok %d - %s', ++this.i, title));
appendLogs();
output.push(dumpError(test.error, true));
} else {
output = [
`# ${title}`,
format('%s %d - %s %s', passed, ++this.i, title, directive).trim()
];
output.push(format('%s %d - %s %s', passed, ++this.i, title, directive).trim());
appendLogs();
}
return output.join('\n');
}
unhandledError(err) {
const output = [
`# ${err.message}`,
@ -89,6 +98,7 @@ class TapReporter {
return output.join('\n');
}
finish(runStatus) {
const output = [
'',
@ -105,12 +115,15 @@ class TapReporter {
return output.join('\n');
}
write(str) {
console.log(str);
}
stdout(data) {
process.stderr.write(data);
}
stderr(data) {
this.stdout(data);
}

View File

@ -5,7 +5,6 @@ const figures = require('figures');
const chalk = require('chalk');
const plur = require('plur');
const trimOffNewlines = require('trim-off-newlines');
const extractStack = require('../extract-stack');
const codeExcerpt = require('../code-excerpt');
const colors = require('../colors');
const formatSerializedError = require('./format-serialized-error');
@ -20,34 +19,46 @@ class VerboseReporter {
colors[key].enabled = this.options.color;
}
}
start() {
return '';
}
test(test, runStatus) {
const lines = [];
if (test.error) {
return ' ' + colors.error(figures.cross) + ' ' + test.title + ' ' + colors.error(test.error.message);
}
if (test.todo) {
return ' ' + colors.todo('- ' + test.title);
lines.push(' ' + colors.error(figures.cross) + ' ' + test.title + ' ' + colors.error(test.error.message));
} else if (test.todo) {
lines.push(' ' + colors.todo('- ' + test.title));
} else if (test.skip) {
return ' ' + colors.skip('- ' + test.title);
lines.push(' ' + colors.skip('- ' + test.title));
} else if (test.failing) {
lines.push(' ' + colors.error(figures.tick) + ' ' + colors.error(test.title));
} else if (runStatus.fileCount === 1 && runStatus.testCount === 1 && test.title === '[anonymous]') {
// No output
} else {
// Display duration only over a threshold
const threshold = 100;
const duration = test.duration > threshold ? colors.duration(' (' + prettyMs(test.duration) + ')') : '';
lines.push(' ' + colors.pass(figures.tick) + ' ' + test.title + duration);
}
if (test.failing) {
return ' ' + colors.error(figures.tick) + ' ' + colors.error(test.title);
if (test.logs) {
test.logs.forEach(log => {
const logLines = indentString(colors.log(log), 6);
const logLinesWithLeadingFigure = logLines.replace(
/^ {6}/,
` ${colors.information(figures.info)} `
);
lines.push(logLinesWithLeadingFigure);
});
}
if (runStatus.fileCount === 1 && runStatus.testCount === 1 && test.title === '[anonymous]') {
return undefined;
}
// Display duration only over a threshold
const threshold = 100;
const duration = test.duration > threshold ? colors.duration(' (' + prettyMs(test.duration) + ')') : '';
return ' ' + colors.pass(figures.tick) + ' ' + test.title + duration;
return lines.length > 0 ? lines.join('\n') : undefined;
}
unhandledError(err) {
if (err.type === 'exception' && err.name === 'AvaError') {
return colors.error(' ' + figures.cross + ' ' + err.message);
@ -61,6 +72,7 @@ class VerboseReporter {
let output = colors.error(types[err.type] + ':', err.file) + '\n';
if (err.stack) {
output += ' ' + colors.stack(err.title || err.summary) + '\n';
output += ' ' + colors.stack(err.stack) + '\n';
} else {
output += ' ' + colors.stack(JSON.stringify(err)) + '\n';
@ -70,6 +82,7 @@ class VerboseReporter {
return output;
}
finish(runStatus) {
let output = '';
@ -86,7 +99,9 @@ class VerboseReporter {
].filter(Boolean);
if (lines.length > 0) {
lines[0] += ' ' + chalk.gray.dim('[' + new Date().toLocaleTimeString('en-US', {hour12: false}) + ']');
if (this.options.watching) {
lines[0] += ' ' + chalk.gray.dim('[' + new Date().toLocaleTimeString('en-US', {hour12: false}) + ']');
}
output += lines.join('\n') + '\n';
}
@ -104,6 +119,21 @@ class VerboseReporter {
}
output += ' ' + colors.title(test.title) + '\n';
if (test.logs) {
test.logs.forEach(log => {
const logLines = indentString(colors.log(log), 6);
const logLinesWithLeadingFigure = logLines.replace(
/^ {6}/,
` ${colors.information(figures.info)} `
);
output += logLinesWithLeadingFigure + '\n';
});
output += '\n';
}
if (test.error.source) {
output += ' ' + colors.errorSource(test.error.source.file + ':' + test.error.source.line) + '\n';
@ -132,9 +162,9 @@ class VerboseReporter {
}
if (test.error.stack) {
const extracted = extractStack(test.error.stack);
if (extracted.includes('\n')) {
output += '\n' + indentString(colors.errorStack(extracted), 2) + '\n';
const stack = test.error.stack;
if (stack.includes('\n')) {
output += '\n' + indentString(colors.errorStack(stack), 2) + '\n';
}
}
@ -153,15 +183,19 @@ class VerboseReporter {
return '\n' + trimOffNewlines(output) + '\n';
}
section() {
return chalk.gray.dim('\u2500'.repeat(process.stdout.columns || 80));
}
write(str) {
console.error(str);
}
stdout(data) {
process.stderr.write(data);
}
stderr(data) {
process.stderr.write(data);
}

9
node_modules/ava/lib/run-status.js generated vendored
View File

@ -44,6 +44,7 @@ class RunStatus extends EventEmitter {
autoBind(this);
}
observeFork(emitter) {
emitter
.on('teardown', this.handleTeardown)
@ -54,6 +55,7 @@ class RunStatus extends EventEmitter {
.on('stdout', this.handleOutput.bind(this, 'stdout'))
.on('stderr', this.handleOutput.bind(this, 'stderr'));
}
handleRejections(data) {
this.rejectionCount += data.rejections.length;
@ -64,6 +66,7 @@ class RunStatus extends EventEmitter {
this.errors.push(err);
});
}
handleExceptions(data) {
this.exceptionCount++;
const err = data.exception;
@ -72,10 +75,12 @@ class RunStatus extends EventEmitter {
this.emit('error', err, this);
this.errors.push(err);
}
handleTeardown(data) {
this.emit('dependencies', data.file, data.dependencies, this);
this.emit('touchedFiles', data.touchedFiles);
}
handleStats(stats) {
this.emit('stats', stats, this);
@ -85,6 +90,7 @@ class RunStatus extends EventEmitter {
this.testCount += stats.testCount;
}
handleTest(test) {
test.title = this.prefixTitle(test.file) + test.title;
@ -98,6 +104,7 @@ class RunStatus extends EventEmitter {
this.emit('test', test, this);
}
prefixTitle(file) {
if (!this.prefixTitles) {
return '';
@ -107,9 +114,11 @@ class RunStatus extends EventEmitter {
return prefixTitle(file, this.base, separator);
}
handleOutput(channel, data) {
this.emit(channel, data, this);
}
processResults(results) {
// Assemble stats from all tests
this.stats = results.map(result => result.stats);

7
node_modules/ava/lib/runner.js generated vendored
View File

@ -52,6 +52,7 @@ class Runner extends EventEmitter {
this.projectDir = options.projectDir;
this.serial = options.serial;
this.updateSnapshots = options.updateSnapshots;
this.snapshotDir = options.snapshotDir;
this.hasStarted = false;
this.results = [];
@ -112,7 +113,7 @@ class Runner extends EventEmitter {
}
if (metadata.type === 'test' && this.match.length > 0) {
metadata.exclusive = title !== null && matcher([title], this.match).length === 1;
metadata.exclusive = matcher([title || ''], this.match).length === 1;
}
const validationError = validateTest(title, fn, metadata);
@ -130,6 +131,7 @@ class Runner extends EventEmitter {
addTestResult(result) {
const test = result.result;
const props = {
logs: test.logs,
duration: test.duration,
title: test.title,
error: result.reason,
@ -183,6 +185,8 @@ class Runner extends EventEmitter {
compareTestSnapshot(options) {
if (!this.snapshots) {
this.snapshots = snapshotManager.load({
file: this.file,
fixedLocation: this.snapshotDir,
name: path.basename(this.file),
projectDir: this.projectDir,
relFile: path.relative(this.projectDir, this.file),
@ -219,6 +223,7 @@ class Runner extends EventEmitter {
});
return Bluebird.try(() => this.tests.build().run());
}
attributeLeakedError(err) {
return this.tests.attributeLeakedError(err);
}

View File

@ -4,7 +4,6 @@ const cleanYamlObject = require('clean-yaml-object');
const StackUtils = require('stack-utils');
const assert = require('./assert');
const beautifyStack = require('./beautify-stack');
const extractStack = require('./extract-stack');
function isAvaAssertionError(source) {
return source instanceof assert.AssertionError;
@ -20,7 +19,7 @@ function extractSource(stack) {
return null;
}
const firstStackLine = extractStack(stack).split('\n')[0];
const firstStackLine = stack.split('\n')[0];
return stackUtils.parseLine(firstStackLine);
}
function buildSource(source) {
@ -90,5 +89,11 @@ module.exports = error => {
}
}
if (typeof error.stack === 'string') {
retval.summary = error.stack.split('\n')[0];
} else {
retval.summary = JSON.stringify(error);
}
return retval;
};

View File

@ -11,6 +11,7 @@ const indentString = require('indent-string');
const makeDir = require('make-dir');
const md5Hex = require('md5-hex');
const Buffer = require('safe-buffer').Buffer;
const convertSourceMap = require('convert-source-map');
const concordanceOptions = require('./concordance-options').snapshotManager;
@ -355,18 +356,39 @@ class Manager {
}
}
function determineSnapshotDir(projectDir, testDir) {
const parts = new Set(path.relative(projectDir, testDir).split(path.sep));
function determineSnapshotDir(options) {
const testDir = determineSourceMappedDir(options);
if (options.fixedLocation) {
const relativeTestLocation = path.relative(options.projectDir, testDir);
return path.join(options.fixedLocation, relativeTestLocation);
}
const parts = new Set(path.relative(options.projectDir, testDir).split(path.sep));
if (parts.has('__tests__')) {
return path.join(testDir, '__snapshots__');
} else if (parts.has('test') || parts.has('tests')) { // Accept tests, even though it's not in the default test patterns
}
if (parts.has('test') || parts.has('tests')) { // Accept tests, even though it's not in the default test patterns
return path.join(testDir, 'snapshots');
}
return testDir;
}
function determineSourceMappedDir(options) {
const source = tryRead(options.file).toString();
const converter = convertSourceMap.fromSource(source) || convertSourceMap.fromMapFileSource(source, options.testDir);
if (converter) {
const map = converter.toObject();
const firstSource = `${map.sourceRoot || ''}${map.sources[0]}`;
const sourceFile = path.resolve(options.testDir, firstSource);
return path.dirname(sourceFile);
}
return options.testDir;
}
function load(options) {
const dir = determineSnapshotDir(options.projectDir, options.testDir);
const dir = determineSnapshotDir(options);
const reportFile = `${options.name}.md`;
const snapFile = `${options.name}.snap`;
const snapPath = path.join(dir, snapFile);

View File

@ -33,6 +33,7 @@ class TestCollection extends EventEmitter {
this._emitTestResult = this._emitTestResult.bind(this);
}
add(test) {
const metadata = test.metadata;
const type = metadata.type;
@ -91,6 +92,7 @@ class TestCollection extends EventEmitter {
this.tests.concurrent.push(test);
}
}
_skippedTest(test) {
return {
run: () => {
@ -103,10 +105,12 @@ class TestCollection extends EventEmitter {
}
};
}
_emitTestResult(result) {
this.pendingTestInstances.delete(result.result);
this.emit('test', result);
}
_buildHooks(hooks, testTitle, context) {
return hooks.map(hook => {
const test = this._buildHook(hook, testTitle, context);
@ -118,6 +122,7 @@ class TestCollection extends EventEmitter {
return test;
});
}
_buildHook(hook, testTitle, contextRef) {
let title = hook.title;
@ -141,6 +146,7 @@ class TestCollection extends EventEmitter {
this.pendingTestInstances.add(test);
return test;
}
_buildTest(test, contextRef) {
if (!contextRef) {
contextRef = null;
@ -158,6 +164,7 @@ class TestCollection extends EventEmitter {
this.pendingTestInstances.add(test);
return test;
}
_buildTestWithHooks(test) {
if (test.metadata.skipped || test.metadata.todo) {
return new Sequence([this._skippedTest(this._buildTest(test))], true);
@ -175,24 +182,41 @@ class TestCollection extends EventEmitter {
}
return sequence;
}
_buildTests(tests) {
return tests.map(test => this._buildTestWithHooks(test));
}
build() {
const beforeHooks = new Sequence(this._buildHooks(this.hooks.before));
const afterHooks = new Sequence(this._buildHooks(this.hooks.after));
_hasUnskippedTests() {
return this.tests.serial.concat(this.tests.concurrent)
.some(test => {
return !(test.metadata && test.metadata.skipped === true);
});
}
build() {
const serialTests = new Sequence(this._buildTests(this.tests.serial), this.bail);
const concurrentTests = new Concurrent(this._buildTests(this.tests.concurrent), this.bail);
const allTests = new Sequence([serialTests, concurrentTests]);
let finalTests = new Sequence([beforeHooks, allTests, afterHooks], true);
let finalTests;
// Only run before and after hooks when there are unskipped tests
if (this._hasUnskippedTests()) {
const beforeHooks = new Sequence(this._buildHooks(this.hooks.before));
const afterHooks = new Sequence(this._buildHooks(this.hooks.after));
finalTests = new Sequence([beforeHooks, allTests, afterHooks], true);
} else {
finalTests = new Sequence([allTests], true);
}
if (this.hooks.afterAlways.length > 0) {
const afterAlwaysHooks = new Sequence(this._buildHooks(this.hooks.afterAlways));
finalTests = new Sequence([finalTests, afterAlwaysHooks], false);
}
return finalTests;
}
attributeLeakedError(err) {
for (const test of this.pendingTestInstances) {
if (test.attributeLeakedError(err)) {

13
node_modules/ava/lib/test-worker.js generated vendored
View File

@ -2,7 +2,6 @@
// Check if the test is being run without AVA cli
{
/* eslint-disable import/order */
const path = require('path');
const chalk = require('chalk');
@ -17,22 +16,18 @@
}
}
const currentlyUnhandled = require('currently-unhandled')();
const isObj = require('is-obj');
const adapter = require('./process-adapter');
const globals = require('./globals');
const opts = adapter.opts;
globals.options = opts;
/* eslint-enable import/order */
const Bluebird = require('bluebird');
const currentlyUnhandled = require('currently-unhandled')();
const isObj = require('is-obj');
const serializeError = require('./serialize-error');
// Bluebird specific
Bluebird.longStackTraces();
(opts.require || []).forEach(require);
(opts.require || []).forEach(x => require(x));
adapter.installSourceMapSupport();
adapter.installPrecompilerHook();

10
node_modules/ava/lib/test.js generated vendored
View File

@ -71,6 +71,7 @@ class ExecutionContext {
_throwsArgStart(assertion, file, line) {
this._test.trackThrows({assertion, file, line});
}
_throwsArgEnd() {
this._test.trackThrows(null);
}
@ -78,6 +79,10 @@ class ExecutionContext {
{
const assertions = assert.wrapAssertions({
log(executionContext, text) {
executionContext._test.addLog(text);
},
pass(executionContext) {
executionContext._test.countPassedAssertion();
},
@ -108,6 +113,7 @@ class Test {
this.metadata = options.metadata;
this.onResult = options.onResult;
this.title = options.title;
this.logs = [];
this.snapshotInvocationCount = 0;
this.compareWithSnapshot = assertionOptions => {
@ -175,6 +181,10 @@ class Test {
this.assertCount++;
}
addLog(text) {
this.logs.push(text);
}
addPendingAssertion(promise) {
if (this.finishing) {
this.saveFirstError(new Error('Assertion passed, but test has already finished'));

20
node_modules/ava/lib/watcher.js generated vendored
View File

@ -25,6 +25,7 @@ class Debouncer {
this.timer = null;
this.repeat = false;
}
debounce(delay) {
if (this.timer) {
this.again = true;
@ -55,6 +56,7 @@ class Debouncer {
this.timer = timer;
}
cancel() {
if (this.timer) {
clearTimeout(this.timer);
@ -69,6 +71,7 @@ class TestDependency {
this.file = file;
this.sources = sources;
}
contains(source) {
return this.sources.indexOf(source) !== -1;
}
@ -146,6 +149,7 @@ class Watcher {
this.watchFiles();
this.rerunAll();
}
watchFiles() {
const patterns = this.avaFiles.getChokidarPatterns();
@ -160,16 +164,18 @@ class Watcher {
}
});
}
trackTestDependencies(api) {
const relative = absPath => nodePath.relative(process.cwd(), absPath);
api.on('test-run', runStatus => {
runStatus.on('dependencies', (file, dependencies) => {
const sourceDeps = dependencies.map(relative).filter(this.avaFiles.isSource);
const sourceDeps = dependencies.map(x => relative(x)).filter(this.avaFiles.isSource);
this.updateTestDependencies(file, sourceDeps);
});
});
}
updateTestDependencies(file, sources) {
if (sources.length === 0) {
this.testDependencies = this.testDependencies.filter(dep => dep.file !== file);
@ -190,6 +196,7 @@ class Watcher {
this.testDependencies.push(new TestDependency(file, sources));
}
}
trackTouchedFiles(api) {
api.on('test-run', runStatus => {
runStatus.on('touchedFiles', files => {
@ -199,11 +206,13 @@ class Watcher {
});
});
}
trackExclusivity(api) {
api.on('stats', stats => {
this.updateExclusivity(stats.file, stats.hasExclusive);
});
}
updateExclusivity(file, hasExclusiveTests) {
const index = this.filesWithExclusiveTests.indexOf(file);
@ -213,6 +222,7 @@ class Watcher {
this.filesWithExclusiveTests.splice(index, 1);
}
}
trackFailures(api) {
api.on('test-run', (runStatus, files) => {
files.forEach(file => {
@ -230,9 +240,11 @@ class Watcher {
});
});
}
pruneFailures(file) {
this.filesWithFailures = this.filesWithFailures.filter(state => state.file !== file);
}
countFailure(file, vector) {
const isUpdate = this.filesWithFailures.some(state => {
if (state.file !== file) {
@ -251,6 +263,7 @@ class Watcher {
});
}
}
sumPreviousFailures(beforeVector) {
let total = 0;
@ -262,6 +275,7 @@ class Watcher {
return total;
}
cleanUnlinkedTests(unlinkedTests) {
unlinkedTests.forEach(testFile => {
this.updateTestDependencies(testFile, []);
@ -269,6 +283,7 @@ class Watcher {
this.pruneFailures(testFile);
});
}
observeStdin(stdin) {
stdin.resume();
stdin.setEncoding('utf8');
@ -295,14 +310,17 @@ class Watcher {
});
});
}
rerunAll() {
this.dirtyStates = {};
this.run();
}
updatePreviousSnapshots() {
this.dirtyStates = {};
this.run(this.previousFiles, true);
}
runAfterChanges() {
const dirtyStates = this.dirtyStates;
this.dirtyStates = {};

View File

@ -58,11 +58,17 @@ for (const key of Object.keys(ansiStyles)) {
styles[key] = {
get() {
const codes = ansiStyles[key];
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], key);
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
}
};
}
styles.visible = {
get() {
return build.call(this, this._styles || [], true, 'visible');
}
};
ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
for (const model of Object.keys(ansiStyles.color.ansi)) {
if (skipModels.has(model)) {
@ -79,7 +85,7 @@ for (const model of Object.keys(ansiStyles.color.ansi)) {
close: ansiStyles.color.close,
closeRe: ansiStyles.color.closeRe
};
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], model);
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
};
}
};
@ -102,7 +108,7 @@ for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
close: ansiStyles.bgColor.close,
closeRe: ansiStyles.bgColor.closeRe
};
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], model);
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
};
}
};
@ -110,12 +116,13 @@ for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
const proto = Object.defineProperties(() => {}, styles);
function build(_styles, key) {
function build(_styles, _empty, key) {
const builder = function () {
return applyStyle.apply(builder, arguments);
};
builder._styles = _styles;
builder._empty = _empty;
const self = this;
@ -167,7 +174,7 @@ function applyStyle() {
}
if (!this.enabled || this.level <= 0 || !str) {
return str;
return this._empty ? '' : str;
}
// Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
@ -218,3 +225,4 @@ Object.defineProperties(Chalk.prototype, styles);
module.exports = Chalk(); // eslint-disable-line new-cap
module.exports.supportsColor = supportsColor;
module.exports.default = module.exports; // For TypeScript

View File

@ -1,6 +1,6 @@
{
"name": "chalk",
"version": "2.1.0",
"version": "2.3.0",
"description": "Terminal string styling done right",
"license": "MIT",
"repository": "chalk/chalk",
@ -8,13 +8,14 @@
"node": ">=4"
},
"scripts": {
"test": "xo && nyc ava",
"test": "xo && tsc --project types && nyc ava",
"bench": "matcha benchmark.js",
"coveralls": "nyc report --reporter=text-lcov | coveralls"
},
"files": [
"index.js",
"templates.js"
"templates.js",
"types/index.d.ts"
],
"keywords": [
"color",
@ -46,14 +47,16 @@
},
"devDependencies": {
"ava": "*",
"coveralls": "^2.11.2",
"execa": "^0.7.0",
"coveralls": "^3.0.0",
"execa": "^0.8.0",
"import-fresh": "^2.0.0",
"matcha": "^0.7.0",
"nyc": "^11.0.2",
"resolve-from": "^3.0.0",
"resolve-from": "^4.0.0",
"typescript": "^2.5.3",
"xo": "*"
},
"types": "types/index.d.ts",
"xo": {
"envs": [
"node",

View File

@ -9,7 +9,7 @@
> Terminal string styling done right
[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo)
[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo) [![Mentioned in Awesome Node.js](https://awesome.re/mentioned-badge.svg)](https://github.com/sindresorhus/awesome-nodejs)
### [See what's new in Chalk 2](https://github.com/chalk/chalk/releases/tag/v2.0.0)
@ -170,6 +170,7 @@ Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=
- `inverse`
- `hidden`
- `strikethrough` *(Not widely supported)*
- `visible` (Text is emitted only if enabled)
### Colors
@ -286,6 +287,7 @@ If you're on Windows, do yourself a favor and use [`cmder`](http://cmder.net/) i
- [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal
- [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color
- [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Strip ANSI escape codes from a stream
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
- [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
@ -293,6 +295,7 @@ If you're on Windows, do yourself a favor and use [`cmder`](http://cmder.net/) i
- [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models
- [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal
- [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to strings
- [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings
## Maintainers

View File

@ -1,28 +1,28 @@
'use strict';
const TEMPLATE_REGEX = /(?:\\(u[a-f0-9]{4}|x[a-f0-9]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
const ESCAPE_REGEX = /\\(u[0-9a-f]{4}|x[0-9a-f]{2}|.)|([^\\])/gi;
const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
const ESCAPES = {
n: '\n',
r: '\r',
t: '\t',
b: '\b',
f: '\f',
v: '\v',
0: '\0',
'\\': '\\',
e: '\u001b',
a: '\u0007'
};
const ESCAPES = new Map([
['n', '\n'],
['r', '\r'],
['t', '\t'],
['b', '\b'],
['f', '\f'],
['v', '\v'],
['0', '\0'],
['\\', '\\'],
['e', '\u001B'],
['a', '\u0007']
]);
function unescape(c) {
if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
return String.fromCharCode(parseInt(c.slice(1), 16));
}
return ESCAPES[c] || c;
return ESCAPES.get(c) || c;
}
function parseArguments(name, args) {

80
node_modules/ava/package.json generated vendored
View File

@ -1,48 +1,17 @@
{
"name": "ava",
"version": "0.21.0",
"version": "0.24.0",
"description": "Futuristic test runner 🚀",
"license": "MIT",
"repository": "avajs/ava",
"homepage": "https://ava.li",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"maintainers": [
{
"name": "Vadim Demedes",
"email": "vdemedes@gmail.com",
"url": "github.com/vadimdemedes"
},
{
"name": "James Talmage",
"email": "james@talmage.io",
"url": "github.com/jamestalmage"
},
{
"name": "Mark Wubben",
"email": "mark@novemberborn.net",
"url": "novemberborn.net"
},
{
"name": "Juan Soto",
"email": "juan@juansoto.me",
"url": "juansoto.me"
},
{
"name": "Jeroen Engels",
"email": "jfm.engels@gmail.com",
"url": "github.com/jfmengels"
}
],
"bin": "cli.js",
"engines": {
"node": ">=4"
},
"scripts": {
"test": "xo && flow check test/flow-types && tsc -p test/ts-types && nyc tap --no-cov --timeout=300 --jobs=4 test/*.js test/reporters/*.js",
"lint": "xo && (cd test/fixture && xo '**' '!{source-map-initial,syntax-error}.js' '!snapshots/test-sourcemaps/build/**') && lock-verify",
"test": "npm run lint && flow check test/flow-types && tsc -p test/ts-types && nyc tap --no-cov --timeout=300 --jobs=4 test/*.js test/reporters/*.js",
"test-win": "tap --no-cov --reporter=classic --timeout=300 --jobs=4 test/*.js test/reporters/*.js",
"visual": "node test/visual/run-visual-tests.js",
"prepublish": "npm run make-ts",
@ -75,7 +44,6 @@
"babel",
"assert",
"assertion",
"futuristic",
"promise",
"promises",
"async",
@ -85,8 +53,8 @@
"generators",
"yield",
"observable",
"unit",
"observables",
"unit",
"snapshot",
"expect",
"typescript",
@ -97,7 +65,7 @@
"@ava/babel-preset-transform-test-files": "^3.0.0",
"@ava/write-file-atomic": "^2.2.0",
"@concordance/react": "^1.0.0",
"ansi-escapes": "^2.0.0",
"ansi-escapes": "^3.0.0",
"ansi-styles": "^3.1.0",
"arr-flatten": "^1.0.1",
"array-union": "^1.0.1",
@ -106,6 +74,8 @@
"auto-bind": "^1.1.0",
"ava-init": "^0.2.0",
"babel-core": "^6.17.0",
"babel-generator": "^6.26.0",
"babel-plugin-syntax-object-rest-spread": "^6.13.0",
"bluebird": "^3.0.0",
"caching-transform": "^1.0.0",
"chalk": "^2.0.1",
@ -122,7 +92,7 @@
"convert-source-map": "^1.2.0",
"core-assert": "^0.2.0",
"currently-unhandled": "^0.4.1",
"debug": "^2.2.0",
"debug": "^3.0.1",
"dot-prop": "^4.1.0",
"empower-core": "^0.6.1",
"equal-length": "^1.0.0",
@ -139,7 +109,7 @@
"is-ci": "^1.0.7",
"is-generator-fn": "^1.0.0",
"is-obj": "^1.0.0",
"is-observable": "^0.2.0",
"is-observable": "^1.0.0",
"is-promise": "^2.1.0",
"js-yaml": "^3.8.2",
"last-line-stream": "^1.0.0",
@ -159,47 +129,49 @@
"package-hash": "^2.0.0",
"pkg-conf": "^2.0.0",
"plur": "^2.0.0",
"pretty-ms": "^2.0.0",
"pretty-ms": "^3.0.0",
"require-precompiled": "^0.1.0",
"resolve-cwd": "^2.0.0",
"safe-buffer": "^5.1.1",
"semver": "^5.4.1",
"slash": "^1.0.0",
"source-map-support": "^0.4.0",
"stack-utils": "^1.0.0",
"source-map-support": "^0.5.0",
"stack-utils": "^1.0.1",
"strip-ansi": "^4.0.0",
"strip-bom-buf": "^1.0.0",
"supports-color": "^4.0.0",
"supports-color": "^5.0.0",
"time-require": "^0.1.2",
"trim-off-newlines": "^1.0.1",
"unique-temp-dir": "^1.0.0",
"update-notifier": "^2.1.0"
"update-notifier": "^2.3.0"
},
"devDependencies": {
"cli-table2": "^0.2.0",
"codecov": "^2.1.0",
"codecov": "^3.0.0",
"del": "^3.0.0",
"delay": "^2.0.0",
"execa": "^0.7.0",
"flow-bin": "^0.49.1",
"execa": "^0.8.0",
"flow-bin": "^0.59.0",
"get-stream": "^3.0.0",
"git-branch": "^1.0.0",
"has-ansi": "^3.0.0",
"inquirer": "^3.0.5",
"inquirer": "^4.0.0",
"is-array-sorted": "^1.0.0",
"lolex": "^1.4.0",
"lock-verify": "^1.1.0",
"lolex": "^2.1.2",
"nyc": "^11.0.3",
"proxyquire": "^1.7.4",
"react": "^15.6.1",
"react-test-renderer": "^15.6.1",
"react": "^16.1.1",
"react-test-renderer": "^16.1.1",
"signal-exit": "^3.0.0",
"sinon": "^2.0.0",
"sinon": "^4.1.2",
"source-map-fixtures": "^2.1.0",
"tap": "^10.0.0",
"temp-write": "^3.1.0",
"touch": "^2.0.2",
"touch": "^3.1.0",
"typescript": "^2.2.2",
"xo": "^0.18.2",
"zen-observable": "^0.5.1"
"zen-observable": "^0.6.0"
},
"typings": "types/generated.d.ts",
"xo": {

71
node_modules/ava/readme.md generated vendored
View File

@ -2,7 +2,7 @@
> Futuristic test runner
[![Build Status: Linux](https://travis-ci.org/avajs/ava.svg?branch=master)](https://travis-ci.org/avajs/ava) [![Build status: Windows](https://ci.appveyor.com/api/projects/status/e7v91mu2m5x48ehx/branch/master?svg=true)](https://ci.appveyor.com/project/ava/ava/branch/master) [![Coverage Status](https://coveralls.io/repos/github/avajs/ava/badge.svg?branch=master)](https://coveralls.io/github/avajs/ava?branch=master) [![Dependency Status](https://dependencyci.com/github/avajs/ava/badge)](https://dependencyci.com/github/avajs/ava) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo) [![Gitter](https://badges.gitter.im/join_chat.svg)](https://gitter.im/avajs/ava)
[![Build Status: Linux](https://travis-ci.org/avajs/ava.svg?branch=master)](https://travis-ci.org/avajs/ava) [![Build status: Windows](https://ci.appveyor.com/api/projects/status/e7v91mu2m5x48ehx/branch/master?svg=true)](https://ci.appveyor.com/project/ava/ava/branch/master) [![Coverage Status](https://coveralls.io/repos/github/avajs/ava/badge.svg?branch=master)](https://coveralls.io/github/avajs/ava?branch=master) [![Dependency Status](https://dependencyci.com/github/avajs/ava/badge)](https://dependencyci.com/github/avajs/ava) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo) [![Gitter](https://badges.gitter.im/join_chat.svg)](https://gitter.im/avajs/ava) [![Mentioned in Awesome Node.js](https://awesome.re/mentioned-badge.svg)](https://github.com/sindresorhus/awesome-nodejs)
Even though JavaScript is single-threaded, IO in Node.js can happen in parallel due to its async nature. AVA takes advantage of this and runs your tests concurrently, which is especially beneficial for IO heavy tests. In addition, test files are run in parallel as separate processes, giving you even better performance and an isolated environment for each test file. [Switching](https://github.com/sindresorhus/pageres/commit/663be15acb3dd2eb0f71b1956ef28c2cd3fdeed0) from Mocha to AVA in Pageres brought the test time down from 31 to 11 seconds. Having tests run concurrently forces you to write atomic tests, meaning tests don't depend on global state or the state of other tests, which is a great thing!
@ -69,21 +69,21 @@ test(t => {
### Add AVA to your project
Install AVA globally and run it with `--init` to add AVA to your `package.json`. [Yarn](https://yarnpkg.com/) currently provides significant speed improvements over npm during the installation process. Consider [using Yarn](https://yarnpkg.com/en/docs/install) if the installation is too slow for your needs.
Install AVA globally and run it with `--init` to add AVA to your `package.json`.
```console
$ yarn global add ava
$ ava --init
```
If you prefer using npm:
```console
$ npm install --global ava
$ ava --init
```
If you prefer using Yarn:
```console
$ yarn global add ava
$ ava --init
```
Your `package.json` will then look like this:
```json
@ -105,13 +105,13 @@ Any arguments passed after `--init` are added as config to `package.json`.
You can also install AVA directly:
```console
$ yarn add --dev ava
$ npm install --save-dev ava
```
Alternatively using npm:
Alternatively using Yarn:
```console
$ npm install --save-dev ava
$ yarn add --dev ava
```
You'll have to configure the `test` script in your `package.json` to use `ava` (see above).
@ -169,7 +169,7 @@ $ ava --help
--match, -m Only run tests with matching title (Can be repeated)
--watch, -w Re-run tests when tests and source files change
--timeout, -T Set global timeout
--concurrency, -c Maximum number of test files running at the same time (EXPERIMENTAL)
--concurrency, -c Max number of test files running at the same time (Default: CPU cores)
--update-snapshots, -u Update snapshots
Examples
@ -277,7 +277,20 @@ All of the CLI options can be configured in the `ava` section of your `package.j
Arguments passed to the CLI will always take precedence over the configuration in `package.json`.
See the [ES2017 support](#es2017-support) section for details on the `babel` option.
### Options
- `files`: file & directory paths and glob patterns that select which files AVA will run tests from. Only files with a `.js` extension are used. Files with an underscore prefix are ignored. All `.js` files in selected directories are run
- `source`: files that, when changed, cause tests to be re-run in watch mode. See the [watch mode recipe for details](https://github.com/avajs/ava/blob/master/docs/recipes/watch-mode.md#source-files-and-test-files)
- `match`: not typically useful in the `package.json` configuration, but equivalent to [specifying `--match` on the CLI](#running-tests-with-matching-titles)
- `failFast`: stop running further tests once a test fails
- `failWithoutAssertions`: if `false`, does not fail a test if it doesn't run [assertions](#assertions)
- `tap`: if `true`, enables the [TAP reporter](#tap-reporter)
- `snapshotDir`: specifies a fixed location for storing snapshot files. Use this if your snapshots are ending up in the wrong location
- `powerAssert`: if `false`, disables [power-assert](https://github.com/power-assert-js/power-assert) which otherwise helps provide more descriptive error messages
- `require`: extra modules to require before tests are run. Modules are required in the [worker processes](#process-isolation)
- `babel`: test file specific Babel options. See [ES2017 support](#es2017-support) for more details
Note that providing files on the CLI overrides the `files` option. If you've configured a glob pattern, for instance `test/**/*.test.js`, you may want to repeat it when using the CLI: `ava 'test/integration/*.test.js'`.
## Documentation
@ -400,7 +413,7 @@ test.only('will be run', t => {
});
```
`.only` applies across all test files, so if you use it in one file, no tests from the other file will run.
*Note:* The `.only` modifier applies to the test file it's defined in, so if you run multiple test files, tests in other files will still run. If you want to only run the `test.only` test, provide just that test file to AVA.
### Running tests with matching titles
@ -513,10 +526,12 @@ test.failing('demonstrate some bug', t => {
AVA lets you register hooks that are run before and after your tests. This allows you to run setup and/or teardown code.
`test.before()` registers a hook to be run before the first test in your test file. Similarly `test.after()` registers a hook to be run after the last test. Use `test.after.always()` to register a hook that will **always** run once your tests and other hooks complete. `.always()` hooks run regardless of whether there were earlier failures, so they are ideal for cleanup tasks. There are two exceptions to this however. If you use `--fail-fast` AVA will stop testing as soon as a failure occurs, and it won't run any hooks including the `.always()` hooks. Uncaught exceptions will crash your tests, possibly preventing `.always()` hooks from running.
`test.before()` registers a hook to be run before the first test in your test file. Similarly `test.after()` registers a hook to be run after the last test. Use `test.after.always()` to register a hook that will **always** run once your tests and other hooks complete. `.always()` hooks run regardless of whether there were earlier failures or if all tests were skipped, so they are ideal for cleanup tasks. There are two exceptions to this however. If you use `--fail-fast` AVA will stop testing as soon as a failure occurs, and it won't run any hooks including the `.always()` hooks. Uncaught exceptions will crash your tests, possibly preventing `.always()` hooks from running.
`test.beforeEach()` registers a hook to be run before each test in your test file. Similarly `test.afterEach()` a hook to be run after each test. Use `test.afterEach.always()` to register an after hook that is called even if other test hooks, or the test itself, fail. `.always()` hooks are ideal for cleanup tasks.
If a test is skipped with the `.skip` modifier, the respective `.beforeEach()` and `.afterEach()` hooks are not run. Likewise, if all tests in a test file are skipped `.before()` and `.after()` hooks for the file are not run. Hooks modified with `.always()` will always run, even if all tests are skipped.
**Note**: If the `--fail-fast` flag is specified, AVA will stop after the first test failure and the `.always` hook will **not** run.
Like `test()` these methods take an optional title and a callback function. The title is shown if your hook fails to execute. The callback is called with an [execution object](#t).
@ -875,6 +890,10 @@ Plan how many assertion there are in the test. The test will fail if the actual
End the test. Only works with `test.cb()`.
###### `t.log(message)`
Print a log message contextually alongside the test result instead of immediately printing it to `stdout` like `console.log`.
## Assertions
Assertions are mixed into the [execution object](#t) provided to each test implementation:
@ -975,7 +994,7 @@ Assert that `function` does not throw an error or that `promise` does not reject
Like the `.throws()` assertion, when testing a promise you must wait for the assertion to complete:
```js
test('rejects', async t => {
test('resolves', async t => {
await t.notThrows(promise);
});
```
@ -1041,6 +1060,20 @@ You can then check your code. If the change was intentional you can use the `--u
$ ava --update-snapshots
```
You can specify a fixed location for storing the snapshot files in AVA's [`package.json` configuration](#configuration):
```json
{
"ava": {
"snapshotDir": "custom-directory"
}
}
```
The snapshot files will be saved in a directory structure that mirrors that of your test files.
If you are running AVA against precompiled test files, AVA will try and use source maps to determine the location of the original files. Snapshots will be stored next to these files, following the same rules as if AVA had executed the original files directly. This is great if you're writing your tests in TypeScript (see our [TypeScript recipe](docs/recipes/typescript.md)).
### Skipping assertions
Any assertion can be skipped using the `skip` modifier. Skipped assertions are still counted, so there is no need to change your planned assertion count.
@ -1096,6 +1129,8 @@ t.true(a.test(b) || b === c)
Each test file is run in a separate Node.js process. This allows you to change the global state or overriding a built-in in one test file, without affecting another. It's also great for performance on modern multi-core processors, allowing multiple test files to execute in parallel.
AVA will set `process.env.NODE_ENV` to `test`, unless the `NODE_ENV` environment variable has been set. This is useful if the code you're testing has test defaults (for example when picking what database to connect to, or environment-specific Babel options). It may cause your code or its dependencies to behave differently though. Note that `'NODE_ENV' in process.env` will always be `true`.
## Tips
### Temp files
@ -1178,7 +1213,7 @@ It's the [Andromeda galaxy](https://simple.wikipedia.org/wiki/Andromeda_galaxy).
## Team
[![Sindre Sorhus](https://avatars.githubusercontent.com/u/170270?s=130)](http://sindresorhus.com) | [![Vadim Demedes](https://avatars.githubusercontent.com/u/697676?s=130)](https://github.com/vadimdemedes) | [![James Talmage](https://avatars.githubusercontent.com/u/4082216?s=130)](https://github.com/jamestalmage) | [![Mark Wubben](https://avatars.githubusercontent.com/u/33538?s=130)](https://novemberborn.net) | [![Juan Soto](https://avatars.githubusercontent.com/u/8217766?s=130)](https://juansoto.me) | [![Jeroen Engels](https://avatars.githubusercontent.com/u/3869412?s=130)](https://github.com/jfmengels)
[![Sindre Sorhus](https://github.com/sindresorhus.png?size=100)](https://github.com/sindresorhus) | [![Vadim Demedes](https://github.com/vadimdemedes.png?size=100)](https://github.com/vadimdemedes) | [![James Talmage](https://github.com/jamestalmage.png?size=100)](https://github.com/jamestalmage) | [![Mark Wubben](https://github.com/novemberborn.png?size=100)](https://github.com/novemberborn) | [![Juan Soto](https://github.com/sotojuan.png?size=100)](https://github.com/sotojuan) | [![Jeroen Engels](https://github.com/jfmengels.png?size=100)](https://github.com/jfmengels)
---|---|---|---|---|---
[Sindre Sorhus](http://sindresorhus.com) | [Vadim Demedes](https://github.com/vadimdemedes) | [James Talmage](https://github.com/jamestalmage) | [Mark Wubben](https://novemberborn.net) | [Juan Soto](http://juansoto.me) | [Jeroen Engels](https://github.com/jfmengels)

View File

@ -88,6 +88,10 @@ export interface AssertContext {
ifError(error: any, message?: string): void;
}
export interface TestContext extends AssertContext {
/**
* Test title.
*/
title: string;
/**
* Plan how many assertion there are in the test.
* The test will fail if the actual assertion count doesn't match planned assertions.
@ -95,6 +99,10 @@ export interface TestContext extends AssertContext {
plan(count: number): void;
skip: AssertContext;
/**
* Print a log message contextually alongside the test result instead of immediately printing it to stdout like console.log.
*/
log(message: string): void;
}
export interface CallbackTestContext extends TestContext {
/**

View File

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2014 Evan Wallace
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

@ -1,251 +0,0 @@
# Source Map Support
[![Build Status](https://travis-ci.org/evanw/node-source-map-support.svg?branch=master)](https://travis-ci.org/evanw/node-source-map-support)
This module provides source map support for stack traces in node via the [V8 stack trace API](https://github.com/v8/v8/wiki/Stack-Trace-API). It uses the [source-map](https://github.com/mozilla/source-map) module to replace the paths and line numbers of source-mapped files with their original paths and line numbers. The output mimics node's stack trace format with the goal of making every compile-to-JS language more of a first-class citizen. Source maps are completely general (not specific to any one language) so you can use source maps with multiple compile-to-JS languages in the same node process.
## Installation and Usage
#### Node support
```
$ npm install source-map-support
```
Source maps can be generated using libraries such as [source-map-index-generator](https://github.com/twolfson/source-map-index-generator). Once you have a valid source map, insert the following line at the top of your compiled code:
```js
require('source-map-support').install();
```
And place a source mapping comment somewhere in the file (usually done automatically or with an option by your transpiler):
```
//# sourceMappingURL=path/to/source.map
```
If multiple sourceMappingURL comments exist in one file, the last sourceMappingURL comment will be
respected (e.g. if a file mentions the comment in code, or went through multiple transpilers).
The path should either be absolute or relative to the compiled file.
It is also possible to to install the source map support directly by
requiring the `register` module which can be handy with ES6:
```js
import 'source-map-support/register'
// Instead of:
import sourceMapSupport from 'source-map-support'
sourceMapSupport.install()
```
Note: if you're using babel-register, it includes source-map-support already.
It is also very useful with Mocha:
```
$ mocha --require source-map-support/register tests/
```
#### Browser support
This library also works in Chrome. While the DevTools console already supports source maps, the V8 engine doesn't and `Error.prototype.stack` will be incorrect without this library. Everything will just work if you deploy your source files using [browserify](http://browserify.org/). Just make sure to pass the `--debug` flag to the browserify command so your source maps are included in the bundled code.
This library also works if you use another build process or just include the source files directly. In this case, include the file `browser-source-map-support.js` in your page and call `sourceMapSupport.install()`. It contains the whole library already bundled for the browser using browserify.
```html
<script src="browser-source-map-support.js"></script>
<script>sourceMapSupport.install();</script>
```
This library also works if you use AMD (Asynchronous Module Definition), which is used in tools like [RequireJS](http://requirejs.org/). Just list `browser-source-map-support` as a dependency:
```html
<script>
define(['browser-source-map-support'], function(sourceMapSupport) {
sourceMapSupport.install();
});
</script>
```
## Options
This module installs two things: a change to the `stack` property on `Error` objects and a handler for uncaught exceptions that mimics node's default exception handler (the handler can be seen in the demos below). You may want to disable the handler if you have your own uncaught exception handler. This can be done by passing an argument to the installer:
```js
require('source-map-support').install({
handleUncaughtExceptions: false
});
```
This module loads source maps from the filesystem by default. You can provide alternate loading behavior through a callback as shown below. For example, [Meteor](https://github.com/meteor) keeps all source maps cached in memory to avoid disk access.
```js
require('source-map-support').install({
retrieveSourceMap: function(source) {
if (source === 'compiled.js') {
return {
url: 'original.js',
map: fs.readFileSync('compiled.js.map', 'utf8')
};
}
return null;
}
});
```
The module will by default assume a browser environment if XMLHttpRequest and window are defined. If either of these do not exist it will instead assume a node environment.
In some rare cases, e.g. when running a browser emulation and where both variables are also set, you can explictly specify the environment to be either 'browser' or 'node'.
```js
require('source-map-support').install({
environment: 'node'
});
```
To support files with inline source maps, the `hookRequire` options can be specified, which will monitor all source files for inline source maps.
```js
require('source-map-support').install({
hookRequire: true
});
```
This monkey patches the `require` module loading chain, so is not enabled by default and is not recommended for any sort of production usage.
## Demos
#### Basic Demo
original.js:
```js
throw new Error('test'); // This is the original code
```
compiled.js:
```js
require('source-map-support').install();
throw new Error('test'); // This is the compiled code
// The next line defines the sourceMapping.
//# sourceMappingURL=compiled.js.map
```
compiled.js.map:
```json
{
"version": 3,
"file": "compiled.js",
"sources": ["original.js"],
"names": [],
"mappings": ";;AAAA,MAAM,IAAI"
}
```
Run compiled.js using node (notice how the stack trace uses original.js instead of compiled.js):
```
$ node compiled.js
original.js:1
throw new Error('test'); // This is the original code
^
Error: test
at Object.<anonymous> (original.js:1:7)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
```
#### TypeScript Demo
demo.ts:
```typescript
declare function require(name: string);
require('source-map-support').install();
class Foo {
constructor() { this.bar(); }
bar() { throw new Error('this is a demo'); }
}
new Foo();
```
Compile and run the file using the TypeScript compiler from the terminal:
```
$ npm install source-map-support typescript
$ node_modules/typescript/bin/tsc -sourcemap demo.ts
$ node demo.js
demo.ts:5
bar() { throw new Error('this is a demo'); }
^
Error: this is a demo
at Foo.bar (demo.ts:5:17)
at new Foo (demo.ts:4:24)
at Object.<anonymous> (demo.ts:7:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
```
#### CoffeeScript Demo
demo.coffee:
```coffee
require('source-map-support').install()
foo = ->
bar = -> throw new Error 'this is a demo'
bar()
foo()
```
Compile and run the file using the CoffeeScript compiler from the terminal:
```sh
$ npm install source-map-support coffee-script
$ node_modules/coffee-script/bin/coffee --map --compile demo.coffee
$ node demo.js
demo.coffee:3
bar = -> throw new Error 'this is a demo'
^
Error: this is a demo
at bar (demo.coffee:3:22)
at foo (demo.coffee:4:3)
at Object.<anonymous> (demo.coffee:5:1)
at Object.<anonymous> (demo.coffee:1:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
```
## Tests
This repo contains both automated tests for node and manual tests for the browser. The automated tests can be run using mocha (type `mocha` in the root directory). To run the manual tests:
* Build the tests using `build.js`
* Launch the HTTP server (`npm run serve-tests`) and visit
* http://127.0.0.1:1336/amd-test
* http://127.0.0.1:1336/browser-test
* http://127.0.0.1:1336/browserify-test - **Currently not working** due to a bug with browserify (see [pull request #66](https://github.com/evanw/node-source-map-support/pull/66) for details).
* For `header-test`, run `server.js` inside that directory and visit http://127.0.0.1:1337/
## License
This code is available under the [MIT license](http://opensource.org/licenses/MIT).

View File

@ -1,110 +0,0 @@
/*
* Support for source maps in V8 stack traces
* https://github.com/evanw/node-source-map-support
*/
/*
The buffer module from node.js, for the browser.
@author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
license MIT
*/
(this.define||function(N,O){this.sourceMapSupport=O()})("browser-source-map-support",function(N){(function n(v,m,c){function d(e,a){if(!m[e]){if(!v[e]){var h="function"==typeof require&&require;if(!a&&h)return h(e,!0);if(k)return k(e,!0);throw Error("Cannot find module '"+e+"'");}h=m[e]={exports:{}};v[e][0].call(h.exports,function(a){var c=v[e][1][a];return d(c?c:a)},h,h.exports,n,v,m,c)}return m[e].exports}for(var k="function"==typeof require&&require,q=0;q<c.length;q++)d(c[q]);return d})({1:[function(n,
v,m){N=n("./source-map-support")},{"./source-map-support":19}],2:[function(n,v,m){(function(c){function d(c){c=c.charCodeAt(0);if(43===c||45===c)return 62;if(47===c||95===c)return 63;if(48>c)return-1;if(58>c)return c-48+52;if(91>c)return c-65;if(123>c)return c-97+26}var k="undefined"!==typeof Uint8Array?Uint8Array:Array;c.toByteArray=function(c){function e(a){u[b++]=a}if(0<c.length%4)throw Error("Invalid string. Length must be a multiple of 4");var a=c.length;var h="="===c.charAt(a-2)?2:"="===c.charAt(a-
1)?1:0;var u=new k(3*c.length/4-h);var r=0<h?c.length-4:c.length;var b=0;for(a=0;a<r;a+=4){var f=d(c.charAt(a))<<18|d(c.charAt(a+1))<<12|d(c.charAt(a+2))<<6|d(c.charAt(a+3));e((f&16711680)>>16);e((f&65280)>>8);e(f&255)}2===h?(f=d(c.charAt(a))<<2|d(c.charAt(a+1))>>4,e(f&255)):1===h&&(f=d(c.charAt(a))<<10|d(c.charAt(a+1))<<4|d(c.charAt(a+2))>>2,e(f>>8&255),e(f&255));return u};c.fromByteArray=function(c){var e=c.length%3,a="",h;var d=0;for(h=c.length-e;d<h;d+=3){var r=(c[d]<<16)+(c[d+1]<<8)+c[d+2];r=
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>18&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>12&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>6&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r&63);a+=r}switch(e){case 1:r=c[c.length-1];a+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>2);a+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<
4&63);a+="==";break;case 2:r=(c[c.length-2]<<8)+c[c.length-1],a+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>10),a+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>4&63),a+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<2&63),a+="="}return a}})("undefined"===typeof m?this.base64js={}:m)},{}],3:[function(n,v,m){},{}],4:[function(n,v,m){function c(g,l,b){if(!(this instanceof c))return new c(g,l,b);var x=typeof g;
if("base64"===l&&"string"===x)for(g=g.trim?g.trim():g.replace(/^\s+|\s+$/g,"");0!==g.length%4;)g+="=";if("number"===x)var a=B(g);else if("string"===x)a=c.byteLength(g,l);else if("object"===x)a=B(g.length);else throw Error("First argument needs to be a number, array or string.");if(c._useTypedArrays)var f=c._augment(new Uint8Array(a));else f=this,f.length=a,f._isBuffer=!0;if(c._useTypedArrays&&"number"===typeof g.byteLength)f._set(g);else{var e=g;if(L(e)||c.isBuffer(e)||e&&"object"===typeof e&&"number"===
typeof e.length)for(l=0;l<a;l++)c.isBuffer(g)?f[l]=g.readUInt8(l):f[l]=g[l];else if("string"===x)f.write(g,0,l);else if("number"===x&&!c._useTypedArrays&&!b)for(l=0;l<a;l++)f[l]=0}return f}function d(g,l,b){var x="";for(b=Math.min(g.length,b);l<b;l++)x+=String.fromCharCode(g[l]);return x}function k(g,l,b,a){a||(p("boolean"===typeof b,"missing or invalid endian"),p(void 0!==l&&null!==l,"missing offset"),p(l+1<g.length,"Trying to read beyond buffer length"));a=g.length;if(!(l>=a))return b?(b=g[l],l+
1<a&&(b|=g[l+1]<<8)):(b=g[l]<<8,l+1<a&&(b|=g[l+1])),b}function q(g,l,b,a){a||(p("boolean"===typeof b,"missing or invalid endian"),p(void 0!==l&&null!==l,"missing offset"),p(l+3<g.length,"Trying to read beyond buffer length"));a=g.length;if(!(l>=a)){var x;b?(l+2<a&&(x=g[l+2]<<16),l+1<a&&(x|=g[l+1]<<8),x|=g[l],l+3<a&&(x+=g[l+3]<<24>>>0)):(l+1<a&&(x=g[l+1]<<16),l+2<a&&(x|=g[l+2]<<8),l+3<a&&(x|=g[l+3]),x+=g[l]<<24>>>0);return x}}function e(g,l,b,a){a||(p("boolean"===typeof b,"missing or invalid endian"),
p(void 0!==l&&null!==l,"missing offset"),p(l+1<g.length,"Trying to read beyond buffer length"));if(!(l>=g.length))return g=k(g,l,b,!0),g&32768?-1*(65535-g+1):g}function a(g,l,b,a){a||(p("boolean"===typeof b,"missing or invalid endian"),p(void 0!==l&&null!==l,"missing offset"),p(l+3<g.length,"Trying to read beyond buffer length"));if(!(l>=g.length))return g=q(g,l,b,!0),g&2147483648?-1*(4294967295-g+1):g}function h(g,l,b,a){a||(p("boolean"===typeof b,"missing or invalid endian"),p(l+3<g.length,"Trying to read beyond buffer length"));
return J.read(g,l,b,23,4)}function u(g,l,b,a){a||(p("boolean"===typeof b,"missing or invalid endian"),p(l+7<g.length,"Trying to read beyond buffer length"));return J.read(g,l,b,52,8)}function r(g,l,b,a,c){c||(p(void 0!==l&&null!==l,"missing value"),p("boolean"===typeof a,"missing or invalid endian"),p(void 0!==b&&null!==b,"missing offset"),p(b+1<g.length,"trying to write beyond buffer length"),H(l,65535));var x=g.length;if(!(b>=x))for(c=0,x=Math.min(x-b,2);c<x;c++)g[b+c]=(l&255<<8*(a?c:1-c))>>>8*
(a?c:1-c)}function b(g,l,b,a,c){c||(p(void 0!==l&&null!==l,"missing value"),p("boolean"===typeof a,"missing or invalid endian"),p(void 0!==b&&null!==b,"missing offset"),p(b+3<g.length,"trying to write beyond buffer length"),H(l,4294967295));var x=g.length;if(!(b>=x))for(c=0,x=Math.min(x-b,4);c<x;c++)g[b+c]=l>>>8*(a?c:3-c)&255}function f(g,l,b,a,c){c||(p(void 0!==l&&null!==l,"missing value"),p("boolean"===typeof a,"missing or invalid endian"),p(void 0!==b&&null!==b,"missing offset"),p(b+1<g.length,
"Trying to write beyond buffer length"),z(l,32767,-32768));b>=g.length||(0<=l?r(g,l,b,a,c):r(g,65535+l+1,b,a,c))}function G(g,l,a,c,f){f||(p(void 0!==l&&null!==l,"missing value"),p("boolean"===typeof c,"missing or invalid endian"),p(void 0!==a&&null!==a,"missing offset"),p(a+3<g.length,"Trying to write beyond buffer length"),z(l,2147483647,-2147483648));a>=g.length||(0<=l?b(g,l,a,c,f):b(g,4294967295+l+1,a,c,f))}function t(g,b,a,c,f){f||(p(void 0!==b&&null!==b,"missing value"),p("boolean"===typeof c,
"missing or invalid endian"),p(void 0!==a&&null!==a,"missing offset"),p(a+3<g.length,"Trying to write beyond buffer length"),E(b,3.4028234663852886E38,-3.4028234663852886E38));a>=g.length||J.write(g,b,a,c,23,4)}function M(g,b,a,c,f){f||(p(void 0!==b&&null!==b,"missing value"),p("boolean"===typeof c,"missing or invalid endian"),p(void 0!==a&&null!==a,"missing offset"),p(a+7<g.length,"Trying to write beyond buffer length"),E(b,1.7976931348623157E308,-1.7976931348623157E308));a>=g.length||J.write(g,
b,a,c,52,8)}function I(g,b,a){if("number"!==typeof g)return a;g=~~g;if(g>=b)return b;if(0<=g)return g;g+=b;return 0<=g?g:0}function B(g){g=~~Math.ceil(+g);return 0>g?0:g}function L(g){return(Array.isArray||function(g){return"[object Array]"===Object.prototype.toString.call(g)})(g)}function C(g){return 16>g?"0"+g.toString(16):g.toString(16)}function y(g){for(var b=[],a=0;a<g.length;a++){var c=g.charCodeAt(a);if(127>=c)b.push(g.charCodeAt(a));else{var f=a;55296<=c&&57343>=c&&a++;c=encodeURIComponent(g.slice(f,
a+1)).substr(1).split("%");for(f=0;f<c.length;f++)b.push(parseInt(c[f],16))}}return b}function K(g){for(var b=[],a=0;a<g.length;a++)b.push(g.charCodeAt(a)&255);return b}function A(g,b,a,c){for(var l=0;l<c&&!(l+a>=b.length||l>=g.length);l++)b[l+a]=g[l];return l}function F(g){try{return decodeURIComponent(g)}catch(l){return String.fromCharCode(65533)}}function H(g,b){p("number"===typeof g,"cannot write a non-number as a number");p(0<=g,"specified a negative value for writing an unsigned value");p(g<=
b,"value is larger than maximum value for type");p(Math.floor(g)===g,"value has a fractional component")}function z(g,b,a){p("number"===typeof g,"cannot write a non-number as a number");p(g<=b,"value larger than maximum allowed value");p(g>=a,"value smaller than minimum allowed value");p(Math.floor(g)===g,"value has a fractional component")}function E(g,b,a){p("number"===typeof g,"cannot write a non-number as a number");p(g<=b,"value larger than maximum allowed value");p(g>=a,"value smaller than minimum allowed value")}
function p(g,b){if(!g)throw Error(b||"Failed assertion");}var D=n("base64-js"),J=n("ieee754");m.Buffer=c;m.SlowBuffer=c;m.INSPECT_MAX_BYTES=50;c.poolSize=8192;c._useTypedArrays=function(){try{var g=new ArrayBuffer(0),b=new Uint8Array(g);b.foo=function(){return 42};return 42===b.foo()&&"function"===typeof b.subarray}catch(x){return!1}}();c.isEncoding=function(g){switch(String(g).toLowerCase()){case "hex":case "utf8":case "utf-8":case "ascii":case "binary":case "base64":case "raw":case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return!0;
default:return!1}};c.isBuffer=function(g){return!(null===g||void 0===g||!g._isBuffer)};c.byteLength=function(g,b){g+="";switch(b||"utf8"){case "hex":var a=g.length/2;break;case "utf8":case "utf-8":a=y(g).length;break;case "ascii":case "binary":case "raw":a=g.length;break;case "base64":a=D.toByteArray(g).length;break;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":a=2*g.length;break;default:throw Error("Unknown encoding");}return a};c.concat=function(g,b){p(L(g),"Usage: Buffer.concat(list, [totalLength])\nlist should be an Array.");
if(0===g.length)return new c(0);if(1===g.length)return g[0];var a;if("number"!==typeof b)for(a=b=0;a<g.length;a++)b+=g[a].length;var l=new c(b),f=0;for(a=0;a<g.length;a++){var e=g[a];e.copy(l,f);f+=e.length}return l};c.prototype.write=function(g,b,a,f){if(isFinite(b))isFinite(a)||(f=a,a=void 0);else{var l=f;f=b;b=a;a=l}b=Number(b)||0;l=this.length-b;a?(a=Number(a),a>l&&(a=l)):a=l;f=String(f||"utf8").toLowerCase();switch(f){case "hex":b=Number(b)||0;f=this.length-b;a?(a=Number(a),a>f&&(a=f)):a=f;f=
g.length;p(0===f%2,"Invalid hex string");a>f/2&&(a=f/2);for(f=0;f<a;f++)l=parseInt(g.substr(2*f,2),16),p(!isNaN(l),"Invalid hex string"),this[b+f]=l;c._charsWritten=2*f;g=f;break;case "utf8":case "utf-8":g=c._charsWritten=A(y(g),this,b,a);break;case "ascii":g=c._charsWritten=A(K(g),this,b,a);break;case "binary":g=c._charsWritten=A(K(g),this,b,a);break;case "base64":g=c._charsWritten=A(D.toByteArray(g),this,b,a);break;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":l=[];for(var e=0;e<g.length;e++){var h=
g.charCodeAt(e);f=h>>8;h%=256;l.push(h);l.push(f)}g=c._charsWritten=A(l,this,b,a);break;default:throw Error("Unknown encoding");}return g};c.prototype.toString=function(g,b,a){g=String(g||"utf8").toLowerCase();b=Number(b)||0;a=void 0!==a?Number(a):a=this.length;if(a===b)return"";switch(g){case "hex":g=this.length;if(!b||0>b)b=0;if(!a||0>a||a>g)a=g;for(g="";b<a;b++)g+=C(this[b]);a=g;break;case "utf8":case "utf-8":var c=g="";for(a=Math.min(this.length,a);b<a;b++)127>=this[b]?(g+=F(c)+String.fromCharCode(this[b]),
c=""):c+="%"+this[b].toString(16);a=g+F(c);break;case "ascii":a=d(this,b,a);break;case "binary":a=d(this,b,a);break;case "base64":a=0===b&&a===this.length?D.fromByteArray(this):D.fromByteArray(this.slice(b,a));break;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":a=this.slice(b,a);b="";for(g=0;g<a.length;g+=2)b+=String.fromCharCode(a[g]+256*a[g+1]);a=b;break;default:throw Error("Unknown encoding");}return a};c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||
this,0)}};c.prototype.copy=function(g,b,a,f){a||(a=0);f||0===f||(f=this.length);b||(b=0);if(f!==a&&0!==g.length&&0!==this.length)if(p(f>=a,"sourceEnd < sourceStart"),p(0<=b&&b<g.length,"targetStart out of bounds"),p(0<=a&&a<this.length,"sourceStart out of bounds"),p(0<=f&&f<=this.length,"sourceEnd out of bounds"),f>this.length&&(f=this.length),g.length-b<f-a&&(f=g.length-b+a),f-=a,100>f||!c._useTypedArrays)for(var l=0;l<f;l++)g[l+b]=this[l+a];else g._set(this.subarray(a,a+f),b)};c.prototype.slice=
function(b,a){var g=this.length;b=I(b,g,0);a=I(a,g,g);if(c._useTypedArrays)return c._augment(this.subarray(b,a));g=a-b;for(var f=new c(g,void 0,!0),l=0;l<g;l++)f[l]=this[l+b];return f};c.prototype.get=function(b){console.log(".get() is deprecated. Access using array indexes instead.");return this.readUInt8(b)};c.prototype.set=function(b,a){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(b,a)};c.prototype.readUInt8=function(b,a){a||(p(void 0!==b&&null!==
b,"missing offset"),p(b<this.length,"Trying to read beyond buffer length"));if(!(b>=this.length))return this[b]};c.prototype.readUInt16LE=function(b,a){return k(this,b,!0,a)};c.prototype.readUInt16BE=function(b,a){return k(this,b,!1,a)};c.prototype.readUInt32LE=function(b,a){return q(this,b,!0,a)};c.prototype.readUInt32BE=function(b,a){return q(this,b,!1,a)};c.prototype.readInt8=function(b,a){a||(p(void 0!==b&&null!==b,"missing offset"),p(b<this.length,"Trying to read beyond buffer length"));if(!(b>=
this.length))return this[b]&128?-1*(255-this[b]+1):this[b]};c.prototype.readInt16LE=function(b,a){return e(this,b,!0,a)};c.prototype.readInt16BE=function(b,a){return e(this,b,!1,a)};c.prototype.readInt32LE=function(b,f){return a(this,b,!0,f)};c.prototype.readInt32BE=function(b,f){return a(this,b,!1,f)};c.prototype.readFloatLE=function(b,a){return h(this,b,!0,a)};c.prototype.readFloatBE=function(b,a){return h(this,b,!1,a)};c.prototype.readDoubleLE=function(b,a){return u(this,b,!0,a)};c.prototype.readDoubleBE=
function(b,a){return u(this,b,!1,a)};c.prototype.writeUInt8=function(b,a,f){f||(p(void 0!==b&&null!==b,"missing value"),p(void 0!==a&&null!==a,"missing offset"),p(a<this.length,"trying to write beyond buffer length"),H(b,255));a>=this.length||(this[a]=b)};c.prototype.writeUInt16LE=function(b,a,f){r(this,b,a,!0,f)};c.prototype.writeUInt16BE=function(b,a,f){r(this,b,a,!1,f)};c.prototype.writeUInt32LE=function(a,f,c){b(this,a,f,!0,c)};c.prototype.writeUInt32BE=function(a,f,c){b(this,a,f,!1,c)};c.prototype.writeInt8=
function(b,a,f){f||(p(void 0!==b&&null!==b,"missing value"),p(void 0!==a&&null!==a,"missing offset"),p(a<this.length,"Trying to write beyond buffer length"),z(b,127,-128));a>=this.length||(0<=b?this.writeUInt8(b,a,f):this.writeUInt8(255+b+1,a,f))};c.prototype.writeInt16LE=function(b,a,c){f(this,b,a,!0,c)};c.prototype.writeInt16BE=function(b,a,c){f(this,b,a,!1,c)};c.prototype.writeInt32LE=function(b,a,f){G(this,b,a,!0,f)};c.prototype.writeInt32BE=function(b,a,f){G(this,b,a,!1,f)};c.prototype.writeFloatLE=
function(b,a,f){t(this,b,a,!0,f)};c.prototype.writeFloatBE=function(b,a,f){t(this,b,a,!1,f)};c.prototype.writeDoubleLE=function(b,a,f){M(this,b,a,!0,f)};c.prototype.writeDoubleBE=function(b,a,f){M(this,b,a,!1,f)};c.prototype.fill=function(b,a,f){b||(b=0);a||(a=0);f||(f=this.length);"string"===typeof b&&(b=b.charCodeAt(0));p("number"===typeof b&&!isNaN(b),"value is not a number");p(f>=a,"end < start");if(f!==a&&0!==this.length)for(p(0<=a&&a<this.length,"start out of bounds"),p(0<=f&&f<=this.length,
"end out of bounds");a<f;a++)this[a]=b};c.prototype.inspect=function(){for(var b=[],a=this.length,f=0;f<a;f++)if(b[f]=C(this[f]),f===m.INSPECT_MAX_BYTES){b[f+1]="...";break}return"<Buffer "+b.join(" ")+">"};c.prototype.toArrayBuffer=function(){if("undefined"!==typeof Uint8Array){if(c._useTypedArrays)return(new c(this)).buffer;for(var b=new Uint8Array(this.length),a=0,f=b.length;a<f;a+=1)b[a]=this[a];return b.buffer}throw Error("Buffer.toArrayBuffer not supported in this browser");};var w=c.prototype;
c._augment=function(b){b._isBuffer=!0;b._get=b.get;b._set=b.set;b.get=w.get;b.set=w.set;b.write=w.write;b.toString=w.toString;b.toLocaleString=w.toString;b.toJSON=w.toJSON;b.copy=w.copy;b.slice=w.slice;b.readUInt8=w.readUInt8;b.readUInt16LE=w.readUInt16LE;b.readUInt16BE=w.readUInt16BE;b.readUInt32LE=w.readUInt32LE;b.readUInt32BE=w.readUInt32BE;b.readInt8=w.readInt8;b.readInt16LE=w.readInt16LE;b.readInt16BE=w.readInt16BE;b.readInt32LE=w.readInt32LE;b.readInt32BE=w.readInt32BE;b.readFloatLE=w.readFloatLE;
b.readFloatBE=w.readFloatBE;b.readDoubleLE=w.readDoubleLE;b.readDoubleBE=w.readDoubleBE;b.writeUInt8=w.writeUInt8;b.writeUInt16LE=w.writeUInt16LE;b.writeUInt16BE=w.writeUInt16BE;b.writeUInt32LE=w.writeUInt32LE;b.writeUInt32BE=w.writeUInt32BE;b.writeInt8=w.writeInt8;b.writeInt16LE=w.writeInt16LE;b.writeInt16BE=w.writeInt16BE;b.writeInt32LE=w.writeInt32LE;b.writeInt32BE=w.writeInt32BE;b.writeFloatLE=w.writeFloatLE;b.writeFloatBE=w.writeFloatBE;b.writeDoubleLE=w.writeDoubleLE;b.writeDoubleBE=w.writeDoubleBE;
b.fill=w.fill;b.inspect=w.inspect;b.toArrayBuffer=w.toArrayBuffer;return b}},{"base64-js":2,ieee754:5}],5:[function(n,v,m){m.read=function(c,d,k,q,e){var a=8*e-q-1;var h=(1<<a)-1,u=h>>1,r=-7;e=k?e-1:0;var b=k?-1:1,f=c[d+e];e+=b;k=f&(1<<-r)-1;f>>=-r;for(r+=a;0<r;k=256*k+c[d+e],e+=b,r-=8);a=k&(1<<-r)-1;k>>=-r;for(r+=q;0<r;a=256*a+c[d+e],e+=b,r-=8);if(0===k)k=1-u;else{if(k===h)return a?NaN:Infinity*(f?-1:1);a+=Math.pow(2,q);k-=u}return(f?-1:1)*a*Math.pow(2,k-q)};m.write=function(c,d,k,q,e,a){var h,u=
8*a-e-1,r=(1<<u)-1,b=r>>1,f=23===e?Math.pow(2,-24)-Math.pow(2,-77):0;a=q?0:a-1;var G=q?1:-1,t=0>d||0===d&&0>1/d?1:0;d=Math.abs(d);isNaN(d)||Infinity===d?(d=isNaN(d)?1:0,q=r):(q=Math.floor(Math.log(d)/Math.LN2),1>d*(h=Math.pow(2,-q))&&(q--,h*=2),d=1<=q+b?d+f/h:d+f*Math.pow(2,1-b),2<=d*h&&(q++,h/=2),q+b>=r?(d=0,q=r):1<=q+b?(d=(d*h-1)*Math.pow(2,e),q+=b):(d=d*Math.pow(2,b-1)*Math.pow(2,e),q=0));for(;8<=e;c[k+a]=d&255,a+=G,d/=256,e-=8);q=q<<e|d;for(u+=e;0<u;c[k+a]=q&255,a+=G,q/=256,u-=8);c[k+a-G]|=128*
t}},{}],6:[function(n,v,m){(function(c){function d(a,c){for(var e=0,h=a.length-1;0<=h;h--){var b=a[h];"."===b?a.splice(h,1):".."===b?(a.splice(h,1),e++):e&&(a.splice(h,1),e--)}if(c)for(;e--;e)a.unshift("..");return a}function k(a,c){if(a.filter)return a.filter(c);for(var e=[],h=0;h<a.length;h++)c(a[h],h,a)&&e.push(a[h]);return e}var q=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;m.resolve=function(){for(var a="",e=!1,u=arguments.length-1;-1<=u&&!e;u--){var r=0<=u?arguments[u]:c.cwd();
if("string"!==typeof r)throw new TypeError("Arguments to path.resolve must be strings");r&&(a=r+"/"+a,e="/"===r.charAt(0))}a=d(k(a.split("/"),function(b){return!!b}),!e).join("/");return(e?"/":"")+a||"."};m.normalize=function(a){var c=m.isAbsolute(a),u="/"===e(a,-1);(a=d(k(a.split("/"),function(a){return!!a}),!c).join("/"))||c||(a=".");a&&u&&(a+="/");return(c?"/":"")+a};m.isAbsolute=function(a){return"/"===a.charAt(0)};m.join=function(){var a=Array.prototype.slice.call(arguments,0);return m.normalize(k(a,
function(a,c){if("string"!==typeof a)throw new TypeError("Arguments to path.join must be strings");return a}).join("/"))};m.relative=function(a,c){function e(b){for(var a=0;a<b.length&&""===b[a];a++);for(var f=b.length-1;0<=f&&""===b[f];f--);return a>f?[]:b.slice(a,f-a+1)}a=m.resolve(a).substr(1);c=m.resolve(c).substr(1);for(var h=e(a.split("/")),b=e(c.split("/")),f=Math.min(h.length,b.length),G=f,t=0;t<f;t++)if(h[t]!==b[t]){G=t;break}f=[];for(t=G;t<h.length;t++)f.push("..");f=f.concat(b.slice(G));
return f.join("/")};m.sep="/";m.delimiter=":";m.dirname=function(a){var c=q.exec(a).slice(1);a=c[0];c=c[1];if(!a&&!c)return".";c&&(c=c.substr(0,c.length-1));return a+c};m.basename=function(a,c){var e=q.exec(a).slice(1)[2];c&&e.substr(-1*c.length)===c&&(e=e.substr(0,e.length-c.length));return e};m.extname=function(a){return q.exec(a).slice(1)[3]};var e="b"==="ab".substr(-1)?function(a,c,e){return a.substr(c,e)}:function(a,c,e){0>c&&(c=a.length+c);return a.substr(c,e)}}).call(this,n("node_modules/process/browser.js"))},
{"node_modules/process/browser.js":7}],7:[function(n,v,m){function c(){}n=v.exports={};n.nextTick=function(){if("undefined"!==typeof window&&window.setImmediate)return function(c){return window.setImmediate(c)};if("undefined"!==typeof window&&window.postMessage&&window.addEventListener){var c=[];window.addEventListener("message",function(d){var k=d.source;k!==window&&null!==k||"process-tick"!==d.data||(d.stopPropagation(),0<c.length&&c.shift()())},!0);return function(d){c.push(d);window.postMessage("process-tick",
"*")}}return function(c){setTimeout(c,0)}}();n.title="browser";n.browser=!0;n.env={};n.argv=[];n.on=c;n.once=c;n.off=c;n.emit=c;n.binding=function(c){throw Error("process.binding is not supported");};n.cwd=function(){return"/"};n.chdir=function(c){throw Error("process.chdir is not supported");}},{}],8:[function(n,v,m){function c(){this._array=[];this._set=Object.create(null)}var d=n("./util"),k=Object.prototype.hasOwnProperty;c.fromArray=function(d,e){for(var a=new c,h=0,k=d.length;h<k;h++)a.add(d[h],
e);return a};c.prototype.size=function(){return Object.getOwnPropertyNames(this._set).length};c.prototype.add=function(c,e){var a=d.toSetString(c),h=k.call(this._set,a),u=this._array.length;h&&!e||this._array.push(c);h||(this._set[a]=u)};c.prototype.has=function(c){c=d.toSetString(c);return k.call(this._set,c)};c.prototype.indexOf=function(c){var e=d.toSetString(c);if(k.call(this._set,e))return this._set[e];throw Error('"'+c+'" is not in the set.');};c.prototype.at=function(c){if(0<=c&&c<this._array.length)return this._array[c];
throw Error("No element indexed by "+c);};c.prototype.toArray=function(){return this._array.slice()};m.ArraySet=c},{"./util":17}],9:[function(n,v,m){var c=n("./base64");m.encode=function(d){var k="",q=0>d?(-d<<1)+1:(d<<1)+0;do d=q&31,q>>>=5,0<q&&(d|=32),k+=c.encode(d);while(0<q);return k};m.decode=function(d,k,q){var e=d.length,a=0,h=0;do{if(k>=e)throw Error("Expected more digits in base 64 VLQ value.");var u=c.decode(d.charCodeAt(k++));if(-1===u)throw Error("Invalid base64 digit: "+d.charAt(k-1));
var r=!!(u&32);u&=31;a+=u<<h;h+=5}while(r);d=a>>1;q.value=1===(a&1)?-d:d;q.rest=k}},{"./base64":10}],10:[function(n,v,m){var c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");m.encode=function(d){if(0<=d&&d<c.length)return c[d];throw new TypeError("Must be between 0 and 63: "+d);};m.decode=function(c){return 65<=c&&90>=c?c-65:97<=c&&122>=c?c-97+26:48<=c&&57>=c?c-48+52:43==c?62:47==c?63:-1}},{}],11:[function(n,v,m){function c(d,k,q,e,a,h){var u=Math.floor((k-d)/2)+d,r=
a(q,e[u],!0);return 0===r?u:0<r?1<k-u?c(u,k,q,e,a,h):h==m.LEAST_UPPER_BOUND?k<e.length?k:-1:u:1<u-d?c(d,u,q,e,a,h):h==m.LEAST_UPPER_BOUND?u:0>d?-1:d}m.GREATEST_LOWER_BOUND=1;m.LEAST_UPPER_BOUND=2;m.search=function(d,k,q,e){if(0===k.length)return-1;d=c(-1,k.length,d,k,q,e||m.GREATEST_LOWER_BOUND);if(0>d)return-1;for(;0<=d-1&&0===q(k[d],k[d-1],!0);)--d;return d}},{}],12:[function(n,v,m){function c(){this._array=[];this._sorted=!0;this._last={generatedLine:-1,generatedColumn:0}}var d=n("./util");c.prototype.unsortedForEach=
function(c,d){this._array.forEach(c,d)};c.prototype.add=function(c){var k=this._last,e=k.generatedLine,a=c.generatedLine,h=k.generatedColumn,u=c.generatedColumn;a>e||a==e&&u>=h||0>=d.compareByGeneratedPositionsInflated(k,c)?this._last=c:this._sorted=!1;this._array.push(c)};c.prototype.toArray=function(){this._sorted||(this._array.sort(d.compareByGeneratedPositionsInflated),this._sorted=!0);return this._array};m.MappingList=c},{"./util":17}],13:[function(n,v,m){function c(c,d,e){var a=c[d];c[d]=c[e];
c[e]=a}function d(k,m,e,a){if(e<a){var h=e-1;c(k,Math.round(e+Math.random()*(a-e)),a);for(var u=k[a],r=e;r<a;r++)0>=m(k[r],u)&&(h+=1,c(k,h,r));c(k,h+1,r);h+=1;d(k,m,e,h-1);d(k,m,h+1,a)}}m.quickSort=function(c,m){d(c,m,0,c.length-1)}},{}],14:[function(n,v,m){function c(b){var a=b;"string"===typeof b&&(a=JSON.parse(b.replace(/^\)\]\}'/,"")));return null!=a.sections?new q(a):new d(a)}function d(b){var a=b;"string"===typeof b&&(a=JSON.parse(b.replace(/^\)\]\}'/,"")));b=e.getArg(a,"version");var c=e.getArg(a,
"sources"),t=e.getArg(a,"names",[]),d=e.getArg(a,"sourceRoot",null),r=e.getArg(a,"sourcesContent",null),k=e.getArg(a,"mappings");a=e.getArg(a,"file",null);if(b!=this._version)throw Error("Unsupported version: "+b);c=c.map(String).map(e.normalize).map(function(b){return d&&e.isAbsolute(d)&&e.isAbsolute(b)?e.relative(d,b):b});this._names=h.fromArray(t.map(String),!0);this._sources=h.fromArray(c,!0);this.sourceRoot=d;this.sourcesContent=r;this._mappings=k;this.file=a}function k(){this.generatedColumn=
this.generatedLine=0;this.name=this.originalColumn=this.originalLine=this.source=null}function q(b){var a=b;"string"===typeof b&&(a=JSON.parse(b.replace(/^\)\]\}'/,"")));b=e.getArg(a,"version");a=e.getArg(a,"sections");if(b!=this._version)throw Error("Unsupported version: "+b);this._sources=new h;this._names=new h;var d={line:-1,column:0};this._sections=a.map(function(b){if(b.url)throw Error("Support for url field in sections not implemented.");var a=e.getArg(b,"offset"),f=e.getArg(a,"line"),t=e.getArg(a,
"column");if(f<d.line||f===d.line&&t<d.column)throw Error("Section offsets must be ordered and non-overlapping.");d=a;return{generatedOffset:{generatedLine:f+1,generatedColumn:t+1},consumer:new c(e.getArg(b,"map"))}})}var e=n("./util"),a=n("./binary-search"),h=n("./array-set").ArraySet,u=n("./base64-vlq"),r=n("./quick-sort").quickSort;c.fromSourceMap=function(b){return d.fromSourceMap(b)};c.prototype._version=3;c.prototype.__generatedMappings=null;Object.defineProperty(c.prototype,"_generatedMappings",
{get:function(){this.__generatedMappings||this._parseMappings(this._mappings,this.sourceRoot);return this.__generatedMappings}});c.prototype.__originalMappings=null;Object.defineProperty(c.prototype,"_originalMappings",{get:function(){this.__originalMappings||this._parseMappings(this._mappings,this.sourceRoot);return this.__originalMappings}});c.prototype._charIsMappingSeparator=function(b,a){var c=b.charAt(a);return";"===c||","===c};c.prototype._parseMappings=function(b,a){throw Error("Subclasses must implement _parseMappings");
};c.GENERATED_ORDER=1;c.ORIGINAL_ORDER=2;c.GREATEST_LOWER_BOUND=1;c.LEAST_UPPER_BOUND=2;c.prototype.eachMapping=function(b,a,d){a=a||null;switch(d||c.GENERATED_ORDER){case c.GENERATED_ORDER:d=this._generatedMappings;break;case c.ORIGINAL_ORDER:d=this._originalMappings;break;default:throw Error("Unknown order of iteration.");}var f=this.sourceRoot;d.map(function(b){var a=null===b.source?null:this._sources.at(b.source);null!=a&&null!=f&&(a=e.join(f,a));return{source:a,generatedLine:b.generatedLine,
generatedColumn:b.generatedColumn,originalLine:b.originalLine,originalColumn:b.originalColumn,name:null===b.name?null:this._names.at(b.name)}},this).forEach(b,a)};c.prototype.allGeneratedPositionsFor=function(b){var c=e.getArg(b,"line"),d={source:e.getArg(b,"source"),originalLine:c,originalColumn:e.getArg(b,"column",0)};null!=this.sourceRoot&&(d.source=e.relative(this.sourceRoot,d.source));if(!this._sources.has(d.source))return[];d.source=this._sources.indexOf(d.source);var t=[];d=this._findMapping(d,
this._originalMappings,"originalLine","originalColumn",e.compareByOriginalPositions,a.LEAST_UPPER_BOUND);if(0<=d){var h=this._originalMappings[d];if(void 0===b.column)for(c=h.originalLine;h&&h.originalLine===c;)t.push({line:e.getArg(h,"generatedLine",null),column:e.getArg(h,"generatedColumn",null),lastColumn:e.getArg(h,"lastGeneratedColumn",null)}),h=this._originalMappings[++d];else for(b=h.originalColumn;h&&h.originalLine===c&&h.originalColumn==b;)t.push({line:e.getArg(h,"generatedLine",null),column:e.getArg(h,
"generatedColumn",null),lastColumn:e.getArg(h,"lastGeneratedColumn",null)}),h=this._originalMappings[++d]}return t};m.SourceMapConsumer=c;d.prototype=Object.create(c.prototype);d.prototype.consumer=c;d.fromSourceMap=function(b){var a=Object.create(d.prototype),c=a._names=h.fromArray(b._names.toArray(),!0),t=a._sources=h.fromArray(b._sources.toArray(),!0);a.sourceRoot=b._sourceRoot;a.sourcesContent=b._generateSourcesContent(a._sources.toArray(),a.sourceRoot);a.file=b._file;b=b._mappings.toArray().slice();
for(var u=a.__generatedMappings=[],m=a.__originalMappings=[],q=0,n=b.length;q<n;q++){var C=b[q],y=new k;y.generatedLine=C.generatedLine;y.generatedColumn=C.generatedColumn;C.source&&(y.source=t.indexOf(C.source),y.originalLine=C.originalLine,y.originalColumn=C.originalColumn,C.name&&(y.name=c.indexOf(C.name)),m.push(y));u.push(y)}r(a.__originalMappings,e.compareByOriginalPositions);return a};d.prototype._version=3;Object.defineProperty(d.prototype,"sources",{get:function(){return this._sources.toArray().map(function(b){return null!=
this.sourceRoot?e.join(this.sourceRoot,b):b},this)}});d.prototype._parseMappings=function(b,a){for(var c=1,f=0,d=0,h=0,m=0,q=0,n=b.length,y=0,v={},A={},F=[],H=[],z,E,p,D,J;y<n;)if(";"===b.charAt(y))c++,y++,f=0;else if(","===b.charAt(y))y++;else{z=new k;z.generatedLine=c;for(D=y;D<n&&!this._charIsMappingSeparator(b,D);D++);E=b.slice(y,D);if(p=v[E])y+=E.length;else{for(p=[];y<D;)u.decode(b,y,A),J=A.value,y=A.rest,p.push(J);if(2===p.length)throw Error("Found a source, but no line and column");if(3===
p.length)throw Error("Found a source and line, but no column");v[E]=p}z.generatedColumn=f+p[0];f=z.generatedColumn;1<p.length&&(z.source=m+p[1],m+=p[1],z.originalLine=d+p[2],d=z.originalLine,z.originalLine+=1,z.originalColumn=h+p[3],h=z.originalColumn,4<p.length&&(z.name=q+p[4],q+=p[4]));H.push(z);"number"===typeof z.originalLine&&F.push(z)}r(H,e.compareByGeneratedPositionsDeflated);this.__generatedMappings=H;r(F,e.compareByOriginalPositions);this.__originalMappings=F};d.prototype._findMapping=function(b,
c,e,d,h,r){if(0>=b[e])throw new TypeError("Line must be greater than or equal to 1, got "+b[e]);if(0>b[d])throw new TypeError("Column must be greater than or equal to 0, got "+b[d]);return a.search(b,c,h,r)};d.prototype.computeColumnSpans=function(){for(var b=0;b<this._generatedMappings.length;++b){var a=this._generatedMappings[b];if(b+1<this._generatedMappings.length){var c=this._generatedMappings[b+1];if(a.generatedLine===c.generatedLine){a.lastGeneratedColumn=c.generatedColumn-1;continue}}a.lastGeneratedColumn=
Infinity}};d.prototype.originalPositionFor=function(b){var a={generatedLine:e.getArg(b,"line"),generatedColumn:e.getArg(b,"column")};b=this._findMapping(a,this._generatedMappings,"generatedLine","generatedColumn",e.compareByGeneratedPositionsDeflated,e.getArg(b,"bias",c.GREATEST_LOWER_BOUND));if(0<=b&&(b=this._generatedMappings[b],b.generatedLine===a.generatedLine)){a=e.getArg(b,"source",null);null!==a&&(a=this._sources.at(a),null!=this.sourceRoot&&(a=e.join(this.sourceRoot,a)));var d=e.getArg(b,
"name",null);null!==d&&(d=this._names.at(d));return{source:a,line:e.getArg(b,"originalLine",null),column:e.getArg(b,"originalColumn",null),name:d}}return{source:null,line:null,column:null,name:null}};d.prototype.hasContentsOfAllSources=function(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(b){return null==b}):!1};d.prototype.sourceContentFor=function(b,a){if(!this.sourcesContent)return null;null!=this.sourceRoot&&(b=e.relative(this.sourceRoot,
b));if(this._sources.has(b))return this.sourcesContent[this._sources.indexOf(b)];var c;if(null!=this.sourceRoot&&(c=e.urlParse(this.sourceRoot))){var f=b.replace(/^file:\/\//,"");if("file"==c.scheme&&this._sources.has(f))return this.sourcesContent[this._sources.indexOf(f)];if((!c.path||"/"==c.path)&&this._sources.has("/"+b))return this.sourcesContent[this._sources.indexOf("/"+b)]}if(a)return null;throw Error('"'+b+'" is not in the SourceMap.');};d.prototype.generatedPositionFor=function(b){var a=
e.getArg(b,"source");null!=this.sourceRoot&&(a=e.relative(this.sourceRoot,a));if(!this._sources.has(a))return{line:null,column:null,lastColumn:null};a=this._sources.indexOf(a);a={source:a,originalLine:e.getArg(b,"line"),originalColumn:e.getArg(b,"column")};b=this._findMapping(a,this._originalMappings,"originalLine","originalColumn",e.compareByOriginalPositions,e.getArg(b,"bias",c.GREATEST_LOWER_BOUND));return 0<=b&&(b=this._originalMappings[b],b.source===a.source)?{line:e.getArg(b,"generatedLine",
null),column:e.getArg(b,"generatedColumn",null),lastColumn:e.getArg(b,"lastGeneratedColumn",null)}:{line:null,column:null,lastColumn:null}};m.BasicSourceMapConsumer=d;q.prototype=Object.create(c.prototype);q.prototype.constructor=c;q.prototype._version=3;Object.defineProperty(q.prototype,"sources",{get:function(){for(var a=[],c=0;c<this._sections.length;c++)for(var e=0;e<this._sections[c].consumer.sources.length;e++)a.push(this._sections[c].consumer.sources[e]);return a}});q.prototype.originalPositionFor=
function(b){var c={generatedLine:e.getArg(b,"line"),generatedColumn:e.getArg(b,"column")},d=a.search(c,this._sections,function(a,b){var c=a.generatedLine-b.generatedOffset.generatedLine;return c?c:a.generatedColumn-b.generatedOffset.generatedColumn});return(d=this._sections[d])?d.consumer.originalPositionFor({line:c.generatedLine-(d.generatedOffset.generatedLine-1),column:c.generatedColumn-(d.generatedOffset.generatedLine===c.generatedLine?d.generatedOffset.generatedColumn-1:0),bias:b.bias}):{source:null,
line:null,column:null,name:null}};q.prototype.hasContentsOfAllSources=function(){return this._sections.every(function(a){return a.consumer.hasContentsOfAllSources()})};q.prototype.sourceContentFor=function(a,c){for(var b=0;b<this._sections.length;b++){var f=this._sections[b].consumer.sourceContentFor(a,!0);if(f)return f}if(c)return null;throw Error('"'+a+'" is not in the SourceMap.');};q.prototype.generatedPositionFor=function(a){for(var b=0;b<this._sections.length;b++){var c=this._sections[b];if(-1!==
c.consumer.sources.indexOf(e.getArg(a,"source"))){var d=c.consumer.generatedPositionFor(a);if(d)return{line:d.line+(c.generatedOffset.generatedLine-1),column:d.column+(c.generatedOffset.generatedLine===d.line?c.generatedOffset.generatedColumn-1:0)}}}return{line:null,column:null}};q.prototype._parseMappings=function(a,c){this.__generatedMappings=[];this.__originalMappings=[];for(var b=0;b<this._sections.length;b++)for(var f=this._sections[b],d=f.consumer._generatedMappings,h=0;h<d.length;h++){var k=
d[h],u=f.consumer._sources.at(k.source);null!==f.consumer.sourceRoot&&(u=e.join(f.consumer.sourceRoot,u));this._sources.add(u);u=this._sources.indexOf(u);var m=f.consumer._names.at(k.name);this._names.add(m);m=this._names.indexOf(m);k={source:u,generatedLine:k.generatedLine+(f.generatedOffset.generatedLine-1),generatedColumn:k.generatedColumn+(f.generatedOffset.generatedLine===k.generatedLine?f.generatedOffset.generatedColumn-1:0),originalLine:k.originalLine,originalColumn:k.originalColumn,name:m};
this.__generatedMappings.push(k);"number"===typeof k.originalLine&&this.__originalMappings.push(k)}r(this.__generatedMappings,e.compareByGeneratedPositionsDeflated);r(this.__originalMappings,e.compareByOriginalPositions)};m.IndexedSourceMapConsumer=q},{"./array-set":8,"./base64-vlq":9,"./binary-search":11,"./quick-sort":13,"./util":17}],15:[function(n,v,m){function c(a){a||(a={});this._file=k.getArg(a,"file",null);this._sourceRoot=k.getArg(a,"sourceRoot",null);this._skipValidation=k.getArg(a,"skipValidation",
!1);this._sources=new q;this._names=new q;this._mappings=new e;this._sourcesContents=null}var d=n("./base64-vlq"),k=n("./util"),q=n("./array-set").ArraySet,e=n("./mapping-list").MappingList;c.prototype._version=3;c.fromSourceMap=function(a){var e=a.sourceRoot,d=new c({file:a.file,sourceRoot:e});a.eachMapping(function(a){var b={generated:{line:a.generatedLine,column:a.generatedColumn}};null!=a.source&&(b.source=a.source,null!=e&&(b.source=k.relative(e,b.source)),b.original={line:a.originalLine,column:a.originalColumn},
null!=a.name&&(b.name=a.name));d.addMapping(b)});a.sources.forEach(function(c){var b=a.sourceContentFor(c);null!=b&&d.setSourceContent(c,b)});return d};c.prototype.addMapping=function(a){var c=k.getArg(a,"generated"),e=k.getArg(a,"original",null),d=k.getArg(a,"source",null);a=k.getArg(a,"name",null);this._skipValidation||this._validateMapping(c,e,d,a);null!=d&&(d=String(d),this._sources.has(d)||this._sources.add(d));null!=a&&(a=String(a),this._names.has(a)||this._names.add(a));this._mappings.add({generatedLine:c.line,
generatedColumn:c.column,originalLine:null!=e&&e.line,originalColumn:null!=e&&e.column,source:d,name:a})};c.prototype.setSourceContent=function(a,c){var e=a;null!=this._sourceRoot&&(e=k.relative(this._sourceRoot,e));null!=c?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[k.toSetString(e)]=c):this._sourcesContents&&(delete this._sourcesContents[k.toSetString(e)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))};c.prototype.applySourceMap=
function(a,c,e){var d=c;if(null==c){if(null==a.file)throw Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');d=a.file}var b=this._sourceRoot;null!=b&&(d=k.relative(b,d));var f=new q,h=new q;this._mappings.unsortedForEach(function(c){if(c.source===d&&null!=c.originalLine){var t=a.originalPositionFor({line:c.originalLine,column:c.originalColumn});null!=t.source&&(c.source=t.source,null!=e&&(c.source=
k.join(e,c.source)),null!=b&&(c.source=k.relative(b,c.source)),c.originalLine=t.line,c.originalColumn=t.column,null!=t.name&&(c.name=t.name))}t=c.source;null==t||f.has(t)||f.add(t);c=c.name;null==c||h.has(c)||h.add(c)},this);this._sources=f;this._names=h;a.sources.forEach(function(c){var f=a.sourceContentFor(c);null!=f&&(null!=e&&(c=k.join(e,c)),null!=b&&(c=k.relative(b,c)),this.setSourceContent(c,f))},this)};c.prototype._validateMapping=function(a,c,e,d){if(!(a&&"line"in a&&"column"in a&&0<a.line&&
0<=a.column&&!c&&!e&&!d||a&&"line"in a&&"column"in a&&c&&"line"in c&&"column"in c&&0<a.line&&0<=a.column&&0<c.line&&0<=c.column&&e))throw Error("Invalid mapping: "+JSON.stringify({generated:a,source:e,original:c,name:d}));};c.prototype._serializeMappings=function(){for(var a=0,c=1,e=0,m=0,b=0,f=0,q="",t,n,I,B=this._mappings.toArray(),v=0,C=B.length;v<C;v++){n=B[v];t="";if(n.generatedLine!==c)for(a=0;n.generatedLine!==c;)t+=";",c++;else if(0<v){if(!k.compareByGeneratedPositionsInflated(n,B[v-1]))continue;
t+=","}t+=d.encode(n.generatedColumn-a);a=n.generatedColumn;null!=n.source&&(I=this._sources.indexOf(n.source),t+=d.encode(I-f),f=I,t+=d.encode(n.originalLine-1-m),m=n.originalLine-1,t+=d.encode(n.originalColumn-e),e=n.originalColumn,null!=n.name&&(n=this._names.indexOf(n.name),t+=d.encode(n-b),b=n));q+=t}return q};c.prototype._generateSourcesContent=function(a,c){return a.map(function(a){if(!this._sourcesContents)return null;null!=c&&(a=k.relative(c,a));a=k.toSetString(a);return Object.prototype.hasOwnProperty.call(this._sourcesContents,
a)?this._sourcesContents[a]:null},this)};c.prototype.toJSON=function(){var a={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};null!=this._file&&(a.file=this._file);null!=this._sourceRoot&&(a.sourceRoot=this._sourceRoot);this._sourcesContents&&(a.sourcesContent=this._generateSourcesContent(a.sources,a.sourceRoot));return a};c.prototype.toString=function(){return JSON.stringify(this.toJSON())};m.SourceMapGenerator=c},{"./array-set":8,
"./base64-vlq":9,"./mapping-list":12,"./util":17}],16:[function(n,v,m){function c(c,a,d,k,m){this.children=[];this.sourceContents={};this.line=null==c?null:c;this.column=null==a?null:a;this.source=null==d?null:d;this.name=null==m?null:m;this.$$$isSourceNode$$$=!0;null!=k&&this.add(k)}var d=n("./source-map-generator").SourceMapGenerator,k=n("./util"),q=/(\r?\n)/;c.fromStringWithSourceMap=function(e,a,d){function h(a,b){if(null===a||void 0===a.source)m.add(b);else{var f=d?k.join(d,a.source):a.source;
m.add(new c(a.originalLine,a.originalColumn,f,b,a.name))}}var m=new c,b=e.split(q),f=function(){var a=b.shift(),c=b.shift()||"";return a+c},n=1,t=0,v=null;a.eachMapping(function(a){if(null!==v)if(n<a.generatedLine)h(v,f()),n++,t=0;else{var c=b[0];var e=c.substr(0,a.generatedColumn-t);b[0]=c.substr(a.generatedColumn-t);t=a.generatedColumn;h(v,e);v=a;return}for(;n<a.generatedLine;)m.add(f()),n++;t<a.generatedColumn&&(c=b[0],m.add(c.substr(0,a.generatedColumn)),b[0]=c.substr(a.generatedColumn),t=a.generatedColumn);
v=a},this);0<b.length&&(v&&h(v,f()),m.add(b.join("")));a.sources.forEach(function(b){var c=a.sourceContentFor(b);null!=c&&(null!=d&&(b=k.join(d,b)),m.setSourceContent(b,c))});return m};c.prototype.add=function(c){if(Array.isArray(c))c.forEach(function(a){this.add(a)},this);else if(c.$$$isSourceNode$$$||"string"===typeof c)c&&this.children.push(c);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+c);return this};c.prototype.prepend=function(c){if(Array.isArray(c))for(var a=
c.length-1;0<=a;a--)this.prepend(c[a]);else if(c.$$$isSourceNode$$$||"string"===typeof c)this.children.unshift(c);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+c);return this};c.prototype.walk=function(c){for(var a,e=0,d=this.children.length;e<d;e++)a=this.children[e],a.$$$isSourceNode$$$?a.walk(c):""!==a&&c(a,{source:this.source,line:this.line,column:this.column,name:this.name})};c.prototype.join=function(c){var a,e=this.children.length;if(0<
e){var d=[];for(a=0;a<e-1;a++)d.push(this.children[a]),d.push(c);d.push(this.children[a]);this.children=d}return this};c.prototype.replaceRight=function(c,a){var e=this.children[this.children.length-1];e.$$$isSourceNode$$$?e.replaceRight(c,a):"string"===typeof e?this.children[this.children.length-1]=e.replace(c,a):this.children.push("".replace(c,a));return this};c.prototype.setSourceContent=function(c,a){this.sourceContents[k.toSetString(c)]=a};c.prototype.walkSourceContents=function(c){for(var a=
0,e=this.children.length;a<e;a++)this.children[a].$$$isSourceNode$$$&&this.children[a].walkSourceContents(c);var d=Object.keys(this.sourceContents);a=0;for(e=d.length;a<e;a++)c(k.fromSetString(d[a]),this.sourceContents[d[a]])};c.prototype.toString=function(){var c="";this.walk(function(a){c+=a});return c};c.prototype.toStringWithSourceMap=function(c){var a="",e=1,k=0,m=new d(c),b=!1,f=null,n=null,t=null,q=null;this.walk(function(c,d){a+=c;null!==d.source&&null!==d.line&&null!==d.column?(f===d.source&&
n===d.line&&t===d.column&&q===d.name||m.addMapping({source:d.source,original:{line:d.line,column:d.column},generated:{line:e,column:k},name:d.name}),f=d.source,n=d.line,t=d.column,q=d.name,b=!0):b&&(m.addMapping({generated:{line:e,column:k}}),f=null,b=!1);for(var h=0,r=c.length;h<r;h++)10===c.charCodeAt(h)?(e++,k=0,h+1===r?(f=null,b=!1):b&&m.addMapping({source:d.source,original:{line:d.line,column:d.column},generated:{line:e,column:k},name:d.name})):k++});this.walkSourceContents(function(a,b){m.setSourceContent(a,
b)});return{code:a,map:m}};m.SourceNode=c},{"./source-map-generator":15,"./util":17}],17:[function(n,v,m){function c(a){return(a=a.match(u))?{scheme:a[1],auth:a[2],host:a[3],port:a[4],path:a[5]}:null}function d(a){var b="";a.scheme&&(b+=a.scheme+":");b+="//";a.auth&&(b+=a.auth+"@");a.host&&(b+=a.host);a.port&&(b+=":"+a.port);a.path&&(b+=a.path);return b}function k(a){var b=a,e=c(a);if(e){if(!e.path)return a;b=e.path}a=m.isAbsolute(b);b=b.split(/\/+/);for(var k,h=0,n=b.length-1;0<=n;n--)k=b[n],"."===
k?b.splice(n,1):".."===k?h++:0<h&&(""===k?(b.splice(n+1,h),h=0):(b.splice(n,2),h--));b=b.join("/");""===b&&(b=a?"/":".");return e?(e.path=b,d(e)):b}function q(a){return a}function e(a){return h(a)?"$"+a:a}function a(a){return h(a)?a.slice(1):a}function h(a){if(!a)return!1;var b=a.length;if(9>b||95!==a.charCodeAt(b-1)||95!==a.charCodeAt(b-2)||111!==a.charCodeAt(b-3)||116!==a.charCodeAt(b-4)||111!==a.charCodeAt(b-5)||114!==a.charCodeAt(b-6)||112!==a.charCodeAt(b-7)||95!==a.charCodeAt(b-8)||95!==a.charCodeAt(b-
9))return!1;for(b-=10;0<=b;b--)if(36!==a.charCodeAt(b))return!1;return!0}m.getArg=function(a,c,d){if(c in a)return a[c];if(3===arguments.length)return d;throw Error('"'+c+'" is a required argument.');};var u=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/,r=/^data:.+\,.+$/;m.urlParse=c;m.urlGenerate=d;m.normalize=k;m.join=function(a,e){""===a&&(a=".");""===e&&(e=".");var b=c(e),f=c(a);f&&(a=f.path||"/");if(b&&!b.scheme)return f&&(b.scheme=f.scheme),d(b);if(b||e.match(r))return e;
if(f&&!f.host&&!f.path)return f.host=e,d(f);b="/"===e.charAt(0)?e:k(a.replace(/\/+$/,"")+"/"+e);return f?(f.path=b,d(f)):b};m.isAbsolute=function(a){return"/"===a.charAt(0)||!!a.match(u)};m.relative=function(a,c){""===a&&(a=".");a=a.replace(/\/$/,"");for(var b=0;0!==c.indexOf(a+"/");){var d=a.lastIndexOf("/");if(0>d)return c;a=a.slice(0,d);if(a.match(/^([^\/]+:\/)?\/*$/))return c;++b}return Array(b+1).join("../")+c.substr(a.length+1)};n=!("__proto__"in Object.create(null));m.toSetString=n?q:e;m.fromSetString=
n?q:a;m.compareByOriginalPositions=function(a,c,d){var b=a.source-c.source;if(0!==b)return b;b=a.originalLine-c.originalLine;if(0!==b)return b;b=a.originalColumn-c.originalColumn;if(0!==b||d)return b;b=a.generatedColumn-c.generatedColumn;if(0!==b)return b;b=a.generatedLine-c.generatedLine;return 0!==b?b:a.name-c.name};m.compareByGeneratedPositionsDeflated=function(a,c,d){var b=a.generatedLine-c.generatedLine;if(0!==b)return b;b=a.generatedColumn-c.generatedColumn;if(0!==b||d)return b;b=a.source-c.source;
if(0!==b)return b;b=a.originalLine-c.originalLine;if(0!==b)return b;b=a.originalColumn-c.originalColumn;return 0!==b?b:a.name-c.name};m.compareByGeneratedPositionsInflated=function(a,c){var b=a.generatedLine-c.generatedLine;if(0!==b)return b;b=a.generatedColumn-c.generatedColumn;if(0!==b)return b;b=a.source;var d=c.source;b=b===d?0:b>d?1:-1;if(0!==b)return b;b=a.originalLine-c.originalLine;if(0!==b)return b;b=a.originalColumn-c.originalColumn;0===b&&(b=a.name,d=c.name,b=b===d?0:b>d?1:-1);return b}},
{}],18:[function(n,v,m){m.SourceMapGenerator=n("./lib/source-map-generator").SourceMapGenerator;m.SourceMapConsumer=n("./lib/source-map-consumer").SourceMapConsumer;m.SourceNode=n("./lib/source-node").SourceNode},{"./lib/source-map-consumer":14,"./lib/source-map-generator":15,"./lib/source-node":16}],19:[function(n,v,m){(function(c,d){function k(){return"browser"===K?!0:"node"===K?!1:"undefined"!==typeof window&&"function"===typeof XMLHttpRequest&&!(window.require&&window.module&&window.process&&
"renderer"===window.process.type)}function q(a){return function(b){for(var c=0;c<a.length;c++){var d=a[c](b);if(d)return d}return null}}function e(a,b){if(!a)return b;var c=I.dirname(a),d=/^\w+:\/\/[^\/]*/.exec(c);d=d?d[0]:"";return d+I.resolve(c.slice(d.length),b)}function a(a){var b=F[a.source];if(!b){var c=D(a.source);c?(b=F[a.source]={url:c.url,map:new M(c.map)},b.map.sourcesContent&&b.map.sources.forEach(function(a,c){var d=b.map.sourcesContent[c];if(d){var g=e(b.url,a);A[g]=d}})):b=F[a.source]=
{url:null,map:null}}return b&&b.map&&(c=b.map.originalPositionFor(a),null!==c.source)?(c.source=e(b.url,c.source),c):a}function h(b){var c=/^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(b);return c?(b=a({source:c[2],line:+c[3],column:c[4]-1}),"eval at "+c[1]+" ("+b.source+":"+b.line+":"+(b.column+1)+")"):(c=/^eval at ([^(]+) \((.+)\)$/.exec(b))?"eval at "+c[1]+" ("+h(c[2])+")":b}function u(){var a="";if(this.isNative())a="native";else{var b=this.getScriptNameOrSourceURL();!b&&this.isEval()&&(a=this.getEvalOrigin(),
a+=", ");a=b?a+b:a+"<anonymous>";b=this.getLineNumber();null!=b&&(a+=":"+b,(b=this.getColumnNumber())&&(a+=":"+b))}b="";var c=this.getFunctionName(),d=!0,e=this.isConstructor();if(this.isToplevel()||e)e?b+="new "+(c||"<anonymous>"):c?b+=c:(b+=a,d=!1);else{e=this.getTypeName();"[object Object]"===e&&(e="null");var f=this.getMethodName();c?(e&&0!=c.indexOf(e)&&(b+=e+"."),b+=c,f&&c.indexOf("."+f)!=c.length-f.length-1&&(b+=" [as "+f+"]")):b+=e+"."+(f||"<anonymous>")}d&&(b+=" ("+a+")");return b}function r(a){var b=
{};Object.getOwnPropertyNames(Object.getPrototypeOf(a)).forEach(function(c){b[c]=/^(?:is|get)/.test(c)?function(){return a[c].call(a)}:a[c]});b.toString=u;return b}function b(b){if(b.isNative())return b;var c=b.getFileName()||b.getScriptNameOrSourceURL();if(c){var d=b.getLineNumber(),e=b.getColumnNumber()-1;1===d&&62<e&&!k()&&!b.isEval()&&(e-=62);var f=a({source:c,line:d,column:e});b=r(b);b.getFileName=function(){return f.source};b.getLineNumber=function(){return f.line};b.getColumnNumber=function(){return f.column+
1};b.getScriptNameOrSourceURL=function(){return f.source};return b}var m=b.isEval()&&b.getEvalOrigin();m&&(m=h(m),b=r(b),b.getEvalOrigin=function(){return m});return b}function f(a,c){y&&(A={},F={});return a+c.map(function(a){return"\n at "+b(a)}).join("")}function v(a){var b=/\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(a.stack);if(b){a=b[1];var c=+b[2];b=+b[3];var d=A[a];if(!d&&B&&B.existsSync(a))try{d=B.readFileSync(a,"utf8")}catch(x){d=""}if(d&&(d=d.split(/(?:\r\n|\r|\n)/)[c-1]))return a+":"+
c+"\n"+d+"\n"+Array(b).join(" ")+"^"}return null}function t(){var a=c.emit;c.emit=function(b){if("uncaughtException"===b){var d=arguments[1]&&arguments[1].stack,e=0<this.listeners(b).length;if(d&&!e){d=arguments[1];if(e=v(d))console.error(),console.error(e);console.error(d.stack);c.exit(1);return}}return a.apply(this,arguments)}}var M=n("source-map").SourceMapConsumer,I=n("path");try{var B=n("fs");B.existsSync&&B.readFileSync||(B=null)}catch(J){}var L=!1,C=!1,y=!1,K="auto",A={},F={},H=/^data:application\/json[^,]+base64,/,
z=[],E=[],p=q(z);z.push(function(a){a=a.trim();if(a in A)return A[a];var b=null;if(!B){var c=new XMLHttpRequest;c.open("GET",a,!1);c.send(null);b=null;4===c.readyState&&200===c.status&&(b=c.responseText)}else if(B.existsSync(a))try{b=B.readFileSync(a,"utf8")}catch(l){b=""}return A[a]=b});var D=q(E);E.push(function(a){a:{if(k())try{var b=new XMLHttpRequest;b.open("GET",a,!1);b.send(null);var c=b.getResponseHeader("SourceMap")||b.getResponseHeader("X-SourceMap");if(c){var f=c;break a}}catch(P){}f=p(a);
b=/(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/)[ \t]*$)/mg;for(var h;c=b.exec(f);)h=c;f=h?h[1]:null}if(!f)return null;H.test(f)?(h=f.slice(f.indexOf(",")+1),h=(new d(h,"base64")).toString(),f=a):(f=e(a,f),h=p(f));return h?{url:f,map:h}:null});m.wrapCallSite=b;m.getErrorSource=v;m.mapSourcePosition=a;m.retrieveSourceMap=D;m.install=function(a){a=a||{};if(a.environment&&(K=a.environment,-1===["node","browser","auto"].indexOf(K)))throw Error("environment "+
K+" was unknown. Available options are {auto, browser, node}");a.retrieveFile&&(a.overrideRetrieveFile&&(z.length=0),z.unshift(a.retrieveFile));a.retrieveSourceMap&&(a.overrideRetrieveSourceMap&&(E.length=0),E.unshift(a.retrieveSourceMap));if(a.hookRequire&&!k()){try{var b=n("module")}catch(l){}var d=b.prototype._compile;d.__sourceMapSupport||(b.prototype._compile=function(a,b){A[b]=a;F[b]=void 0;return d.call(this,a,b)},b.prototype._compile.__sourceMapSupport=!0)}y||(y="emptyCacheBetweenOperations"in
a?a.emptyCacheBetweenOperations:!1);L||(L=!0,Error.prepareStackTrace=f);!C&&("handleUncaughtExceptions"in a?a.handleUncaughtExceptions:1)&&"object"===typeof c&&null!==c&&"function"===typeof c.on&&(C=!0,t())}}).call(this,n("node_modules/process/browser.js"),n("buffer").Buffer)},{"node_modules/process/browser.js":7,buffer:4,fs:3,module:3,path:6,"source-map":18}]},{},[1]);return N});

View File

@ -1,30 +0,0 @@
{
"name": "source-map-support",
"description": "Fixes stack traces for files with source maps",
"version": "0.4.18",
"main": "./source-map-support.js",
"scripts": {
"build": "node build.js",
"serve-tests": "http-server -p 1336",
"prepublish": "npm run build",
"test": "mocha"
},
"dependencies": {
"source-map": "^0.5.6"
},
"devDependencies": {
"browserify": "3.44.2",
"coffee-script": "1.7.1",
"http-server": "^0.8.5",
"mocha": "1.18.2",
"webpack": "^1.13.3"
},
"repository": {
"type": "git",
"url": "https://github.com/evanw/node-source-map-support"
},
"bugs": {
"url": "https://github.com/evanw/node-source-map-support/issues"
},
"license": "MIT"
}

View File

@ -1 +0,0 @@
require('./').install();

View File

@ -1,527 +0,0 @@
var SourceMapConsumer = require('source-map').SourceMapConsumer;
var path = require('path');
var fs;
try {
fs = require('fs');
if (!fs.existsSync || !fs.readFileSync) {
// fs doesn't have all methods we need
fs = null;
}
} catch (err) {
/* nop */
}
// Only install once if called multiple times
var errorFormatterInstalled = false;
var uncaughtShimInstalled = false;
// If true, the caches are reset before a stack trace formatting operation
var emptyCacheBetweenOperations = false;
// Supports {browser, node, auto}
var environment = "auto";
// Maps a file path to a string containing the file contents
var fileContentsCache = {};
// Maps a file path to a source map for that file
var sourceMapCache = {};
// Regex for detecting source maps
var reSourceMap = /^data:application\/json[^,]+base64,/;
// Priority list of retrieve handlers
var retrieveFileHandlers = [];
var retrieveMapHandlers = [];
function isInBrowser() {
if (environment === "browser")
return true;
if (environment === "node")
return false;
return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function') && !(window.require && window.module && window.process && window.process.type === "renderer"));
}
function hasGlobalProcessEventEmitter() {
return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function'));
}
function handlerExec(list) {
return function(arg) {
for (var i = 0; i < list.length; i++) {
var ret = list[i](arg);
if (ret) {
return ret;
}
}
return null;
};
}
var retrieveFile = handlerExec(retrieveFileHandlers);
retrieveFileHandlers.push(function(path) {
// Trim the path to make sure there is no extra whitespace.
path = path.trim();
if (path in fileContentsCache) {
return fileContentsCache[path];
}
var contents = null;
if (!fs) {
// Use SJAX if we are in the browser
var xhr = new XMLHttpRequest();
xhr.open('GET', path, false);
xhr.send(null);
var contents = null
if (xhr.readyState === 4 && xhr.status === 200) {
contents = xhr.responseText
}
} else if (fs.existsSync(path)) {
// Otherwise, use the filesystem
try {
contents = fs.readFileSync(path, 'utf8');
} catch (er) {
contents = '';
}
}
return fileContentsCache[path] = contents;
});
// Support URLs relative to a directory, but be careful about a protocol prefix
// in case we are in the browser (i.e. directories may start with "http://")
function supportRelativeURL(file, url) {
if (!file) return url;
var dir = path.dirname(file);
var match = /^\w+:\/\/[^\/]*/.exec(dir);
var protocol = match ? match[0] : '';
return protocol + path.resolve(dir.slice(protocol.length), url);
}
function retrieveSourceMapURL(source) {
var fileData;
if (isInBrowser()) {
try {
var xhr = new XMLHttpRequest();
xhr.open('GET', source, false);
xhr.send(null);
fileData = xhr.readyState === 4 ? xhr.responseText : null;
// Support providing a sourceMappingURL via the SourceMap header
var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
xhr.getResponseHeader("X-SourceMap");
if (sourceMapHeader) {
return sourceMapHeader;
}
} catch (e) {
}
}
// Get the URL of the source map
fileData = retrieveFile(source);
var re = /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/)[ \t]*$)/mg;
// Keep executing the search to find the *last* sourceMappingURL to avoid
// picking up sourceMappingURLs from comments, strings, etc.
var lastMatch, match;
while (match = re.exec(fileData)) lastMatch = match;
if (!lastMatch) return null;
return lastMatch[1];
};
// Can be overridden by the retrieveSourceMap option to install. Takes a
// generated source filename; returns a {map, optional url} object, or null if
// there is no source map. The map field may be either a string or the parsed
// JSON object (ie, it must be a valid argument to the SourceMapConsumer
// constructor).
var retrieveSourceMap = handlerExec(retrieveMapHandlers);
retrieveMapHandlers.push(function(source) {
var sourceMappingURL = retrieveSourceMapURL(source);
if (!sourceMappingURL) return null;
// Read the contents of the source map
var sourceMapData;
if (reSourceMap.test(sourceMappingURL)) {
// Support source map URL as a data url
var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);
sourceMapData = new Buffer(rawData, "base64").toString();
sourceMappingURL = source;
} else {
// Support source map URLs relative to the source URL
sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
sourceMapData = retrieveFile(sourceMappingURL);
}
if (!sourceMapData) {
return null;
}
return {
url: sourceMappingURL,
map: sourceMapData
};
});
function mapSourcePosition(position) {
var sourceMap = sourceMapCache[position.source];
if (!sourceMap) {
// Call the (overrideable) retrieveSourceMap function to get the source map.
var urlAndMap = retrieveSourceMap(position.source);
if (urlAndMap) {
sourceMap = sourceMapCache[position.source] = {
url: urlAndMap.url,
map: new SourceMapConsumer(urlAndMap.map)
};
// Load all sources stored inline with the source map into the file cache
// to pretend like they are already loaded. They may not exist on disk.
if (sourceMap.map.sourcesContent) {
sourceMap.map.sources.forEach(function(source, i) {
var contents = sourceMap.map.sourcesContent[i];
if (contents) {
var url = supportRelativeURL(sourceMap.url, source);
fileContentsCache[url] = contents;
}
});
}
} else {
sourceMap = sourceMapCache[position.source] = {
url: null,
map: null
};
}
}
// Resolve the source URL relative to the URL of the source map
if (sourceMap && sourceMap.map) {
var originalPosition = sourceMap.map.originalPositionFor(position);
// Only return the original position if a matching line was found. If no
// matching line is found then we return position instead, which will cause
// the stack trace to print the path and line for the compiled file. It is
// better to give a precise location in the compiled file than a vague
// location in the original file.
if (originalPosition.source !== null) {
originalPosition.source = supportRelativeURL(
sourceMap.url, originalPosition.source);
return originalPosition;
}
}
return position;
}
// Parses code generated by FormatEvalOrigin(), a function inside V8:
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js
function mapEvalOrigin(origin) {
// Most eval() calls are in this format
var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
if (match) {
var position = mapSourcePosition({
source: match[2],
line: +match[3],
column: match[4] - 1
});
return 'eval at ' + match[1] + ' (' + position.source + ':' +
position.line + ':' + (position.column + 1) + ')';
}
// Parse nested eval() calls using recursion
match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
if (match) {
return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
}
// Make sure we still return useful information if we didn't find anything
return origin;
}
// This is copied almost verbatim from the V8 source code at
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The
// implementation of wrapCallSite() used to just forward to the actual source
// code of CallSite.prototype.toString but unfortunately a new release of V8
// did something to the prototype chain and broke the shim. The only fix I
// could find was copy/paste.
function CallSiteToString() {
var fileName;
var fileLocation = "";
if (this.isNative()) {
fileLocation = "native";
} else {
fileName = this.getScriptNameOrSourceURL();
if (!fileName && this.isEval()) {
fileLocation = this.getEvalOrigin();
fileLocation += ", "; // Expecting source position to follow.
}
if (fileName) {
fileLocation += fileName;
} else {
// Source code does not originate from a file and is not native, but we
// can still get the source position inside the source string, e.g. in
// an eval string.
fileLocation += "<anonymous>";
}
var lineNumber = this.getLineNumber();
if (lineNumber != null) {
fileLocation += ":" + lineNumber;
var columnNumber = this.getColumnNumber();
if (columnNumber) {
fileLocation += ":" + columnNumber;
}
}
}
var line = "";
var functionName = this.getFunctionName();
var addSuffix = true;
var isConstructor = this.isConstructor();
var isMethodCall = !(this.isToplevel() || isConstructor);
if (isMethodCall) {
var typeName = this.getTypeName();
// Fixes shim to be backward compatable with Node v0 to v4
if (typeName === "[object Object]") {
typeName = "null";
}
var methodName = this.getMethodName();
if (functionName) {
if (typeName && functionName.indexOf(typeName) != 0) {
line += typeName + ".";
}
line += functionName;
if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
line += " [as " + methodName + "]";
}
} else {
line += typeName + "." + (methodName || "<anonymous>");
}
} else if (isConstructor) {
line += "new " + (functionName || "<anonymous>");
} else if (functionName) {
line += functionName;
} else {
line += fileLocation;
addSuffix = false;
}
if (addSuffix) {
line += " (" + fileLocation + ")";
}
return line;
}
function cloneCallSite(frame) {
var object = {};
Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];
});
object.toString = CallSiteToString;
return object;
}
function wrapCallSite(frame) {
if(frame.isNative()) {
return frame;
}
// Most call sites will return the source file from getFileName(), but code
// passed to eval() ending in "//# sourceURL=..." will return the source file
// from getScriptNameOrSourceURL() instead
var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
if (source) {
var line = frame.getLineNumber();
var column = frame.getColumnNumber() - 1;
// Fix position in Node where some (internal) code is prepended.
// See https://github.com/evanw/node-source-map-support/issues/36
var headerLength = 62;
if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) {
column -= headerLength;
}
var position = mapSourcePosition({
source: source,
line: line,
column: column
});
frame = cloneCallSite(frame);
frame.getFileName = function() { return position.source; };
frame.getLineNumber = function() { return position.line; };
frame.getColumnNumber = function() { return position.column + 1; };
frame.getScriptNameOrSourceURL = function() { return position.source; };
return frame;
}
// Code called using eval() needs special handling
var origin = frame.isEval() && frame.getEvalOrigin();
if (origin) {
origin = mapEvalOrigin(origin);
frame = cloneCallSite(frame);
frame.getEvalOrigin = function() { return origin; };
return frame;
}
// If we get here then we were unable to change the source position
return frame;
}
// This function is part of the V8 stack trace API, for more info see:
// http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
function prepareStackTrace(error, stack) {
if (emptyCacheBetweenOperations) {
fileContentsCache = {};
sourceMapCache = {};
}
return error + stack.map(function(frame) {
return '\n at ' + wrapCallSite(frame);
}).join('');
}
// Generate position and snippet of original source with pointer
function getErrorSource(error) {
var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
if (match) {
var source = match[1];
var line = +match[2];
var column = +match[3];
// Support the inline sourceContents inside the source map
var contents = fileContentsCache[source];
// Support files on disk
if (!contents && fs && fs.existsSync(source)) {
try {
contents = fs.readFileSync(source, 'utf8');
} catch (er) {
contents = '';
}
}
// Format the line from the original source code like node does
if (contents) {
var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
if (code) {
return source + ':' + line + '\n' + code + '\n' +
new Array(column).join(' ') + '^';
}
}
}
return null;
}
function printErrorAndExit (error) {
var source = getErrorSource(error);
if (source) {
console.error();
console.error(source);
}
console.error(error.stack);
process.exit(1);
}
function shimEmitUncaughtException () {
var origEmit = process.emit;
process.emit = function (type) {
if (type === 'uncaughtException') {
var hasStack = (arguments[1] && arguments[1].stack);
var hasListeners = (this.listeners(type).length > 0);
if (hasStack && !hasListeners) {
return printErrorAndExit(arguments[1]);
}
}
return origEmit.apply(this, arguments);
};
}
exports.wrapCallSite = wrapCallSite;
exports.getErrorSource = getErrorSource;
exports.mapSourcePosition = mapSourcePosition;
exports.retrieveSourceMap = retrieveSourceMap;
exports.install = function(options) {
options = options || {};
if (options.environment) {
environment = options.environment;
if (["node", "browser", "auto"].indexOf(environment) === -1) {
throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}")
}
}
// Allow sources to be found by methods other than reading the files
// directly from disk.
if (options.retrieveFile) {
if (options.overrideRetrieveFile) {
retrieveFileHandlers.length = 0;
}
retrieveFileHandlers.unshift(options.retrieveFile);
}
// Allow source maps to be found by methods other than reading the files
// directly from disk.
if (options.retrieveSourceMap) {
if (options.overrideRetrieveSourceMap) {
retrieveMapHandlers.length = 0;
}
retrieveMapHandlers.unshift(options.retrieveSourceMap);
}
// Support runtime transpilers that include inline source maps
if (options.hookRequire && !isInBrowser()) {
var Module;
try {
Module = require('module');
} catch (err) {
// NOP: Loading in catch block to convert webpack error to warning.
}
var $compile = Module.prototype._compile;
if (!$compile.__sourceMapSupport) {
Module.prototype._compile = function(content, filename) {
fileContentsCache[filename] = content;
sourceMapCache[filename] = undefined;
return $compile.call(this, content, filename);
};
Module.prototype._compile.__sourceMapSupport = true;
}
}
// Configure options
if (!emptyCacheBetweenOperations) {
emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
options.emptyCacheBetweenOperations : false;
}
// Install the error reformatter
if (!errorFormatterInstalled) {
errorFormatterInstalled = true;
Error.prepareStackTrace = prepareStackTrace;
}
if (!uncaughtShimInstalled) {
var installHandler = 'handleUncaughtExceptions' in options ?
options.handleUncaughtExceptions : true;
// Provide the option to not install the uncaught exception handler. This is
// to support other uncaught exception handlers (in test frameworks, for
// example). If this handler is not installed and there are no other uncaught
// exception handlers, uncaught exceptions will be caught by node's built-in
// exception handler and the process will still be terminated. However, the
// generated JavaScript code will be shown above the stack trace instead of
// the original source code.
if (installHandler && hasGlobalProcessEventEmitter()) {
uncaughtShimInstalled = true;
shimEmitUncaughtException();
}
}
};

View File

@ -1,3 +0,0 @@
src
test
node_modules

View File

@ -1,33 +0,0 @@
# babel-traverse
> babel-traverse maintains the overall tree state, and is responsible for replacing, removing, and adding nodes.
## Install
```sh
$ npm install --save babel-traverse
```
## Usage
We can use it alongside Babylon to traverse and update nodes:
```js
import * as babylon from "babylon";
import traverse from "babel-traverse";
const code = `function square(n) {
return n * n;
}`;
const ast = babylon.parse(code);
traverse(ast, {
enter(path) {
if (path.isIdentifier({ name: "n" })) {
path.node.name = "x";
}
}
});
```
[:book: **Read the full docs here**](https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-traverse)

View File

@ -1,30 +0,0 @@
"use strict";
exports.__esModule = true;
exports.scope = exports.path = undefined;
var _weakMap = require("babel-runtime/core-js/weak-map");
var _weakMap2 = _interopRequireDefault(_weakMap);
exports.clear = clear;
exports.clearPath = clearPath;
exports.clearScope = clearScope;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var path = exports.path = new _weakMap2.default();
var scope = exports.scope = new _weakMap2.default();
function clear() {
clearPath();
clearScope();
}
function clearPath() {
exports.path = path = new _weakMap2.default();
}
function clearScope() {
exports.scope = scope = new _weakMap2.default();
}

View File

@ -1,200 +0,0 @@
"use strict";
exports.__esModule = true;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _path2 = require("./path");
var _path3 = _interopRequireDefault(_path2);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var testing = process.env.NODE_ENV === "test";
var TraversalContext = function () {
function TraversalContext(scope, opts, state, parentPath) {
(0, _classCallCheck3.default)(this, TraversalContext);
this.queue = null;
this.parentPath = parentPath;
this.scope = scope;
this.state = state;
this.opts = opts;
}
TraversalContext.prototype.shouldVisit = function shouldVisit(node) {
var opts = this.opts;
if (opts.enter || opts.exit) return true;
if (opts[node.type]) return true;
var keys = t.VISITOR_KEYS[node.type];
if (!keys || !keys.length) return false;
for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var key = _ref;
if (node[key]) return true;
}
return false;
};
TraversalContext.prototype.create = function create(node, obj, key, listKey) {
return _path3.default.get({
parentPath: this.parentPath,
parent: node,
container: obj,
key: key,
listKey: listKey
});
};
TraversalContext.prototype.maybeQueue = function maybeQueue(path, notPriority) {
if (this.trap) {
throw new Error("Infinite cycle detected");
}
if (this.queue) {
if (notPriority) {
this.queue.push(path);
} else {
this.priorityQueue.push(path);
}
}
};
TraversalContext.prototype.visitMultiple = function visitMultiple(container, parent, listKey) {
if (container.length === 0) return false;
var queue = [];
for (var key = 0; key < container.length; key++) {
var node = container[key];
if (node && this.shouldVisit(node)) {
queue.push(this.create(parent, container, key, listKey));
}
}
return this.visitQueue(queue);
};
TraversalContext.prototype.visitSingle = function visitSingle(node, key) {
if (this.shouldVisit(node[key])) {
return this.visitQueue([this.create(node, node, key)]);
} else {
return false;
}
};
TraversalContext.prototype.visitQueue = function visitQueue(queue) {
this.queue = queue;
this.priorityQueue = [];
var visited = [];
var stop = false;
for (var _iterator2 = queue, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var path = _ref2;
path.resync();
if (path.contexts.length === 0 || path.contexts[path.contexts.length - 1] !== this) {
path.pushContext(this);
}
if (path.key === null) continue;
if (testing && queue.length >= 10000) {
this.trap = true;
}
if (visited.indexOf(path.node) >= 0) continue;
visited.push(path.node);
if (path.visit()) {
stop = true;
break;
}
if (this.priorityQueue.length) {
stop = this.visitQueue(this.priorityQueue);
this.priorityQueue = [];
this.queue = queue;
if (stop) break;
}
}
for (var _iterator3 = queue, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var _path = _ref3;
_path.popContext();
}
this.queue = null;
return stop;
};
TraversalContext.prototype.visit = function visit(node, key) {
var nodes = node[key];
if (!nodes) return false;
if (Array.isArray(nodes)) {
return this.visitMultiple(nodes, node, key);
} else {
return this.visitSingle(node, key);
}
};
return TraversalContext;
}();
exports.default = TraversalContext;
module.exports = exports["default"];

View File

@ -1,19 +0,0 @@
"use strict";
exports.__esModule = true;
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Hub = function Hub(file, options) {
(0, _classCallCheck3.default)(this, Hub);
this.file = file;
this.options = options;
};
exports.default = Hub;
module.exports = exports["default"];

View File

@ -1,165 +0,0 @@
"use strict";
exports.__esModule = true;
exports.visitors = exports.Hub = exports.Scope = exports.NodePath = undefined;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _path = require("./path");
Object.defineProperty(exports, "NodePath", {
enumerable: true,
get: function get() {
return _interopRequireDefault(_path).default;
}
});
var _scope = require("./scope");
Object.defineProperty(exports, "Scope", {
enumerable: true,
get: function get() {
return _interopRequireDefault(_scope).default;
}
});
var _hub = require("./hub");
Object.defineProperty(exports, "Hub", {
enumerable: true,
get: function get() {
return _interopRequireDefault(_hub).default;
}
});
exports.default = traverse;
var _context = require("./context");
var _context2 = _interopRequireDefault(_context);
var _visitors = require("./visitors");
var visitors = _interopRequireWildcard(_visitors);
var _babelMessages = require("babel-messages");
var messages = _interopRequireWildcard(_babelMessages);
var _includes = require("lodash/includes");
var _includes2 = _interopRequireDefault(_includes);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var _cache = require("./cache");
var cache = _interopRequireWildcard(_cache);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.visitors = visitors;
function traverse(parent, opts, scope, state, parentPath) {
if (!parent) return;
if (!opts) opts = {};
if (!opts.noScope && !scope) {
if (parent.type !== "Program" && parent.type !== "File") {
throw new Error(messages.get("traverseNeedsParent", parent.type));
}
}
visitors.explode(opts);
traverse.node(parent, opts, scope, state, parentPath);
}
traverse.visitors = visitors;
traverse.verify = visitors.verify;
traverse.explode = visitors.explode;
traverse.NodePath = require("./path");
traverse.Scope = require("./scope");
traverse.Hub = require("./hub");
traverse.cheap = function (node, enter) {
return t.traverseFast(node, enter);
};
traverse.node = function (node, opts, scope, state, parentPath, skipKeys) {
var keys = t.VISITOR_KEYS[node.type];
if (!keys) return;
var context = new _context2.default(scope, opts, state, parentPath);
for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var key = _ref;
if (skipKeys && skipKeys[key]) continue;
if (context.visit(node, key)) return;
}
};
traverse.clearNode = function (node, opts) {
t.removeProperties(node, opts);
cache.path.delete(node);
};
traverse.removeProperties = function (tree, opts) {
t.traverseFast(tree, traverse.clearNode, opts);
return tree;
};
function hasBlacklistedType(path, state) {
if (path.node.type === state.type) {
state.has = true;
path.stop();
}
}
traverse.hasType = function (tree, scope, type, blacklistTypes) {
if ((0, _includes2.default)(blacklistTypes, tree.type)) return false;
if (tree.type === type) return true;
var state = {
has: false,
type: type
};
traverse(tree, {
blacklist: blacklistTypes,
enter: hasBlacklistedType
}, scope, state);
return state.has;
};
traverse.clearCache = function () {
cache.clear();
};
traverse.clearCache.clearPath = cache.clearPath;
traverse.clearCache.clearScope = cache.clearScope;
traverse.copyCache = function (source, destination) {
if (cache.path.has(source)) {
cache.path.set(destination, cache.path.get(source));
}
};

View File

@ -1,238 +0,0 @@
"use strict";
exports.__esModule = true;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
exports.findParent = findParent;
exports.find = find;
exports.getFunctionParent = getFunctionParent;
exports.getStatementParent = getStatementParent;
exports.getEarliestCommonAncestorFrom = getEarliestCommonAncestorFrom;
exports.getDeepestCommonAncestorFrom = getDeepestCommonAncestorFrom;
exports.getAncestry = getAncestry;
exports.isAncestor = isAncestor;
exports.isDescendant = isDescendant;
exports.inType = inType;
exports.inShadow = inShadow;
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var _index = require("./index");
var _index2 = _interopRequireDefault(_index);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function findParent(callback) {
var path = this;
while (path = path.parentPath) {
if (callback(path)) return path;
}
return null;
}
function find(callback) {
var path = this;
do {
if (callback(path)) return path;
} while (path = path.parentPath);
return null;
}
function getFunctionParent() {
return this.findParent(function (path) {
return path.isFunction() || path.isProgram();
});
}
function getStatementParent() {
var path = this;
do {
if (Array.isArray(path.container)) {
return path;
}
} while (path = path.parentPath);
}
function getEarliestCommonAncestorFrom(paths) {
return this.getDeepestCommonAncestorFrom(paths, function (deepest, i, ancestries) {
var earliest = void 0;
var keys = t.VISITOR_KEYS[deepest.type];
for (var _iterator = ancestries, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var ancestry = _ref;
var path = ancestry[i + 1];
if (!earliest) {
earliest = path;
continue;
}
if (path.listKey && earliest.listKey === path.listKey) {
if (path.key < earliest.key) {
earliest = path;
continue;
}
}
var earliestKeyIndex = keys.indexOf(earliest.parentKey);
var currentKeyIndex = keys.indexOf(path.parentKey);
if (earliestKeyIndex > currentKeyIndex) {
earliest = path;
}
}
return earliest;
});
}
function getDeepestCommonAncestorFrom(paths, filter) {
var _this = this;
if (!paths.length) {
return this;
}
if (paths.length === 1) {
return paths[0];
}
var minDepth = Infinity;
var lastCommonIndex = void 0,
lastCommon = void 0;
var ancestries = paths.map(function (path) {
var ancestry = [];
do {
ancestry.unshift(path);
} while ((path = path.parentPath) && path !== _this);
if (ancestry.length < minDepth) {
minDepth = ancestry.length;
}
return ancestry;
});
var first = ancestries[0];
depthLoop: for (var i = 0; i < minDepth; i++) {
var shouldMatch = first[i];
for (var _iterator2 = ancestries, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var ancestry = _ref2;
if (ancestry[i] !== shouldMatch) {
break depthLoop;
}
}
lastCommonIndex = i;
lastCommon = shouldMatch;
}
if (lastCommon) {
if (filter) {
return filter(lastCommon, lastCommonIndex, ancestries);
} else {
return lastCommon;
}
} else {
throw new Error("Couldn't find intersection");
}
}
function getAncestry() {
var path = this;
var paths = [];
do {
paths.push(path);
} while (path = path.parentPath);
return paths;
}
function isAncestor(maybeDescendant) {
return maybeDescendant.isDescendant(this);
}
function isDescendant(maybeAncestor) {
return !!this.findParent(function (parent) {
return parent === maybeAncestor;
});
}
function inType() {
var path = this;
while (path) {
for (var _iterator3 = arguments, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var type = _ref3;
if (path.node.type === type) return true;
}
path = path.parentPath;
}
return false;
}
function inShadow(key) {
var parentFn = this.isFunction() ? this : this.findParent(function (p) {
return p.isFunction();
});
if (!parentFn) return;
if (parentFn.isFunctionExpression() || parentFn.isFunctionDeclaration()) {
var shadow = parentFn.node.shadow;
if (shadow && (!key || shadow[key] !== false)) {
return parentFn;
}
} else if (parentFn.isArrowFunctionExpression()) {
return parentFn;
}
return null;
}

View File

@ -1,47 +0,0 @@
"use strict";
exports.__esModule = true;
exports.shareCommentsWithSiblings = shareCommentsWithSiblings;
exports.addComment = addComment;
exports.addComments = addComments;
function shareCommentsWithSiblings() {
if (typeof this.key === "string") return;
var node = this.node;
if (!node) return;
var trailing = node.trailingComments;
var leading = node.leadingComments;
if (!trailing && !leading) return;
var prev = this.getSibling(this.key - 1);
var next = this.getSibling(this.key + 1);
if (!prev.node) prev = next;
if (!next.node) next = prev;
prev.addComments("trailing", leading);
next.addComments("leading", trailing);
}
function addComment(type, content, line) {
this.addComments(type, [{
type: line ? "CommentLine" : "CommentBlock",
value: content
}]);
}
function addComments(type, comments) {
if (!comments) return;
var node = this.node;
if (!node) return;
var key = type + "Comments";
if (node[key]) {
node[key] = node[key].concat(comments);
} else {
node[key] = comments;
}
}

View File

@ -1,281 +0,0 @@
"use strict";
exports.__esModule = true;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
exports.call = call;
exports._call = _call;
exports.isBlacklisted = isBlacklisted;
exports.visit = visit;
exports.skip = skip;
exports.skipKey = skipKey;
exports.stop = stop;
exports.setScope = setScope;
exports.setContext = setContext;
exports.resync = resync;
exports._resyncParent = _resyncParent;
exports._resyncKey = _resyncKey;
exports._resyncList = _resyncList;
exports._resyncRemoved = _resyncRemoved;
exports.popContext = popContext;
exports.pushContext = pushContext;
exports.setup = setup;
exports.setKey = setKey;
exports.requeue = requeue;
exports._getQueueContexts = _getQueueContexts;
var _index = require("../index");
var _index2 = _interopRequireDefault(_index);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function call(key) {
var opts = this.opts;
this.debug(function () {
return key;
});
if (this.node) {
if (this._call(opts[key])) return true;
}
if (this.node) {
return this._call(opts[this.node.type] && opts[this.node.type][key]);
}
return false;
}
function _call(fns) {
if (!fns) return false;
for (var _iterator = fns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var fn = _ref;
if (!fn) continue;
var node = this.node;
if (!node) return true;
var ret = fn.call(this.state, this, this.state);
if (ret) throw new Error("Unexpected return value from visitor method " + fn);
if (this.node !== node) return true;
if (this.shouldStop || this.shouldSkip || this.removed) return true;
}
return false;
}
function isBlacklisted() {
var blacklist = this.opts.blacklist;
return blacklist && blacklist.indexOf(this.node.type) > -1;
}
function visit() {
if (!this.node) {
return false;
}
if (this.isBlacklisted()) {
return false;
}
if (this.opts.shouldSkip && this.opts.shouldSkip(this)) {
return false;
}
if (this.call("enter") || this.shouldSkip) {
this.debug(function () {
return "Skip...";
});
return this.shouldStop;
}
this.debug(function () {
return "Recursing into...";
});
_index2.default.node(this.node, this.opts, this.scope, this.state, this, this.skipKeys);
this.call("exit");
return this.shouldStop;
}
function skip() {
this.shouldSkip = true;
}
function skipKey(key) {
this.skipKeys[key] = true;
}
function stop() {
this.shouldStop = true;
this.shouldSkip = true;
}
function setScope() {
if (this.opts && this.opts.noScope) return;
var target = this.context && this.context.scope;
if (!target) {
var path = this.parentPath;
while (path && !target) {
if (path.opts && path.opts.noScope) return;
target = path.scope;
path = path.parentPath;
}
}
this.scope = this.getScope(target);
if (this.scope) this.scope.init();
}
function setContext(context) {
this.shouldSkip = false;
this.shouldStop = false;
this.removed = false;
this.skipKeys = {};
if (context) {
this.context = context;
this.state = context.state;
this.opts = context.opts;
}
this.setScope();
return this;
}
function resync() {
if (this.removed) return;
this._resyncParent();
this._resyncList();
this._resyncKey();
}
function _resyncParent() {
if (this.parentPath) {
this.parent = this.parentPath.node;
}
}
function _resyncKey() {
if (!this.container) return;
if (this.node === this.container[this.key]) return;
if (Array.isArray(this.container)) {
for (var i = 0; i < this.container.length; i++) {
if (this.container[i] === this.node) {
return this.setKey(i);
}
}
} else {
for (var key in this.container) {
if (this.container[key] === this.node) {
return this.setKey(key);
}
}
}
this.key = null;
}
function _resyncList() {
if (!this.parent || !this.inList) return;
var newContainer = this.parent[this.listKey];
if (this.container === newContainer) return;
this.container = newContainer || null;
}
function _resyncRemoved() {
if (this.key == null || !this.container || this.container[this.key] !== this.node) {
this._markRemoved();
}
}
function popContext() {
this.contexts.pop();
this.setContext(this.contexts[this.contexts.length - 1]);
}
function pushContext(context) {
this.contexts.push(context);
this.setContext(context);
}
function setup(parentPath, container, listKey, key) {
this.inList = !!listKey;
this.listKey = listKey;
this.parentKey = listKey || key;
this.container = container;
this.parentPath = parentPath || this.parentPath;
this.setKey(key);
}
function setKey(key) {
this.key = key;
this.node = this.container[this.key];
this.type = this.node && this.node.type;
}
function requeue() {
var pathToQueue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this;
if (pathToQueue.removed) return;
var contexts = this.contexts;
for (var _iterator2 = contexts, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var context = _ref2;
context.maybeQueue(pathToQueue);
}
}
function _getQueueContexts() {
var path = this;
var contexts = this.contexts;
while (!contexts.length) {
path = path.parentPath;
contexts = path.contexts;
}
return contexts;
}

View File

@ -1,47 +0,0 @@
"use strict";
exports.__esModule = true;
exports.toComputedKey = toComputedKey;
exports.ensureBlock = ensureBlock;
exports.arrowFunctionToShadowed = arrowFunctionToShadowed;
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function toComputedKey() {
var node = this.node;
var key = void 0;
if (this.isMemberExpression()) {
key = node.property;
} else if (this.isProperty() || this.isMethod()) {
key = node.key;
} else {
throw new ReferenceError("todo");
}
if (!node.computed) {
if (t.isIdentifier(key)) key = t.stringLiteral(key.name);
}
return key;
}
function ensureBlock() {
return t.ensureBlock(this.node);
}
function arrowFunctionToShadowed() {
if (!this.isArrowFunctionExpression()) return;
this.ensureBlock();
var node = this.node;
node.expression = false;
node.type = "FunctionExpression";
node.shadow = node.shadow || true;
}

View File

@ -1,398 +0,0 @@
"use strict";
exports.__esModule = true;
var _typeof2 = require("babel-runtime/helpers/typeof");
var _typeof3 = _interopRequireDefault(_typeof2);
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _map = require("babel-runtime/core-js/map");
var _map2 = _interopRequireDefault(_map);
exports.evaluateTruthy = evaluateTruthy;
exports.evaluate = evaluate;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var VALID_CALLEES = ["String", "Number", "Math"];
var INVALID_METHODS = ["random"];
function evaluateTruthy() {
var res = this.evaluate();
if (res.confident) return !!res.value;
}
function evaluate() {
var confident = true;
var deoptPath = void 0;
var seen = new _map2.default();
function deopt(path) {
if (!confident) return;
deoptPath = path;
confident = false;
}
var value = evaluate(this);
if (!confident) value = undefined;
return {
confident: confident,
deopt: deoptPath,
value: value
};
function evaluate(path) {
var node = path.node;
if (seen.has(node)) {
var existing = seen.get(node);
if (existing.resolved) {
return existing.value;
} else {
deopt(path);
return;
}
} else {
var item = { resolved: false };
seen.set(node, item);
var val = _evaluate(path);
if (confident) {
item.resolved = true;
item.value = val;
}
return val;
}
}
function _evaluate(path) {
if (!confident) return;
var node = path.node;
if (path.isSequenceExpression()) {
var exprs = path.get("expressions");
return evaluate(exprs[exprs.length - 1]);
}
if (path.isStringLiteral() || path.isNumericLiteral() || path.isBooleanLiteral()) {
return node.value;
}
if (path.isNullLiteral()) {
return null;
}
if (path.isTemplateLiteral()) {
var str = "";
var i = 0;
var _exprs = path.get("expressions");
for (var _iterator = node.quasis, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var elem = _ref;
if (!confident) break;
str += elem.value.cooked;
var expr = _exprs[i++];
if (expr) str += String(evaluate(expr));
}
if (!confident) return;
return str;
}
if (path.isConditionalExpression()) {
var testResult = evaluate(path.get("test"));
if (!confident) return;
if (testResult) {
return evaluate(path.get("consequent"));
} else {
return evaluate(path.get("alternate"));
}
}
if (path.isExpressionWrapper()) {
return evaluate(path.get("expression"));
}
if (path.isMemberExpression() && !path.parentPath.isCallExpression({ callee: node })) {
var property = path.get("property");
var object = path.get("object");
if (object.isLiteral() && property.isIdentifier()) {
var _value = object.node.value;
var type = typeof _value === "undefined" ? "undefined" : (0, _typeof3.default)(_value);
if (type === "number" || type === "string") {
return _value[property.node.name];
}
}
}
if (path.isReferencedIdentifier()) {
var binding = path.scope.getBinding(node.name);
if (binding && binding.constantViolations.length > 0) {
return deopt(binding.path);
}
if (binding && path.node.start < binding.path.node.end) {
return deopt(binding.path);
}
if (binding && binding.hasValue) {
return binding.value;
} else {
if (node.name === "undefined") {
return binding ? deopt(binding.path) : undefined;
} else if (node.name === "Infinity") {
return binding ? deopt(binding.path) : Infinity;
} else if (node.name === "NaN") {
return binding ? deopt(binding.path) : NaN;
}
var resolved = path.resolve();
if (resolved === path) {
return deopt(path);
} else {
return evaluate(resolved);
}
}
}
if (path.isUnaryExpression({ prefix: true })) {
if (node.operator === "void") {
return undefined;
}
var argument = path.get("argument");
if (node.operator === "typeof" && (argument.isFunction() || argument.isClass())) {
return "function";
}
var arg = evaluate(argument);
if (!confident) return;
switch (node.operator) {
case "!":
return !arg;
case "+":
return +arg;
case "-":
return -arg;
case "~":
return ~arg;
case "typeof":
return typeof arg === "undefined" ? "undefined" : (0, _typeof3.default)(arg);
}
}
if (path.isArrayExpression()) {
var arr = [];
var elems = path.get("elements");
for (var _iterator2 = elems, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var _elem = _ref2;
_elem = _elem.evaluate();
if (_elem.confident) {
arr.push(_elem.value);
} else {
return deopt(_elem);
}
}
return arr;
}
if (path.isObjectExpression()) {
var obj = {};
var props = path.get("properties");
for (var _iterator3 = props, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var prop = _ref3;
if (prop.isObjectMethod() || prop.isSpreadProperty()) {
return deopt(prop);
}
var keyPath = prop.get("key");
var key = keyPath;
if (prop.node.computed) {
key = key.evaluate();
if (!key.confident) {
return deopt(keyPath);
}
key = key.value;
} else if (key.isIdentifier()) {
key = key.node.name;
} else {
key = key.node.value;
}
var valuePath = prop.get("value");
var _value2 = valuePath.evaluate();
if (!_value2.confident) {
return deopt(valuePath);
}
_value2 = _value2.value;
obj[key] = _value2;
}
return obj;
}
if (path.isLogicalExpression()) {
var wasConfident = confident;
var left = evaluate(path.get("left"));
var leftConfident = confident;
confident = wasConfident;
var right = evaluate(path.get("right"));
var rightConfident = confident;
confident = leftConfident && rightConfident;
switch (node.operator) {
case "||":
if (left && leftConfident) {
confident = true;
return left;
}
if (!confident) return;
return left || right;
case "&&":
if (!left && leftConfident || !right && rightConfident) {
confident = true;
}
if (!confident) return;
return left && right;
}
}
if (path.isBinaryExpression()) {
var _left = evaluate(path.get("left"));
if (!confident) return;
var _right = evaluate(path.get("right"));
if (!confident) return;
switch (node.operator) {
case "-":
return _left - _right;
case "+":
return _left + _right;
case "/":
return _left / _right;
case "*":
return _left * _right;
case "%":
return _left % _right;
case "**":
return Math.pow(_left, _right);
case "<":
return _left < _right;
case ">":
return _left > _right;
case "<=":
return _left <= _right;
case ">=":
return _left >= _right;
case "==":
return _left == _right;
case "!=":
return _left != _right;
case "===":
return _left === _right;
case "!==":
return _left !== _right;
case "|":
return _left | _right;
case "&":
return _left & _right;
case "^":
return _left ^ _right;
case "<<":
return _left << _right;
case ">>":
return _left >> _right;
case ">>>":
return _left >>> _right;
}
}
if (path.isCallExpression()) {
var callee = path.get("callee");
var context = void 0;
var func = void 0;
if (callee.isIdentifier() && !path.scope.getBinding(callee.node.name, true) && VALID_CALLEES.indexOf(callee.node.name) >= 0) {
func = global[node.callee.name];
}
if (callee.isMemberExpression()) {
var _object = callee.get("object");
var _property = callee.get("property");
if (_object.isIdentifier() && _property.isIdentifier() && VALID_CALLEES.indexOf(_object.node.name) >= 0 && INVALID_METHODS.indexOf(_property.node.name) < 0) {
context = global[_object.node.name];
func = context[_property.node.name];
}
if (_object.isLiteral() && _property.isIdentifier()) {
var _type = (0, _typeof3.default)(_object.node.value);
if (_type === "string" || _type === "number") {
context = _object.node.value;
func = context[_property.node.name];
}
}
}
if (func) {
var args = path.get("arguments").map(evaluate);
if (!confident) return;
return func.apply(context, args);
}
}
deopt(path);
}
}

View File

@ -1,266 +0,0 @@
"use strict";
exports.__esModule = true;
var _create = require("babel-runtime/core-js/object/create");
var _create2 = _interopRequireDefault(_create);
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
exports.getStatementParent = getStatementParent;
exports.getOpposite = getOpposite;
exports.getCompletionRecords = getCompletionRecords;
exports.getSibling = getSibling;
exports.getPrevSibling = getPrevSibling;
exports.getNextSibling = getNextSibling;
exports.getAllNextSiblings = getAllNextSiblings;
exports.getAllPrevSiblings = getAllPrevSiblings;
exports.get = get;
exports._getKey = _getKey;
exports._getPattern = _getPattern;
exports.getBindingIdentifiers = getBindingIdentifiers;
exports.getOuterBindingIdentifiers = getOuterBindingIdentifiers;
exports.getBindingIdentifierPaths = getBindingIdentifierPaths;
exports.getOuterBindingIdentifierPaths = getOuterBindingIdentifierPaths;
var _index = require("./index");
var _index2 = _interopRequireDefault(_index);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getStatementParent() {
var path = this;
do {
if (!path.parentPath || Array.isArray(path.container) && path.isStatement()) {
break;
} else {
path = path.parentPath;
}
} while (path);
if (path && (path.isProgram() || path.isFile())) {
throw new Error("File/Program node, we can't possibly find a statement parent to this");
}
return path;
}
function getOpposite() {
if (this.key === "left") {
return this.getSibling("right");
} else if (this.key === "right") {
return this.getSibling("left");
}
}
function getCompletionRecords() {
var paths = [];
var add = function add(path) {
if (path) paths = paths.concat(path.getCompletionRecords());
};
if (this.isIfStatement()) {
add(this.get("consequent"));
add(this.get("alternate"));
} else if (this.isDoExpression() || this.isFor() || this.isWhile()) {
add(this.get("body"));
} else if (this.isProgram() || this.isBlockStatement()) {
add(this.get("body").pop());
} else if (this.isFunction()) {
return this.get("body").getCompletionRecords();
} else if (this.isTryStatement()) {
add(this.get("block"));
add(this.get("handler"));
add(this.get("finalizer"));
} else {
paths.push(this);
}
return paths;
}
function getSibling(key) {
return _index2.default.get({
parentPath: this.parentPath,
parent: this.parent,
container: this.container,
listKey: this.listKey,
key: key
});
}
function getPrevSibling() {
return this.getSibling(this.key - 1);
}
function getNextSibling() {
return this.getSibling(this.key + 1);
}
function getAllNextSiblings() {
var _key = this.key;
var sibling = this.getSibling(++_key);
var siblings = [];
while (sibling.node) {
siblings.push(sibling);
sibling = this.getSibling(++_key);
}
return siblings;
}
function getAllPrevSiblings() {
var _key = this.key;
var sibling = this.getSibling(--_key);
var siblings = [];
while (sibling.node) {
siblings.push(sibling);
sibling = this.getSibling(--_key);
}
return siblings;
}
function get(key, context) {
if (context === true) context = this.context;
var parts = key.split(".");
if (parts.length === 1) {
return this._getKey(key, context);
} else {
return this._getPattern(parts, context);
}
}
function _getKey(key, context) {
var _this = this;
var node = this.node;
var container = node[key];
if (Array.isArray(container)) {
return container.map(function (_, i) {
return _index2.default.get({
listKey: key,
parentPath: _this,
parent: node,
container: container,
key: i
}).setContext(context);
});
} else {
return _index2.default.get({
parentPath: this,
parent: node,
container: node,
key: key
}).setContext(context);
}
}
function _getPattern(parts, context) {
var path = this;
for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var part = _ref;
if (part === ".") {
path = path.parentPath;
} else {
if (Array.isArray(path)) {
path = path[part];
} else {
path = path.get(part, context);
}
}
}
return path;
}
function getBindingIdentifiers(duplicates) {
return t.getBindingIdentifiers(this.node, duplicates);
}
function getOuterBindingIdentifiers(duplicates) {
return t.getOuterBindingIdentifiers(this.node, duplicates);
}
function getBindingIdentifierPaths() {
var duplicates = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var outerOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var path = this;
var search = [].concat(path);
var ids = (0, _create2.default)(null);
while (search.length) {
var id = search.shift();
if (!id) continue;
if (!id.node) continue;
var keys = t.getBindingIdentifiers.keys[id.node.type];
if (id.isIdentifier()) {
if (duplicates) {
var _ids = ids[id.node.name] = ids[id.node.name] || [];
_ids.push(id);
} else {
ids[id.node.name] = id;
}
continue;
}
if (id.isExportDeclaration()) {
var declaration = id.get("declaration");
if (declaration.isDeclaration()) {
search.push(declaration);
}
continue;
}
if (outerOnly) {
if (id.isFunctionDeclaration()) {
search.push(id.get("id"));
continue;
}
if (id.isFunctionExpression()) {
continue;
}
}
if (keys) {
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var child = id.get(key);
if (Array.isArray(child) || child.node) {
search = search.concat(child);
}
}
}
}
return ids;
}
function getOuterBindingIdentifierPaths(duplicates) {
return this.getBindingIdentifierPaths(duplicates, true);
}

View File

@ -1,242 +0,0 @@
"use strict";
exports.__esModule = true;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _virtualTypes = require("./lib/virtual-types");
var virtualTypes = _interopRequireWildcard(_virtualTypes);
var _debug2 = require("debug");
var _debug3 = _interopRequireDefault(_debug2);
var _invariant = require("invariant");
var _invariant2 = _interopRequireDefault(_invariant);
var _index = require("../index");
var _index2 = _interopRequireDefault(_index);
var _assign = require("lodash/assign");
var _assign2 = _interopRequireDefault(_assign);
var _scope = require("../scope");
var _scope2 = _interopRequireDefault(_scope);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var _cache = require("../cache");
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _debug = (0, _debug3.default)("babel");
var NodePath = function () {
function NodePath(hub, parent) {
(0, _classCallCheck3.default)(this, NodePath);
this.parent = parent;
this.hub = hub;
this.contexts = [];
this.data = {};
this.shouldSkip = false;
this.shouldStop = false;
this.removed = false;
this.state = null;
this.opts = null;
this.skipKeys = null;
this.parentPath = null;
this.context = null;
this.container = null;
this.listKey = null;
this.inList = false;
this.parentKey = null;
this.key = null;
this.node = null;
this.scope = null;
this.type = null;
this.typeAnnotation = null;
}
NodePath.get = function get(_ref) {
var hub = _ref.hub,
parentPath = _ref.parentPath,
parent = _ref.parent,
container = _ref.container,
listKey = _ref.listKey,
key = _ref.key;
if (!hub && parentPath) {
hub = parentPath.hub;
}
(0, _invariant2.default)(parent, "To get a node path the parent needs to exist");
var targetNode = container[key];
var paths = _cache.path.get(parent) || [];
if (!_cache.path.has(parent)) {
_cache.path.set(parent, paths);
}
var path = void 0;
for (var i = 0; i < paths.length; i++) {
var pathCheck = paths[i];
if (pathCheck.node === targetNode) {
path = pathCheck;
break;
}
}
if (!path) {
path = new NodePath(hub, parent);
paths.push(path);
}
path.setup(parentPath, container, listKey, key);
return path;
};
NodePath.prototype.getScope = function getScope(scope) {
var ourScope = scope;
if (this.isScope()) {
ourScope = new _scope2.default(this, scope);
}
return ourScope;
};
NodePath.prototype.setData = function setData(key, val) {
return this.data[key] = val;
};
NodePath.prototype.getData = function getData(key, def) {
var val = this.data[key];
if (!val && def) val = this.data[key] = def;
return val;
};
NodePath.prototype.buildCodeFrameError = function buildCodeFrameError(msg) {
var Error = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : SyntaxError;
return this.hub.file.buildCodeFrameError(this.node, msg, Error);
};
NodePath.prototype.traverse = function traverse(visitor, state) {
(0, _index2.default)(this.node, visitor, this.scope, state, this);
};
NodePath.prototype.mark = function mark(type, message) {
this.hub.file.metadata.marked.push({
type: type,
message: message,
loc: this.node.loc
});
};
NodePath.prototype.set = function set(key, node) {
t.validate(this.node, key, node);
this.node[key] = node;
};
NodePath.prototype.getPathLocation = function getPathLocation() {
var parts = [];
var path = this;
do {
var key = path.key;
if (path.inList) key = path.listKey + "[" + key + "]";
parts.unshift(key);
} while (path = path.parentPath);
return parts.join(".");
};
NodePath.prototype.debug = function debug(buildMessage) {
if (!_debug.enabled) return;
_debug(this.getPathLocation() + " " + this.type + ": " + buildMessage());
};
return NodePath;
}();
exports.default = NodePath;
(0, _assign2.default)(NodePath.prototype, require("./ancestry"));
(0, _assign2.default)(NodePath.prototype, require("./inference"));
(0, _assign2.default)(NodePath.prototype, require("./replacement"));
(0, _assign2.default)(NodePath.prototype, require("./evaluation"));
(0, _assign2.default)(NodePath.prototype, require("./conversion"));
(0, _assign2.default)(NodePath.prototype, require("./introspection"));
(0, _assign2.default)(NodePath.prototype, require("./context"));
(0, _assign2.default)(NodePath.prototype, require("./removal"));
(0, _assign2.default)(NodePath.prototype, require("./modification"));
(0, _assign2.default)(NodePath.prototype, require("./family"));
(0, _assign2.default)(NodePath.prototype, require("./comments"));
var _loop2 = function _loop2() {
if (_isArray) {
if (_i >= _iterator.length) return "break";
_ref2 = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) return "break";
_ref2 = _i.value;
}
var type = _ref2;
var typeKey = "is" + type;
NodePath.prototype[typeKey] = function (opts) {
return t[typeKey](this.node, opts);
};
NodePath.prototype["assert" + type] = function (opts) {
if (!this[typeKey](opts)) {
throw new TypeError("Expected node path of type " + type);
}
};
};
for (var _iterator = t.TYPES, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref2;
var _ret2 = _loop2();
if (_ret2 === "break") break;
}
var _loop = function _loop(type) {
if (type[0] === "_") return "continue";
if (t.TYPES.indexOf(type) < 0) t.TYPES.push(type);
var virtualType = virtualTypes[type];
NodePath.prototype["is" + type] = function (opts) {
return virtualType.checkPath(this, opts);
};
};
for (var type in virtualTypes) {
var _ret = _loop(type);
if (_ret === "continue") continue;
}
module.exports = exports["default"];

View File

@ -1,142 +0,0 @@
"use strict";
exports.__esModule = true;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
exports.getTypeAnnotation = getTypeAnnotation;
exports._getTypeAnnotation = _getTypeAnnotation;
exports.isBaseType = isBaseType;
exports.couldBeBaseType = couldBeBaseType;
exports.baseTypeStrictlyMatches = baseTypeStrictlyMatches;
exports.isGenericType = isGenericType;
var _inferers = require("./inferers");
var inferers = _interopRequireWildcard(_inferers);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getTypeAnnotation() {
if (this.typeAnnotation) return this.typeAnnotation;
var type = this._getTypeAnnotation() || t.anyTypeAnnotation();
if (t.isTypeAnnotation(type)) type = type.typeAnnotation;
return this.typeAnnotation = type;
}
function _getTypeAnnotation() {
var node = this.node;
if (!node) {
if (this.key === "init" && this.parentPath.isVariableDeclarator()) {
var declar = this.parentPath.parentPath;
var declarParent = declar.parentPath;
if (declar.key === "left" && declarParent.isForInStatement()) {
return t.stringTypeAnnotation();
}
if (declar.key === "left" && declarParent.isForOfStatement()) {
return t.anyTypeAnnotation();
}
return t.voidTypeAnnotation();
} else {
return;
}
}
if (node.typeAnnotation) {
return node.typeAnnotation;
}
var inferer = inferers[node.type];
if (inferer) {
return inferer.call(this, node);
}
inferer = inferers[this.parentPath.type];
if (inferer && inferer.validParent) {
return this.parentPath.getTypeAnnotation();
}
}
function isBaseType(baseName, soft) {
return _isBaseType(baseName, this.getTypeAnnotation(), soft);
}
function _isBaseType(baseName, type, soft) {
if (baseName === "string") {
return t.isStringTypeAnnotation(type);
} else if (baseName === "number") {
return t.isNumberTypeAnnotation(type);
} else if (baseName === "boolean") {
return t.isBooleanTypeAnnotation(type);
} else if (baseName === "any") {
return t.isAnyTypeAnnotation(type);
} else if (baseName === "mixed") {
return t.isMixedTypeAnnotation(type);
} else if (baseName === "empty") {
return t.isEmptyTypeAnnotation(type);
} else if (baseName === "void") {
return t.isVoidTypeAnnotation(type);
} else {
if (soft) {
return false;
} else {
throw new Error("Unknown base type " + baseName);
}
}
}
function couldBeBaseType(name) {
var type = this.getTypeAnnotation();
if (t.isAnyTypeAnnotation(type)) return true;
if (t.isUnionTypeAnnotation(type)) {
for (var _iterator = type.types, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var type2 = _ref;
if (t.isAnyTypeAnnotation(type2) || _isBaseType(name, type2, true)) {
return true;
}
}
return false;
} else {
return _isBaseType(name, type, true);
}
}
function baseTypeStrictlyMatches(right) {
var left = this.getTypeAnnotation();
right = right.getTypeAnnotation();
if (!t.isAnyTypeAnnotation(left) && t.isFlowBaseAnnotation(left)) {
return right.type === left.type;
}
}
function isGenericType(genericName) {
var type = this.getTypeAnnotation();
return t.isGenericTypeAnnotation(type) && t.isIdentifier(type.id, { name: genericName });
}

View File

@ -1,185 +0,0 @@
"use strict";
exports.__esModule = true;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
exports.default = function (node) {
if (!this.isReferenced()) return;
var binding = this.scope.getBinding(node.name);
if (binding) {
if (binding.identifier.typeAnnotation) {
return binding.identifier.typeAnnotation;
} else {
return getTypeAnnotationBindingConstantViolations(this, node.name);
}
}
if (node.name === "undefined") {
return t.voidTypeAnnotation();
} else if (node.name === "NaN" || node.name === "Infinity") {
return t.numberTypeAnnotation();
} else if (node.name === "arguments") {}
};
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getTypeAnnotationBindingConstantViolations(path, name) {
var binding = path.scope.getBinding(name);
var types = [];
path.typeAnnotation = t.unionTypeAnnotation(types);
var functionConstantViolations = [];
var constantViolations = getConstantViolationsBefore(binding, path, functionConstantViolations);
var testType = getConditionalAnnotation(path, name);
if (testType) {
var testConstantViolations = getConstantViolationsBefore(binding, testType.ifStatement);
constantViolations = constantViolations.filter(function (path) {
return testConstantViolations.indexOf(path) < 0;
});
types.push(testType.typeAnnotation);
}
if (constantViolations.length) {
constantViolations = constantViolations.concat(functionConstantViolations);
for (var _iterator = constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var violation = _ref;
types.push(violation.getTypeAnnotation());
}
}
if (types.length) {
return t.createUnionTypeAnnotation(types);
}
}
function getConstantViolationsBefore(binding, path, functions) {
var violations = binding.constantViolations.slice();
violations.unshift(binding.path);
return violations.filter(function (violation) {
violation = violation.resolve();
var status = violation._guessExecutionStatusRelativeTo(path);
if (functions && status === "function") functions.push(violation);
return status === "before";
});
}
function inferAnnotationFromBinaryExpression(name, path) {
var operator = path.node.operator;
var right = path.get("right").resolve();
var left = path.get("left").resolve();
var target = void 0;
if (left.isIdentifier({ name: name })) {
target = right;
} else if (right.isIdentifier({ name: name })) {
target = left;
}
if (target) {
if (operator === "===") {
return target.getTypeAnnotation();
} else if (t.BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) {
return t.numberTypeAnnotation();
} else {
return;
}
} else {
if (operator !== "===") return;
}
var typeofPath = void 0;
var typePath = void 0;
if (left.isUnaryExpression({ operator: "typeof" })) {
typeofPath = left;
typePath = right;
} else if (right.isUnaryExpression({ operator: "typeof" })) {
typeofPath = right;
typePath = left;
}
if (!typePath && !typeofPath) return;
typePath = typePath.resolve();
if (!typePath.isLiteral()) return;
var typeValue = typePath.node.value;
if (typeof typeValue !== "string") return;
if (!typeofPath.get("argument").isIdentifier({ name: name })) return;
return t.createTypeAnnotationBasedOnTypeof(typePath.node.value);
}
function getParentConditionalPath(path) {
var parentPath = void 0;
while (parentPath = path.parentPath) {
if (parentPath.isIfStatement() || parentPath.isConditionalExpression()) {
if (path.key === "test") {
return;
} else {
return parentPath;
}
} else {
path = parentPath;
}
}
}
function getConditionalAnnotation(path, name) {
var ifStatement = getParentConditionalPath(path);
if (!ifStatement) return;
var test = ifStatement.get("test");
var paths = [test];
var types = [];
do {
var _path = paths.shift().resolve();
if (_path.isLogicalExpression()) {
paths.push(_path.get("left"));
paths.push(_path.get("right"));
}
if (_path.isBinaryExpression()) {
var type = inferAnnotationFromBinaryExpression(name, _path);
if (type) types.push(type);
}
} while (paths.length);
if (types.length) {
return {
typeAnnotation: t.createUnionTypeAnnotation(types),
ifStatement: ifStatement
};
} else {
return getConditionalAnnotation(ifStatement, name);
}
}
module.exports = exports["default"];

View File

@ -1,195 +0,0 @@
"use strict";
exports.__esModule = true;
exports.ClassDeclaration = exports.ClassExpression = exports.FunctionDeclaration = exports.ArrowFunctionExpression = exports.FunctionExpression = exports.Identifier = undefined;
var _infererReference = require("./inferer-reference");
Object.defineProperty(exports, "Identifier", {
enumerable: true,
get: function get() {
return _interopRequireDefault(_infererReference).default;
}
});
exports.VariableDeclarator = VariableDeclarator;
exports.TypeCastExpression = TypeCastExpression;
exports.NewExpression = NewExpression;
exports.TemplateLiteral = TemplateLiteral;
exports.UnaryExpression = UnaryExpression;
exports.BinaryExpression = BinaryExpression;
exports.LogicalExpression = LogicalExpression;
exports.ConditionalExpression = ConditionalExpression;
exports.SequenceExpression = SequenceExpression;
exports.AssignmentExpression = AssignmentExpression;
exports.UpdateExpression = UpdateExpression;
exports.StringLiteral = StringLiteral;
exports.NumericLiteral = NumericLiteral;
exports.BooleanLiteral = BooleanLiteral;
exports.NullLiteral = NullLiteral;
exports.RegExpLiteral = RegExpLiteral;
exports.ObjectExpression = ObjectExpression;
exports.ArrayExpression = ArrayExpression;
exports.RestElement = RestElement;
exports.CallExpression = CallExpression;
exports.TaggedTemplateExpression = TaggedTemplateExpression;
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function VariableDeclarator() {
var id = this.get("id");
if (id.isIdentifier()) {
return this.get("init").getTypeAnnotation();
} else {
return;
}
}
function TypeCastExpression(node) {
return node.typeAnnotation;
}
TypeCastExpression.validParent = true;
function NewExpression(node) {
if (this.get("callee").isIdentifier()) {
return t.genericTypeAnnotation(node.callee);
}
}
function TemplateLiteral() {
return t.stringTypeAnnotation();
}
function UnaryExpression(node) {
var operator = node.operator;
if (operator === "void") {
return t.voidTypeAnnotation();
} else if (t.NUMBER_UNARY_OPERATORS.indexOf(operator) >= 0) {
return t.numberTypeAnnotation();
} else if (t.STRING_UNARY_OPERATORS.indexOf(operator) >= 0) {
return t.stringTypeAnnotation();
} else if (t.BOOLEAN_UNARY_OPERATORS.indexOf(operator) >= 0) {
return t.booleanTypeAnnotation();
}
}
function BinaryExpression(node) {
var operator = node.operator;
if (t.NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) {
return t.numberTypeAnnotation();
} else if (t.BOOLEAN_BINARY_OPERATORS.indexOf(operator) >= 0) {
return t.booleanTypeAnnotation();
} else if (operator === "+") {
var right = this.get("right");
var left = this.get("left");
if (left.isBaseType("number") && right.isBaseType("number")) {
return t.numberTypeAnnotation();
} else if (left.isBaseType("string") || right.isBaseType("string")) {
return t.stringTypeAnnotation();
}
return t.unionTypeAnnotation([t.stringTypeAnnotation(), t.numberTypeAnnotation()]);
}
}
function LogicalExpression() {
return t.createUnionTypeAnnotation([this.get("left").getTypeAnnotation(), this.get("right").getTypeAnnotation()]);
}
function ConditionalExpression() {
return t.createUnionTypeAnnotation([this.get("consequent").getTypeAnnotation(), this.get("alternate").getTypeAnnotation()]);
}
function SequenceExpression() {
return this.get("expressions").pop().getTypeAnnotation();
}
function AssignmentExpression() {
return this.get("right").getTypeAnnotation();
}
function UpdateExpression(node) {
var operator = node.operator;
if (operator === "++" || operator === "--") {
return t.numberTypeAnnotation();
}
}
function StringLiteral() {
return t.stringTypeAnnotation();
}
function NumericLiteral() {
return t.numberTypeAnnotation();
}
function BooleanLiteral() {
return t.booleanTypeAnnotation();
}
function NullLiteral() {
return t.nullLiteralTypeAnnotation();
}
function RegExpLiteral() {
return t.genericTypeAnnotation(t.identifier("RegExp"));
}
function ObjectExpression() {
return t.genericTypeAnnotation(t.identifier("Object"));
}
function ArrayExpression() {
return t.genericTypeAnnotation(t.identifier("Array"));
}
function RestElement() {
return ArrayExpression();
}
RestElement.validParent = true;
function Func() {
return t.genericTypeAnnotation(t.identifier("Function"));
}
exports.FunctionExpression = Func;
exports.ArrowFunctionExpression = Func;
exports.FunctionDeclaration = Func;
exports.ClassExpression = Func;
exports.ClassDeclaration = Func;
function CallExpression() {
return resolveCall(this.get("callee"));
}
function TaggedTemplateExpression() {
return resolveCall(this.get("tag"));
}
function resolveCall(callee) {
callee = callee.resolve();
if (callee.isFunction()) {
if (callee.is("async")) {
if (callee.is("generator")) {
return t.genericTypeAnnotation(t.identifier("AsyncIterator"));
} else {
return t.genericTypeAnnotation(t.identifier("Promise"));
}
} else {
if (callee.node.returnType) {
return callee.node.returnType;
} else {}
}
}
}

View File

@ -1,386 +0,0 @@
"use strict";
exports.__esModule = true;
exports.is = undefined;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
exports.matchesPattern = matchesPattern;
exports.has = has;
exports.isStatic = isStatic;
exports.isnt = isnt;
exports.equals = equals;
exports.isNodeType = isNodeType;
exports.canHaveVariableDeclarationOrExpression = canHaveVariableDeclarationOrExpression;
exports.canSwapBetweenExpressionAndStatement = canSwapBetweenExpressionAndStatement;
exports.isCompletionRecord = isCompletionRecord;
exports.isStatementOrBlock = isStatementOrBlock;
exports.referencesImport = referencesImport;
exports.getSource = getSource;
exports.willIMaybeExecuteBefore = willIMaybeExecuteBefore;
exports._guessExecutionStatusRelativeTo = _guessExecutionStatusRelativeTo;
exports._guessExecutionStatusRelativeToDifferentFunctions = _guessExecutionStatusRelativeToDifferentFunctions;
exports.resolve = resolve;
exports._resolve = _resolve;
var _includes = require("lodash/includes");
var _includes2 = _interopRequireDefault(_includes);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function matchesPattern(pattern, allowPartial) {
if (!this.isMemberExpression()) return false;
var parts = pattern.split(".");
var search = [this.node];
var i = 0;
function matches(name) {
var part = parts[i];
return part === "*" || name === part;
}
while (search.length) {
var node = search.shift();
if (allowPartial && i === parts.length) {
return true;
}
if (t.isIdentifier(node)) {
if (!matches(node.name)) return false;
} else if (t.isLiteral(node)) {
if (!matches(node.value)) return false;
} else if (t.isMemberExpression(node)) {
if (node.computed && !t.isLiteral(node.property)) {
return false;
} else {
search.unshift(node.property);
search.unshift(node.object);
continue;
}
} else if (t.isThisExpression(node)) {
if (!matches("this")) return false;
} else {
return false;
}
if (++i > parts.length) {
return false;
}
}
return i === parts.length;
}
function has(key) {
var val = this.node && this.node[key];
if (val && Array.isArray(val)) {
return !!val.length;
} else {
return !!val;
}
}
function isStatic() {
return this.scope.isStatic(this.node);
}
var is = exports.is = has;
function isnt(key) {
return !this.has(key);
}
function equals(key, value) {
return this.node[key] === value;
}
function isNodeType(type) {
return t.isType(this.type, type);
}
function canHaveVariableDeclarationOrExpression() {
return (this.key === "init" || this.key === "left") && this.parentPath.isFor();
}
function canSwapBetweenExpressionAndStatement(replacement) {
if (this.key !== "body" || !this.parentPath.isArrowFunctionExpression()) {
return false;
}
if (this.isExpression()) {
return t.isBlockStatement(replacement);
} else if (this.isBlockStatement()) {
return t.isExpression(replacement);
}
return false;
}
function isCompletionRecord(allowInsideFunction) {
var path = this;
var first = true;
do {
var container = path.container;
if (path.isFunction() && !first) {
return !!allowInsideFunction;
}
first = false;
if (Array.isArray(container) && path.key !== container.length - 1) {
return false;
}
} while ((path = path.parentPath) && !path.isProgram());
return true;
}
function isStatementOrBlock() {
if (this.parentPath.isLabeledStatement() || t.isBlockStatement(this.container)) {
return false;
} else {
return (0, _includes2.default)(t.STATEMENT_OR_BLOCK_KEYS, this.key);
}
}
function referencesImport(moduleSource, importName) {
if (!this.isReferencedIdentifier()) return false;
var binding = this.scope.getBinding(this.node.name);
if (!binding || binding.kind !== "module") return false;
var path = binding.path;
var parent = path.parentPath;
if (!parent.isImportDeclaration()) return false;
if (parent.node.source.value === moduleSource) {
if (!importName) return true;
} else {
return false;
}
if (path.isImportDefaultSpecifier() && importName === "default") {
return true;
}
if (path.isImportNamespaceSpecifier() && importName === "*") {
return true;
}
if (path.isImportSpecifier() && path.node.imported.name === importName) {
return true;
}
return false;
}
function getSource() {
var node = this.node;
if (node.end) {
return this.hub.file.code.slice(node.start, node.end);
} else {
return "";
}
}
function willIMaybeExecuteBefore(target) {
return this._guessExecutionStatusRelativeTo(target) !== "after";
}
function _guessExecutionStatusRelativeTo(target) {
var targetFuncParent = target.scope.getFunctionParent();
var selfFuncParent = this.scope.getFunctionParent();
if (targetFuncParent.node !== selfFuncParent.node) {
var status = this._guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent);
if (status) {
return status;
} else {
target = targetFuncParent.path;
}
}
var targetPaths = target.getAncestry();
if (targetPaths.indexOf(this) >= 0) return "after";
var selfPaths = this.getAncestry();
var commonPath = void 0;
var targetIndex = void 0;
var selfIndex = void 0;
for (selfIndex = 0; selfIndex < selfPaths.length; selfIndex++) {
var selfPath = selfPaths[selfIndex];
targetIndex = targetPaths.indexOf(selfPath);
if (targetIndex >= 0) {
commonPath = selfPath;
break;
}
}
if (!commonPath) {
return "before";
}
var targetRelationship = targetPaths[targetIndex - 1];
var selfRelationship = selfPaths[selfIndex - 1];
if (!targetRelationship || !selfRelationship) {
return "before";
}
if (targetRelationship.listKey && targetRelationship.container === selfRelationship.container) {
return targetRelationship.key > selfRelationship.key ? "before" : "after";
}
var targetKeyPosition = t.VISITOR_KEYS[targetRelationship.type].indexOf(targetRelationship.key);
var selfKeyPosition = t.VISITOR_KEYS[selfRelationship.type].indexOf(selfRelationship.key);
return targetKeyPosition > selfKeyPosition ? "before" : "after";
}
function _guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent) {
var targetFuncPath = targetFuncParent.path;
if (!targetFuncPath.isFunctionDeclaration()) return;
var binding = targetFuncPath.scope.getBinding(targetFuncPath.node.id.name);
if (!binding.references) return "before";
var referencePaths = binding.referencePaths;
for (var _iterator = referencePaths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var path = _ref;
if (path.key !== "callee" || !path.parentPath.isCallExpression()) {
return;
}
}
var allStatus = void 0;
for (var _iterator2 = referencePaths, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var _path = _ref2;
var childOfFunction = !!_path.find(function (path) {
return path.node === targetFuncPath.node;
});
if (childOfFunction) continue;
var status = this._guessExecutionStatusRelativeTo(_path);
if (allStatus) {
if (allStatus !== status) return;
} else {
allStatus = status;
}
}
return allStatus;
}
function resolve(dangerous, resolved) {
return this._resolve(dangerous, resolved) || this;
}
function _resolve(dangerous, resolved) {
if (resolved && resolved.indexOf(this) >= 0) return;
resolved = resolved || [];
resolved.push(this);
if (this.isVariableDeclarator()) {
if (this.get("id").isIdentifier()) {
return this.get("init").resolve(dangerous, resolved);
} else {}
} else if (this.isReferencedIdentifier()) {
var binding = this.scope.getBinding(this.node.name);
if (!binding) return;
if (!binding.constant) return;
if (binding.kind === "module") return;
if (binding.path !== this) {
var ret = binding.path.resolve(dangerous, resolved);
if (this.find(function (parent) {
return parent.node === ret.node;
})) return;
return ret;
}
} else if (this.isTypeCastExpression()) {
return this.get("expression").resolve(dangerous, resolved);
} else if (dangerous && this.isMemberExpression()) {
var targetKey = this.toComputedKey();
if (!t.isLiteral(targetKey)) return;
var targetName = targetKey.value;
var target = this.get("object").resolve(dangerous, resolved);
if (target.isObjectExpression()) {
var props = target.get("properties");
for (var _iterator3 = props, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var prop = _ref3;
if (!prop.isProperty()) continue;
var key = prop.get("key");
var match = prop.isnt("computed") && key.isIdentifier({ name: targetName });
match = match || key.isLiteral({ value: targetName });
if (match) return prop.get("value").resolve(dangerous, resolved);
}
} else if (target.isArrayExpression() && !isNaN(+targetName)) {
var elems = target.get("elements");
var elem = elems[targetName];
if (elem) return elem.resolve(dangerous, resolved);
}
}
}

View File

@ -1,211 +0,0 @@
"use strict";
exports.__esModule = true;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var referenceVisitor = {
ReferencedIdentifier: function ReferencedIdentifier(path, state) {
if (path.isJSXIdentifier() && _babelTypes.react.isCompatTag(path.node.name) && !path.parentPath.isJSXMemberExpression()) {
return;
}
if (path.node.name === "this") {
var scope = path.scope;
do {
if (scope.path.isFunction() && !scope.path.isArrowFunctionExpression()) break;
} while (scope = scope.parent);
if (scope) state.breakOnScopePaths.push(scope.path);
}
var binding = path.scope.getBinding(path.node.name);
if (!binding) return;
if (binding !== state.scope.getBinding(path.node.name)) return;
state.bindings[path.node.name] = binding;
}
};
var PathHoister = function () {
function PathHoister(path, scope) {
(0, _classCallCheck3.default)(this, PathHoister);
this.breakOnScopePaths = [];
this.bindings = {};
this.scopes = [];
this.scope = scope;
this.path = path;
this.attachAfter = false;
}
PathHoister.prototype.isCompatibleScope = function isCompatibleScope(scope) {
for (var key in this.bindings) {
var binding = this.bindings[key];
if (!scope.bindingIdentifierEquals(key, binding.identifier)) {
return false;
}
}
return true;
};
PathHoister.prototype.getCompatibleScopes = function getCompatibleScopes() {
var scope = this.path.scope;
do {
if (this.isCompatibleScope(scope)) {
this.scopes.push(scope);
} else {
break;
}
if (this.breakOnScopePaths.indexOf(scope.path) >= 0) {
break;
}
} while (scope = scope.parent);
};
PathHoister.prototype.getAttachmentPath = function getAttachmentPath() {
var path = this._getAttachmentPath();
if (!path) return;
var targetScope = path.scope;
if (targetScope.path === path) {
targetScope = path.scope.parent;
}
if (targetScope.path.isProgram() || targetScope.path.isFunction()) {
for (var name in this.bindings) {
if (!targetScope.hasOwnBinding(name)) continue;
var binding = this.bindings[name];
if (binding.kind === "param") continue;
if (this.getAttachmentParentForPath(binding.path).key > path.key) {
this.attachAfter = true;
path = binding.path;
for (var _iterator = binding.constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var violationPath = _ref;
if (this.getAttachmentParentForPath(violationPath).key > path.key) {
path = violationPath;
}
}
}
}
}
if (path.parentPath.isExportDeclaration()) {
path = path.parentPath;
}
return path;
};
PathHoister.prototype._getAttachmentPath = function _getAttachmentPath() {
var scopes = this.scopes;
var scope = scopes.pop();
if (!scope) return;
if (scope.path.isFunction()) {
if (this.hasOwnParamBindings(scope)) {
if (this.scope === scope) return;
return scope.path.get("body").get("body")[0];
} else {
return this.getNextScopeAttachmentParent();
}
} else if (scope.path.isProgram()) {
return this.getNextScopeAttachmentParent();
}
};
PathHoister.prototype.getNextScopeAttachmentParent = function getNextScopeAttachmentParent() {
var scope = this.scopes.pop();
if (scope) return this.getAttachmentParentForPath(scope.path);
};
PathHoister.prototype.getAttachmentParentForPath = function getAttachmentParentForPath(path) {
do {
if (!path.parentPath || Array.isArray(path.container) && path.isStatement() || path.isVariableDeclarator() && path.parentPath.node !== null && path.parentPath.node.declarations.length > 1) return path;
} while (path = path.parentPath);
};
PathHoister.prototype.hasOwnParamBindings = function hasOwnParamBindings(scope) {
for (var name in this.bindings) {
if (!scope.hasOwnBinding(name)) continue;
var binding = this.bindings[name];
if (binding.kind === "param" && binding.constant) return true;
}
return false;
};
PathHoister.prototype.run = function run() {
var node = this.path.node;
if (node._hoisted) return;
node._hoisted = true;
this.path.traverse(referenceVisitor, this);
this.getCompatibleScopes();
var attachTo = this.getAttachmentPath();
if (!attachTo) return;
if (attachTo.getFunctionParent() === this.path.getFunctionParent()) return;
var uid = attachTo.scope.generateUidIdentifier("ref");
var declarator = t.variableDeclarator(uid, this.path.node);
var insertFn = this.attachAfter ? "insertAfter" : "insertBefore";
attachTo[insertFn]([attachTo.isVariableDeclarator() ? declarator : t.variableDeclaration("var", [declarator])]);
var parent = this.path.parentPath;
if (parent.isJSXElement() && this.path.container === parent.node.children) {
uid = t.JSXExpressionContainer(uid);
}
this.path.replaceWith(uid);
};
return PathHoister;
}();
exports.default = PathHoister;
module.exports = exports["default"];

View File

@ -1,33 +0,0 @@
"use strict";
exports.__esModule = true;
var hooks = exports.hooks = [function (self, parent) {
var removeParent = self.key === "test" && (parent.isWhile() || parent.isSwitchCase()) || self.key === "declaration" && parent.isExportDeclaration() || self.key === "body" && parent.isLabeledStatement() || self.listKey === "declarations" && parent.isVariableDeclaration() && parent.node.declarations.length === 1 || self.key === "expression" && parent.isExpressionStatement();
if (removeParent) {
parent.remove();
return true;
}
}, function (self, parent) {
if (parent.isSequenceExpression() && parent.node.expressions.length === 1) {
parent.replaceWith(parent.node.expressions[0]);
return true;
}
}, function (self, parent) {
if (parent.isBinary()) {
if (self.key === "left") {
parent.replaceWith(parent.node.right);
} else {
parent.replaceWith(parent.node.left);
}
return true;
}
}, function (self, parent) {
if (parent.isIfStatement() && (self.key === "consequent" || self.key === "alternate") || self.key === "body" && (parent.isLoop() || parent.isArrowFunctionExpression())) {
self.replaceWith({
type: "BlockStatement",
body: []
});
return true;
}
}];

View File

@ -1,141 +0,0 @@
"use strict";
exports.__esModule = true;
exports.Flow = exports.Pure = exports.Generated = exports.User = exports.Var = exports.BlockScoped = exports.Referenced = exports.Scope = exports.Expression = exports.Statement = exports.BindingIdentifier = exports.ReferencedMemberExpression = exports.ReferencedIdentifier = undefined;
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
var ReferencedIdentifier = exports.ReferencedIdentifier = {
types: ["Identifier", "JSXIdentifier"],
checkPath: function checkPath(_ref, opts) {
var node = _ref.node,
parent = _ref.parent;
if (!t.isIdentifier(node, opts) && !t.isJSXMemberExpression(parent, opts)) {
if (t.isJSXIdentifier(node, opts)) {
if (_babelTypes.react.isCompatTag(node.name)) return false;
} else {
return false;
}
}
return t.isReferenced(node, parent);
}
};
var ReferencedMemberExpression = exports.ReferencedMemberExpression = {
types: ["MemberExpression"],
checkPath: function checkPath(_ref2) {
var node = _ref2.node,
parent = _ref2.parent;
return t.isMemberExpression(node) && t.isReferenced(node, parent);
}
};
var BindingIdentifier = exports.BindingIdentifier = {
types: ["Identifier"],
checkPath: function checkPath(_ref3) {
var node = _ref3.node,
parent = _ref3.parent;
return t.isIdentifier(node) && t.isBinding(node, parent);
}
};
var Statement = exports.Statement = {
types: ["Statement"],
checkPath: function checkPath(_ref4) {
var node = _ref4.node,
parent = _ref4.parent;
if (t.isStatement(node)) {
if (t.isVariableDeclaration(node)) {
if (t.isForXStatement(parent, { left: node })) return false;
if (t.isForStatement(parent, { init: node })) return false;
}
return true;
} else {
return false;
}
}
};
var Expression = exports.Expression = {
types: ["Expression"],
checkPath: function checkPath(path) {
if (path.isIdentifier()) {
return path.isReferencedIdentifier();
} else {
return t.isExpression(path.node);
}
}
};
var Scope = exports.Scope = {
types: ["Scopable"],
checkPath: function checkPath(path) {
return t.isScope(path.node, path.parent);
}
};
var Referenced = exports.Referenced = {
checkPath: function checkPath(path) {
return t.isReferenced(path.node, path.parent);
}
};
var BlockScoped = exports.BlockScoped = {
checkPath: function checkPath(path) {
return t.isBlockScoped(path.node);
}
};
var Var = exports.Var = {
types: ["VariableDeclaration"],
checkPath: function checkPath(path) {
return t.isVar(path.node);
}
};
var User = exports.User = {
checkPath: function checkPath(path) {
return path.node && !!path.node.loc;
}
};
var Generated = exports.Generated = {
checkPath: function checkPath(path) {
return !path.isUser();
}
};
var Pure = exports.Pure = {
checkPath: function checkPath(path, opts) {
return path.scope.isPure(path.node, opts);
}
};
var Flow = exports.Flow = {
types: ["Flow", "ImportDeclaration", "ExportDeclaration", "ImportSpecifier"],
checkPath: function checkPath(_ref5) {
var node = _ref5.node;
if (t.isFlow(node)) {
return true;
} else if (t.isImportDeclaration(node)) {
return node.importKind === "type" || node.importKind === "typeof";
} else if (t.isExportDeclaration(node)) {
return node.exportKind === "type";
} else if (t.isImportSpecifier(node)) {
return node.importKind === "type" || node.importKind === "typeof";
} else {
return false;
}
}
};

View File

@ -1,264 +0,0 @@
"use strict";
exports.__esModule = true;
var _typeof2 = require("babel-runtime/helpers/typeof");
var _typeof3 = _interopRequireDefault(_typeof2);
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
exports.insertBefore = insertBefore;
exports._containerInsert = _containerInsert;
exports._containerInsertBefore = _containerInsertBefore;
exports._containerInsertAfter = _containerInsertAfter;
exports._maybePopFromStatements = _maybePopFromStatements;
exports.insertAfter = insertAfter;
exports.updateSiblingKeys = updateSiblingKeys;
exports._verifyNodeList = _verifyNodeList;
exports.unshiftContainer = unshiftContainer;
exports.pushContainer = pushContainer;
exports.hoist = hoist;
var _cache = require("../cache");
var _hoister = require("./lib/hoister");
var _hoister2 = _interopRequireDefault(_hoister);
var _index = require("./index");
var _index2 = _interopRequireDefault(_index);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function insertBefore(nodes) {
this._assertUnremoved();
nodes = this._verifyNodeList(nodes);
if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement()) {
return this.parentPath.insertBefore(nodes);
} else if (this.isNodeType("Expression") || this.parentPath.isForStatement() && this.key === "init") {
if (this.node) nodes.push(this.node);
this.replaceExpressionWithStatements(nodes);
} else {
this._maybePopFromStatements(nodes);
if (Array.isArray(this.container)) {
return this._containerInsertBefore(nodes);
} else if (this.isStatementOrBlock()) {
if (this.node) nodes.push(this.node);
this._replaceWith(t.blockStatement(nodes));
} else {
throw new Error("We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?");
}
}
return [this];
}
function _containerInsert(from, nodes) {
this.updateSiblingKeys(from, nodes.length);
var paths = [];
for (var i = 0; i < nodes.length; i++) {
var to = from + i;
var node = nodes[i];
this.container.splice(to, 0, node);
if (this.context) {
var path = this.context.create(this.parent, this.container, to, this.listKey);
if (this.context.queue) path.pushContext(this.context);
paths.push(path);
} else {
paths.push(_index2.default.get({
parentPath: this.parentPath,
parent: this.parent,
container: this.container,
listKey: this.listKey,
key: to
}));
}
}
var contexts = this._getQueueContexts();
for (var _iterator = paths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var _path = _ref;
_path.setScope();
_path.debug(function () {
return "Inserted.";
});
for (var _iterator2 = contexts, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var context = _ref2;
context.maybeQueue(_path, true);
}
}
return paths;
}
function _containerInsertBefore(nodes) {
return this._containerInsert(this.key, nodes);
}
function _containerInsertAfter(nodes) {
return this._containerInsert(this.key + 1, nodes);
}
function _maybePopFromStatements(nodes) {
var last = nodes[nodes.length - 1];
var isIdentifier = t.isIdentifier(last) || t.isExpressionStatement(last) && t.isIdentifier(last.expression);
if (isIdentifier && !this.isCompletionRecord()) {
nodes.pop();
}
}
function insertAfter(nodes) {
this._assertUnremoved();
nodes = this._verifyNodeList(nodes);
if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement()) {
return this.parentPath.insertAfter(nodes);
} else if (this.isNodeType("Expression") || this.parentPath.isForStatement() && this.key === "init") {
if (this.node) {
var temp = this.scope.generateDeclaredUidIdentifier();
nodes.unshift(t.expressionStatement(t.assignmentExpression("=", temp, this.node)));
nodes.push(t.expressionStatement(temp));
}
this.replaceExpressionWithStatements(nodes);
} else {
this._maybePopFromStatements(nodes);
if (Array.isArray(this.container)) {
return this._containerInsertAfter(nodes);
} else if (this.isStatementOrBlock()) {
if (this.node) nodes.unshift(this.node);
this._replaceWith(t.blockStatement(nodes));
} else {
throw new Error("We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?");
}
}
return [this];
}
function updateSiblingKeys(fromIndex, incrementBy) {
if (!this.parent) return;
var paths = _cache.path.get(this.parent);
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
if (path.key >= fromIndex) {
path.key += incrementBy;
}
}
}
function _verifyNodeList(nodes) {
if (!nodes) {
return [];
}
if (nodes.constructor !== Array) {
nodes = [nodes];
}
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
var msg = void 0;
if (!node) {
msg = "has falsy node";
} else if ((typeof node === "undefined" ? "undefined" : (0, _typeof3.default)(node)) !== "object") {
msg = "contains a non-object node";
} else if (!node.type) {
msg = "without a type";
} else if (node instanceof _index2.default) {
msg = "has a NodePath when it expected a raw object";
}
if (msg) {
var type = Array.isArray(node) ? "array" : typeof node === "undefined" ? "undefined" : (0, _typeof3.default)(node);
throw new Error("Node list " + msg + " with the index of " + i + " and type of " + type);
}
}
return nodes;
}
function unshiftContainer(listKey, nodes) {
this._assertUnremoved();
nodes = this._verifyNodeList(nodes);
var path = _index2.default.get({
parentPath: this,
parent: this.node,
container: this.node[listKey],
listKey: listKey,
key: 0
});
return path.insertBefore(nodes);
}
function pushContainer(listKey, nodes) {
this._assertUnremoved();
nodes = this._verifyNodeList(nodes);
var container = this.node[listKey];
var path = _index2.default.get({
parentPath: this,
parent: this.node,
container: container,
listKey: listKey,
key: container.length
});
return path.replaceWithMultiple(nodes);
}
function hoist() {
var scope = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.scope;
var hoister = new _hoister2.default(this, scope);
return hoister.run();
}

View File

@ -1,72 +0,0 @@
"use strict";
exports.__esModule = true;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
exports.remove = remove;
exports._callRemovalHooks = _callRemovalHooks;
exports._remove = _remove;
exports._markRemoved = _markRemoved;
exports._assertUnremoved = _assertUnremoved;
var _removalHooks = require("./lib/removal-hooks");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function remove() {
this._assertUnremoved();
this.resync();
if (this._callRemovalHooks()) {
this._markRemoved();
return;
}
this.shareCommentsWithSiblings();
this._remove();
this._markRemoved();
}
function _callRemovalHooks() {
for (var _iterator = _removalHooks.hooks, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var fn = _ref;
if (fn(this, this.parentPath)) return true;
}
}
function _remove() {
if (Array.isArray(this.container)) {
this.container.splice(this.key, 1);
this.updateSiblingKeys(this.key, -1);
} else {
this._replaceWith(null);
}
}
function _markRemoved() {
this.shouldSkip = true;
this.removed = true;
this.node = null;
}
function _assertUnremoved() {
if (this.removed) {
throw this.buildCodeFrameError("NodePath has been removed so is read-only.");
}
}

View File

@ -1,268 +0,0 @@
"use strict";
exports.__esModule = true;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
exports.replaceWithMultiple = replaceWithMultiple;
exports.replaceWithSourceString = replaceWithSourceString;
exports.replaceWith = replaceWith;
exports._replaceWith = _replaceWith;
exports.replaceExpressionWithStatements = replaceExpressionWithStatements;
exports.replaceInline = replaceInline;
var _babelCodeFrame = require("babel-code-frame");
var _babelCodeFrame2 = _interopRequireDefault(_babelCodeFrame);
var _index = require("../index");
var _index2 = _interopRequireDefault(_index);
var _index3 = require("./index");
var _index4 = _interopRequireDefault(_index3);
var _babylon = require("babylon");
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var hoistVariablesVisitor = {
Function: function Function(path) {
path.skip();
},
VariableDeclaration: function VariableDeclaration(path) {
if (path.node.kind !== "var") return;
var bindings = path.getBindingIdentifiers();
for (var key in bindings) {
path.scope.push({ id: bindings[key] });
}
var exprs = [];
for (var _iterator = path.node.declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var declar = _ref;
if (declar.init) {
exprs.push(t.expressionStatement(t.assignmentExpression("=", declar.id, declar.init)));
}
}
path.replaceWithMultiple(exprs);
}
};
function replaceWithMultiple(nodes) {
this.resync();
nodes = this._verifyNodeList(nodes);
t.inheritLeadingComments(nodes[0], this.node);
t.inheritTrailingComments(nodes[nodes.length - 1], this.node);
this.node = this.container[this.key] = null;
this.insertAfter(nodes);
if (this.node) {
this.requeue();
} else {
this.remove();
}
}
function replaceWithSourceString(replacement) {
this.resync();
try {
replacement = "(" + replacement + ")";
replacement = (0, _babylon.parse)(replacement);
} catch (err) {
var loc = err.loc;
if (loc) {
err.message += " - make sure this is an expression.";
err.message += "\n" + (0, _babelCodeFrame2.default)(replacement, loc.line, loc.column + 1);
}
throw err;
}
replacement = replacement.program.body[0].expression;
_index2.default.removeProperties(replacement);
return this.replaceWith(replacement);
}
function replaceWith(replacement) {
this.resync();
if (this.removed) {
throw new Error("You can't replace this node, we've already removed it");
}
if (replacement instanceof _index4.default) {
replacement = replacement.node;
}
if (!replacement) {
throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead");
}
if (this.node === replacement) {
return;
}
if (this.isProgram() && !t.isProgram(replacement)) {
throw new Error("You can only replace a Program root node with another Program node");
}
if (Array.isArray(replacement)) {
throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`");
}
if (typeof replacement === "string") {
throw new Error("Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`");
}
if (this.isNodeType("Statement") && t.isExpression(replacement)) {
if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement) && !this.parentPath.isExportDefaultDeclaration()) {
replacement = t.expressionStatement(replacement);
}
}
if (this.isNodeType("Expression") && t.isStatement(replacement)) {
if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement)) {
return this.replaceExpressionWithStatements([replacement]);
}
}
var oldNode = this.node;
if (oldNode) {
t.inheritsComments(replacement, oldNode);
t.removeComments(oldNode);
}
this._replaceWith(replacement);
this.type = replacement.type;
this.setScope();
this.requeue();
}
function _replaceWith(node) {
if (!this.container) {
throw new ReferenceError("Container is falsy");
}
if (this.inList) {
t.validate(this.parent, this.key, [node]);
} else {
t.validate(this.parent, this.key, node);
}
this.debug(function () {
return "Replace with " + (node && node.type);
});
this.node = this.container[this.key] = node;
}
function replaceExpressionWithStatements(nodes) {
this.resync();
var toSequenceExpression = t.toSequenceExpression(nodes, this.scope);
if (t.isSequenceExpression(toSequenceExpression)) {
var exprs = toSequenceExpression.expressions;
if (exprs.length >= 2 && this.parentPath.isExpressionStatement()) {
this._maybePopFromStatements(exprs);
}
if (exprs.length === 1) {
this.replaceWith(exprs[0]);
} else {
this.replaceWith(toSequenceExpression);
}
} else if (toSequenceExpression) {
this.replaceWith(toSequenceExpression);
} else {
var container = t.functionExpression(null, [], t.blockStatement(nodes));
container.shadow = true;
this.replaceWith(t.callExpression(container, []));
this.traverse(hoistVariablesVisitor);
var completionRecords = this.get("callee").getCompletionRecords();
for (var _iterator2 = completionRecords, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var path = _ref2;
if (!path.isExpressionStatement()) continue;
var loop = path.findParent(function (path) {
return path.isLoop();
});
if (loop) {
var uid = loop.getData("expressionReplacementReturnUid");
if (!uid) {
var callee = this.get("callee");
uid = callee.scope.generateDeclaredUidIdentifier("ret");
callee.get("body").pushContainer("body", t.returnStatement(uid));
loop.setData("expressionReplacementReturnUid", uid);
} else {
uid = t.identifier(uid.name);
}
path.get("expression").replaceWith(t.assignmentExpression("=", uid, path.node.expression));
} else {
path.replaceWith(t.returnStatement(path.node.expression));
}
}
return this.node;
}
}
function replaceInline(nodes) {
this.resync();
if (Array.isArray(nodes)) {
if (Array.isArray(this.container)) {
nodes = this._verifyNodeList(nodes);
this._containerInsertAfter(nodes);
return this.remove();
} else {
return this.replaceWithMultiple(nodes);
}
} else {
return this.replaceWith(nodes);
}
}

View File

@ -1,82 +0,0 @@
"use strict";
exports.__esModule = true;
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Binding = function () {
function Binding(_ref) {
var existing = _ref.existing,
identifier = _ref.identifier,
scope = _ref.scope,
path = _ref.path,
kind = _ref.kind;
(0, _classCallCheck3.default)(this, Binding);
this.identifier = identifier;
this.scope = scope;
this.path = path;
this.kind = kind;
this.constantViolations = [];
this.constant = true;
this.referencePaths = [];
this.referenced = false;
this.references = 0;
this.clearValue();
if (existing) {
this.constantViolations = [].concat(existing.path, existing.constantViolations, this.constantViolations);
}
}
Binding.prototype.deoptValue = function deoptValue() {
this.clearValue();
this.hasDeoptedValue = true;
};
Binding.prototype.setValue = function setValue(value) {
if (this.hasDeoptedValue) return;
this.hasValue = true;
this.value = value;
};
Binding.prototype.clearValue = function clearValue() {
this.hasDeoptedValue = false;
this.hasValue = false;
this.value = null;
};
Binding.prototype.reassign = function reassign(path) {
this.constant = false;
if (this.constantViolations.indexOf(path) !== -1) {
return;
}
this.constantViolations.push(path);
};
Binding.prototype.reference = function reference(path) {
if (this.referencePaths.indexOf(path) !== -1) {
return;
}
this.referenced = true;
this.references++;
this.referencePaths.push(path);
};
Binding.prototype.dereference = function dereference() {
this.references--;
this.referenced = !!this.references;
};
return Binding;
}();
exports.default = Binding;
module.exports = exports["default"];

File diff suppressed because it is too large Load Diff

View File

@ -1,113 +0,0 @@
"use strict";
exports.__esModule = true;
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _binding = require("../binding");
var _binding2 = _interopRequireDefault(_binding);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var renameVisitor = {
ReferencedIdentifier: function ReferencedIdentifier(_ref, state) {
var node = _ref.node;
if (node.name === state.oldName) {
node.name = state.newName;
}
},
Scope: function Scope(path, state) {
if (!path.scope.bindingIdentifierEquals(state.oldName, state.binding.identifier)) {
path.skip();
}
},
"AssignmentExpression|Declaration": function AssignmentExpressionDeclaration(path, state) {
var ids = path.getOuterBindingIdentifiers();
for (var name in ids) {
if (name === state.oldName) ids[name].name = state.newName;
}
}
};
var Renamer = function () {
function Renamer(binding, oldName, newName) {
(0, _classCallCheck3.default)(this, Renamer);
this.newName = newName;
this.oldName = oldName;
this.binding = binding;
}
Renamer.prototype.maybeConvertFromExportDeclaration = function maybeConvertFromExportDeclaration(parentDeclar) {
var exportDeclar = parentDeclar.parentPath.isExportDeclaration() && parentDeclar.parentPath;
if (!exportDeclar) return;
var isDefault = exportDeclar.isExportDefaultDeclaration();
if (isDefault && (parentDeclar.isFunctionDeclaration() || parentDeclar.isClassDeclaration()) && !parentDeclar.node.id) {
parentDeclar.node.id = parentDeclar.scope.generateUidIdentifier("default");
}
var bindingIdentifiers = parentDeclar.getOuterBindingIdentifiers();
var specifiers = [];
for (var name in bindingIdentifiers) {
var localName = name === this.oldName ? this.newName : name;
var exportedName = isDefault ? "default" : name;
specifiers.push(t.exportSpecifier(t.identifier(localName), t.identifier(exportedName)));
}
if (specifiers.length) {
var aliasDeclar = t.exportNamedDeclaration(null, specifiers);
if (parentDeclar.isFunctionDeclaration()) {
aliasDeclar._blockHoist = 3;
}
exportDeclar.insertAfter(aliasDeclar);
exportDeclar.replaceWith(parentDeclar.node);
}
};
Renamer.prototype.rename = function rename(block) {
var binding = this.binding,
oldName = this.oldName,
newName = this.newName;
var scope = binding.scope,
path = binding.path;
var parentDeclar = path.find(function (path) {
return path.isDeclaration() || path.isFunctionExpression();
});
if (parentDeclar) {
this.maybeConvertFromExportDeclaration(parentDeclar);
}
scope.traverse(block || scope.block, renameVisitor, this);
if (!block) {
scope.removeOwnBinding(oldName);
scope.bindings[newName] = binding;
this.binding.identifier.name = newName;
}
if (binding.type === "hoisted") {}
};
return Renamer;
}();
exports.default = Renamer;
module.exports = exports["default"];

View File

@ -1,341 +0,0 @@
"use strict";
exports.__esModule = true;
var _typeof2 = require("babel-runtime/helpers/typeof");
var _typeof3 = _interopRequireDefault(_typeof2);
var _keys = require("babel-runtime/core-js/object/keys");
var _keys2 = _interopRequireDefault(_keys);
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
exports.explode = explode;
exports.verify = verify;
exports.merge = merge;
var _virtualTypes = require("./path/lib/virtual-types");
var virtualTypes = _interopRequireWildcard(_virtualTypes);
var _babelMessages = require("babel-messages");
var messages = _interopRequireWildcard(_babelMessages);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var _clone = require("lodash/clone");
var _clone2 = _interopRequireDefault(_clone);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function explode(visitor) {
if (visitor._exploded) return visitor;
visitor._exploded = true;
for (var nodeType in visitor) {
if (shouldIgnoreKey(nodeType)) continue;
var parts = nodeType.split("|");
if (parts.length === 1) continue;
var fns = visitor[nodeType];
delete visitor[nodeType];
for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var part = _ref;
visitor[part] = fns;
}
}
verify(visitor);
delete visitor.__esModule;
ensureEntranceObjects(visitor);
ensureCallbackArrays(visitor);
for (var _iterator2 = (0, _keys2.default)(visitor), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var _nodeType3 = _ref2;
if (shouldIgnoreKey(_nodeType3)) continue;
var wrapper = virtualTypes[_nodeType3];
if (!wrapper) continue;
var _fns2 = visitor[_nodeType3];
for (var type in _fns2) {
_fns2[type] = wrapCheck(wrapper, _fns2[type]);
}
delete visitor[_nodeType3];
if (wrapper.types) {
for (var _iterator4 = wrapper.types, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) {
var _ref4;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref4 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref4 = _i4.value;
}
var _type = _ref4;
if (visitor[_type]) {
mergePair(visitor[_type], _fns2);
} else {
visitor[_type] = _fns2;
}
}
} else {
mergePair(visitor, _fns2);
}
}
for (var _nodeType in visitor) {
if (shouldIgnoreKey(_nodeType)) continue;
var _fns = visitor[_nodeType];
var aliases = t.FLIPPED_ALIAS_KEYS[_nodeType];
var deprecratedKey = t.DEPRECATED_KEYS[_nodeType];
if (deprecratedKey) {
console.trace("Visitor defined for " + _nodeType + " but it has been renamed to " + deprecratedKey);
aliases = [deprecratedKey];
}
if (!aliases) continue;
delete visitor[_nodeType];
for (var _iterator3 = aliases, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var alias = _ref3;
var existing = visitor[alias];
if (existing) {
mergePair(existing, _fns);
} else {
visitor[alias] = (0, _clone2.default)(_fns);
}
}
}
for (var _nodeType2 in visitor) {
if (shouldIgnoreKey(_nodeType2)) continue;
ensureCallbackArrays(visitor[_nodeType2]);
}
return visitor;
}
function verify(visitor) {
if (visitor._verified) return;
if (typeof visitor === "function") {
throw new Error(messages.get("traverseVerifyRootFunction"));
}
for (var nodeType in visitor) {
if (nodeType === "enter" || nodeType === "exit") {
validateVisitorMethods(nodeType, visitor[nodeType]);
}
if (shouldIgnoreKey(nodeType)) continue;
if (t.TYPES.indexOf(nodeType) < 0) {
throw new Error(messages.get("traverseVerifyNodeType", nodeType));
}
var visitors = visitor[nodeType];
if ((typeof visitors === "undefined" ? "undefined" : (0, _typeof3.default)(visitors)) === "object") {
for (var visitorKey in visitors) {
if (visitorKey === "enter" || visitorKey === "exit") {
validateVisitorMethods(nodeType + "." + visitorKey, visitors[visitorKey]);
} else {
throw new Error(messages.get("traverseVerifyVisitorProperty", nodeType, visitorKey));
}
}
}
}
visitor._verified = true;
}
function validateVisitorMethods(path, val) {
var fns = [].concat(val);
for (var _iterator5 = fns, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) {
var _ref5;
if (_isArray5) {
if (_i5 >= _iterator5.length) break;
_ref5 = _iterator5[_i5++];
} else {
_i5 = _iterator5.next();
if (_i5.done) break;
_ref5 = _i5.value;
}
var fn = _ref5;
if (typeof fn !== "function") {
throw new TypeError("Non-function found defined in " + path + " with type " + (typeof fn === "undefined" ? "undefined" : (0, _typeof3.default)(fn)));
}
}
}
function merge(visitors) {
var states = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var wrapper = arguments[2];
var rootVisitor = {};
for (var i = 0; i < visitors.length; i++) {
var visitor = visitors[i];
var state = states[i];
explode(visitor);
for (var type in visitor) {
var visitorType = visitor[type];
if (state || wrapper) {
visitorType = wrapWithStateOrWrapper(visitorType, state, wrapper);
}
var nodeVisitor = rootVisitor[type] = rootVisitor[type] || {};
mergePair(nodeVisitor, visitorType);
}
}
return rootVisitor;
}
function wrapWithStateOrWrapper(oldVisitor, state, wrapper) {
var newVisitor = {};
var _loop = function _loop(key) {
var fns = oldVisitor[key];
if (!Array.isArray(fns)) return "continue";
fns = fns.map(function (fn) {
var newFn = fn;
if (state) {
newFn = function newFn(path) {
return fn.call(state, path, state);
};
}
if (wrapper) {
newFn = wrapper(state.key, key, newFn);
}
return newFn;
});
newVisitor[key] = fns;
};
for (var key in oldVisitor) {
var _ret = _loop(key);
if (_ret === "continue") continue;
}
return newVisitor;
}
function ensureEntranceObjects(obj) {
for (var key in obj) {
if (shouldIgnoreKey(key)) continue;
var fns = obj[key];
if (typeof fns === "function") {
obj[key] = { enter: fns };
}
}
}
function ensureCallbackArrays(obj) {
if (obj.enter && !Array.isArray(obj.enter)) obj.enter = [obj.enter];
if (obj.exit && !Array.isArray(obj.exit)) obj.exit = [obj.exit];
}
function wrapCheck(wrapper, fn) {
var newFn = function newFn(path) {
if (wrapper.checkPath(path)) {
return fn.apply(this, arguments);
}
};
newFn.toString = function () {
return fn.toString();
};
return newFn;
}
function shouldIgnoreKey(key) {
if (key[0] === "_") return true;
if (key === "enter" || key === "exit" || key === "shouldSkip") return true;
if (key === "blacklist" || key === "noScope" || key === "skipKeys") return true;
return false;
}
function mergePair(dest, src) {
for (var key in src) {
dest[key] = [].concat(dest[key] || [], src[key]);
}
}

View File

@ -1 +0,0 @@
../../../../../babylon/bin/babylon.js

View File

@ -1 +0,0 @@
repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve

View File

@ -1,11 +0,0 @@
{
"env": {
"browser": true,
"node": true
},
"rules": {
"no-console": 0,
"no-empty": [1, { "allowEmptyCatch": true }]
},
"extends": "eslint:recommended"
}

View File

@ -1,9 +0,0 @@
support
test
examples
example
*.sock
dist
yarn.lock
coverage
bower.json

View File

@ -1,14 +0,0 @@
language: node_js
node_js:
- "6"
- "5"
- "4"
install:
- make node_modules
script:
- make lint
- make test
- make coveralls

View File

@ -1,362 +0,0 @@
2.6.9 / 2017-09-22
==================
* remove ReDoS regexp in %o formatter (#504)
2.6.8 / 2017-05-18
==================
* Fix: Check for undefined on browser globals (#462, @marbemac)
2.6.7 / 2017-05-16
==================
* Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom)
* Fix: Inline extend function in node implementation (#452, @dougwilson)
* Docs: Fix typo (#455, @msasad)
2.6.5 / 2017-04-27
==================
* Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek)
* Misc: clean up browser reference checks (#447, @thebigredgeek)
* Misc: add npm-debug.log to .gitignore (@thebigredgeek)
2.6.4 / 2017-04-20
==================
* Fix: bug that would occure if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo)
* Chore: ignore bower.json in npm installations. (#437, @joaovieira)
* Misc: update "ms" to v0.7.3 (@tootallnate)
2.6.3 / 2017-03-13
==================
* Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts)
* Docs: Changelog fix (@thebigredgeek)
2.6.2 / 2017-03-10
==================
* Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin)
* Docs: Add backers and sponsors from Open Collective (#422, @piamancini)
* Docs: Add Slackin invite badge (@tootallnate)
2.6.1 / 2017-02-10
==================
* Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error
* Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0)
* Fix: IE8 "Expected identifier" error (#414, @vgoma)
* Fix: Namespaces would not disable once enabled (#409, @musikov)
2.6.0 / 2016-12-28
==================
* Fix: added better null pointer checks for browser useColors (@thebigredgeek)
* Improvement: removed explicit `window.debug` export (#404, @tootallnate)
* Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate)
2.5.2 / 2016-12-25
==================
* Fix: reference error on window within webworkers (#393, @KlausTrainer)
* Docs: fixed README typo (#391, @lurch)
* Docs: added notice about v3 api discussion (@thebigredgeek)
2.5.1 / 2016-12-20
==================
* Fix: babel-core compatibility
2.5.0 / 2016-12-20
==================
* Fix: wrong reference in bower file (@thebigredgeek)
* Fix: webworker compatibility (@thebigredgeek)
* Fix: output formatting issue (#388, @kribblo)
* Fix: babel-loader compatibility (#383, @escwald)
* Misc: removed built asset from repo and publications (@thebigredgeek)
* Misc: moved source files to /src (#378, @yamikuronue)
* Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue)
* Test: coveralls integration (#378, @yamikuronue)
* Docs: simplified language in the opening paragraph (#373, @yamikuronue)
2.4.5 / 2016-12-17
==================
* Fix: `navigator` undefined in Rhino (#376, @jochenberger)
* Fix: custom log function (#379, @hsiliev)
* Improvement: bit of cleanup + linting fixes (@thebigredgeek)
* Improvement: rm non-maintainted `dist/` dir (#375, @freewil)
* Docs: simplified language in the opening paragraph. (#373, @yamikuronue)
2.4.4 / 2016-12-14
==================
* Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts)
2.4.3 / 2016-12-14
==================
* Fix: navigation.userAgent error for react native (#364, @escwald)
2.4.2 / 2016-12-14
==================
* Fix: browser colors (#367, @tootallnate)
* Misc: travis ci integration (@thebigredgeek)
* Misc: added linting and testing boilerplate with sanity check (@thebigredgeek)
2.4.1 / 2016-12-13
==================
* Fix: typo that broke the package (#356)
2.4.0 / 2016-12-13
==================
* Fix: bower.json references unbuilt src entry point (#342, @justmatt)
* Fix: revert "handle regex special characters" (@tootallnate)
* Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate)
* Feature: %O`(big O) pretty-prints objects (#322, @tootallnate)
* Improvement: allow colors in workers (#335, @botverse)
* Improvement: use same color for same namespace. (#338, @lchenay)
2.3.3 / 2016-11-09
==================
* Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne)
* Fix: Returning `localStorage` saved values (#331, Levi Thomason)
* Improvement: Don't create an empty object when no `process` (Nathan Rajlich)
2.3.2 / 2016-11-09
==================
* Fix: be super-safe in index.js as well (@TooTallNate)
* Fix: should check whether process exists (Tom Newby)
2.3.1 / 2016-11-09
==================
* Fix: Added electron compatibility (#324, @paulcbetts)
* Improvement: Added performance optimizations (@tootallnate)
* Readme: Corrected PowerShell environment variable example (#252, @gimre)
* Misc: Removed yarn lock file from source control (#321, @fengmk2)
2.3.0 / 2016-11-07
==================
* Fix: Consistent placement of ms diff at end of output (#215, @gorangajic)
* Fix: Escaping of regex special characters in namespace strings (#250, @zacronos)
* Fix: Fixed bug causing crash on react-native (#282, @vkarpov15)
* Feature: Enabled ES6+ compatible import via default export (#212 @bucaran)
* Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom)
* Package: Update "ms" to 0.7.2 (#315, @DevSide)
* Package: removed superfluous version property from bower.json (#207 @kkirsche)
* Readme: fix USE_COLORS to DEBUG_COLORS
* Readme: Doc fixes for format string sugar (#269, @mlucool)
* Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0)
* Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable)
* Readme: better docs for browser support (#224, @matthewmueller)
* Tooling: Added yarn integration for development (#317, @thebigredgeek)
* Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek)
* Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman)
* Misc: Updated contributors (@thebigredgeek)
2.2.0 / 2015-05-09
==================
* package: update "ms" to v0.7.1 (#202, @dougwilson)
* README: add logging to file example (#193, @DanielOchoa)
* README: fixed a typo (#191, @amir-s)
* browser: expose `storage` (#190, @stephenmathieson)
* Makefile: add a `distclean` target (#189, @stephenmathieson)
2.1.3 / 2015-03-13
==================
* Updated stdout/stderr example (#186)
* Updated example/stdout.js to match debug current behaviour
* Renamed example/stderr.js to stdout.js
* Update Readme.md (#184)
* replace high intensity foreground color for bold (#182, #183)
2.1.2 / 2015-03-01
==================
* dist: recompile
* update "ms" to v0.7.0
* package: update "browserify" to v9.0.3
* component: fix "ms.js" repo location
* changed bower package name
* updated documentation about using debug in a browser
* fix: security error on safari (#167, #168, @yields)
2.1.1 / 2014-12-29
==================
* browser: use `typeof` to check for `console` existence
* browser: check for `console.log` truthiness (fix IE 8/9)
* browser: add support for Chrome apps
* Readme: added Windows usage remarks
* Add `bower.json` to properly support bower install
2.1.0 / 2014-10-15
==================
* node: implement `DEBUG_FD` env variable support
* package: update "browserify" to v6.1.0
* package: add "license" field to package.json (#135, @panuhorsmalahti)
2.0.0 / 2014-09-01
==================
* package: update "browserify" to v5.11.0
* node: use stderr rather than stdout for logging (#29, @stephenmathieson)
1.0.4 / 2014-07-15
==================
* dist: recompile
* example: remove `console.info()` log usage
* example: add "Content-Type" UTF-8 header to browser example
* browser: place %c marker after the space character
* browser: reset the "content" color via `color: inherit`
* browser: add colors support for Firefox >= v31
* debug: prefer an instance `log()` function over the global one (#119)
* Readme: update documentation about styled console logs for FF v31 (#116, @wryk)
1.0.3 / 2014-07-09
==================
* Add support for multiple wildcards in namespaces (#122, @seegno)
* browser: fix lint
1.0.2 / 2014-06-10
==================
* browser: update color palette (#113, @gscottolson)
* common: make console logging function configurable (#108, @timoxley)
* node: fix %o colors on old node <= 0.8.x
* Makefile: find node path using shell/which (#109, @timoxley)
1.0.1 / 2014-06-06
==================
* browser: use `removeItem()` to clear localStorage
* browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777)
* package: add "contributors" section
* node: fix comment typo
* README: list authors
1.0.0 / 2014-06-04
==================
* make ms diff be global, not be scope
* debug: ignore empty strings in enable()
* node: make DEBUG_COLORS able to disable coloring
* *: export the `colors` array
* npmignore: don't publish the `dist` dir
* Makefile: refactor to use browserify
* package: add "browserify" as a dev dependency
* Readme: add Web Inspector Colors section
* node: reset terminal color for the debug content
* node: map "%o" to `util.inspect()`
* browser: map "%j" to `JSON.stringify()`
* debug: add custom "formatters"
* debug: use "ms" module for humanizing the diff
* Readme: add "bash" syntax highlighting
* browser: add Firebug color support
* browser: add colors for WebKit browsers
* node: apply log to `console`
* rewrite: abstract common logic for Node & browsers
* add .jshintrc file
0.8.1 / 2014-04-14
==================
* package: re-add the "component" section
0.8.0 / 2014-03-30
==================
* add `enable()` method for nodejs. Closes #27
* change from stderr to stdout
* remove unnecessary index.js file
0.7.4 / 2013-11-13
==================
* remove "browserify" key from package.json (fixes something in browserify)
0.7.3 / 2013-10-30
==================
* fix: catch localStorage security error when cookies are blocked (Chrome)
* add debug(err) support. Closes #46
* add .browser prop to package.json. Closes #42
0.7.2 / 2013-02-06
==================
* fix package.json
* fix: Mobile Safari (private mode) is broken with debug
* fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript
0.7.1 / 2013-02-05
==================
* add repository URL to package.json
* add DEBUG_COLORED to force colored output
* add browserify support
* fix component. Closes #24
0.7.0 / 2012-05-04
==================
* Added .component to package.json
* Added debug.component.js build
0.6.0 / 2012-03-16
==================
* Added support for "-" prefix in DEBUG [Vinay Pulim]
* Added `.enabled` flag to the node version [TooTallNate]
0.5.0 / 2012-02-02
==================
* Added: humanize diffs. Closes #8
* Added `debug.disable()` to the CS variant
* Removed padding. Closes #10
* Fixed: persist client-side variant again. Closes #9
0.4.0 / 2012-02-01
==================
* Added browser variant support for older browsers [TooTallNate]
* Added `debug.enable('project:*')` to browser variant [TooTallNate]
* Added padding to diff (moved it to the right)
0.3.0 / 2012-01-26
==================
* Added millisecond diff when isatty, otherwise UTC string
0.2.0 / 2012-01-22
==================
* Added wildcard support
0.1.0 / 2011-12-02
==================
* Added: remove colors unless stderr isatty [TooTallNate]
0.0.1 / 2010-01-03
==================
* Initial release

View File

@ -1,19 +0,0 @@
(The MIT License)
Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca>
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

@ -1,50 +0,0 @@
# get Makefile directory name: http://stackoverflow.com/a/5982798/376773
THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd)
# BIN directory
BIN := $(THIS_DIR)/node_modules/.bin
# Path
PATH := node_modules/.bin:$(PATH)
SHELL := /bin/bash
# applications
NODE ?= $(shell which node)
YARN ?= $(shell which yarn)
PKG ?= $(if $(YARN),$(YARN),$(NODE) $(shell which npm))
BROWSERIFY ?= $(NODE) $(BIN)/browserify
.FORCE:
install: node_modules
node_modules: package.json
@NODE_ENV= $(PKG) install
@touch node_modules
lint: .FORCE
eslint browser.js debug.js index.js node.js
test-node: .FORCE
istanbul cover node_modules/mocha/bin/_mocha -- test/**.js
test-browser: .FORCE
mkdir -p dist
@$(BROWSERIFY) \
--standalone debug \
. > dist/debug.js
karma start --single-run
rimraf dist
test: .FORCE
concurrently \
"make test-node" \
"make test-browser"
coveralls:
cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js
.PHONY: all install clean distclean

View File

@ -1,312 +0,0 @@
# debug
[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers)
[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors)
A tiny node.js debugging utility modelled after node core's debugging technique.
**Discussion around the V3 API is under way [here](https://github.com/visionmedia/debug/issues/370)**
## Installation
```bash
$ npm install debug
```
## Usage
`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.
Example _app.js_:
```js
var debug = require('debug')('http')
, http = require('http')
, name = 'My App';
// fake app
debug('booting %s', name);
http.createServer(function(req, res){
debug(req.method + ' ' + req.url);
res.end('hello\n');
}).listen(3000, function(){
debug('listening');
});
// fake worker of some kind
require('./worker');
```
Example _worker.js_:
```js
var debug = require('debug')('worker');
setInterval(function(){
debug('doing some work');
}, 1000);
```
The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:
![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png)
![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png)
#### Windows note
On Windows the environment variable is set using the `set` command.
```cmd
set DEBUG=*,-not_this
```
Note that PowerShell uses different syntax to set environment variables.
```cmd
$env:DEBUG = "*,-not_this"
```
Then, run the program to be debugged as usual.
## Millisecond diff
When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.
![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png)
When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below:
![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png)
## Conventions
If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser".
## Wildcards
The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.
You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:".
## Environment Variables
When running through Node.js, you can set a few environment variables that will
change the behavior of the debug logging:
| Name | Purpose |
|-----------|-------------------------------------------------|
| `DEBUG` | Enables/disables specific debugging namespaces. |
| `DEBUG_COLORS`| Whether or not to use colors in the debug output. |
| `DEBUG_DEPTH` | Object inspection depth. |
| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |
__Note:__ The environment variables beginning with `DEBUG_` end up being
converted into an Options object that gets used with `%o`/`%O` formatters.
See the Node.js documentation for
[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options)
for the complete list.
## Formatters
Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters:
| Formatter | Representation |
|-----------|----------------|
| `%O` | Pretty-print an Object on multiple lines. |
| `%o` | Pretty-print an Object all on a single line. |
| `%s` | String. |
| `%d` | Number (both integer and float). |
| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. |
| `%%` | Single percent sign ('%'). This does not consume an argument. |
### Custom formatters
You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like:
```js
const createDebug = require('debug')
createDebug.formatters.h = (v) => {
return v.toString('hex')
}
// …elsewhere
const debug = createDebug('foo')
debug('this is hex: %h', new Buffer('hello world'))
// foo this is hex: 68656c6c6f20776f726c6421 +0ms
```
## Browser support
You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify),
or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest),
if you don't want to build it yourself.
Debug's enable state is currently persisted by `localStorage`.
Consider the situation shown below where you have `worker:a` and `worker:b`,
and wish to debug both. You can enable this using `localStorage.debug`:
```js
localStorage.debug = 'worker:*'
```
And then refresh the page.
```js
a = debug('worker:a');
b = debug('worker:b');
setInterval(function(){
a('doing some work');
}, 1000);
setInterval(function(){
b('doing some work');
}, 1200);
```
#### Web Inspector Colors
Colors are also enabled on "Web Inspectors" that understand the `%c` formatting
option. These are WebKit web inspectors, Firefox ([since version
31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))
and the Firebug plugin for Firefox (any version).
Colored output looks something like:
![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png)
## Output streams
By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method:
Example _stdout.js_:
```js
var debug = require('debug');
var error = debug('app:error');
// by default stderr is used
error('goes to stderr!');
var log = debug('app:log');
// set this namespace to log via console.log
log.log = console.log.bind(console); // don't forget to bind to console!
log('goes to stdout');
error('still goes to stderr!');
// set all output to go via console.info
// overrides all per-namespace log settings
debug.log = console.info.bind(console);
error('now goes to stdout via console.info');
log('still goes to stdout, but via console.info now');
```
## Authors
- TJ Holowaychuk
- Nathan Rajlich
- Andrew Rhyne
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)]
<a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a>
## Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)]
<a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a>
## License
(The MIT License)
Copyright (c) 2014-2016 TJ Holowaychuk &lt;tj@vision-media.ca&gt;
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

@ -1,19 +0,0 @@
{
"name": "debug",
"repo": "visionmedia/debug",
"description": "small debugging utility",
"version": "2.6.9",
"keywords": [
"debug",
"log",
"debugger"
],
"main": "src/browser.js",
"scripts": [
"src/browser.js",
"src/debug.js"
],
"dependencies": {
"rauchg/ms.js": "0.7.1"
}
}

View File

@ -1,70 +0,0 @@
// Karma configuration
// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'chai', 'sinon'],
// list of files / patterns to load in the browser
files: [
'dist/debug.js',
'test/*spec.js'
],
// list of files to exclude
exclude: [
'src/node.js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}

View File

@ -1 +0,0 @@
module.exports = require('./src/node');

View File

@ -1,49 +0,0 @@
{
"name": "debug",
"version": "2.6.9",
"repository": {
"type": "git",
"url": "git://github.com/visionmedia/debug.git"
},
"description": "small debugging utility",
"keywords": [
"debug",
"log",
"debugger"
],
"author": "TJ Holowaychuk <tj@vision-media.ca>",
"contributors": [
"Nathan Rajlich <nathan@tootallnate.net> (http://n8.io)",
"Andrew Rhyne <rhyneandrew@gmail.com>"
],
"license": "MIT",
"dependencies": {
"ms": "2.0.0"
},
"devDependencies": {
"browserify": "9.0.3",
"chai": "^3.5.0",
"concurrently": "^3.1.0",
"coveralls": "^2.11.15",
"eslint": "^3.12.1",
"istanbul": "^0.4.5",
"karma": "^1.3.0",
"karma-chai": "^0.1.0",
"karma-mocha": "^1.3.0",
"karma-phantomjs-launcher": "^1.0.2",
"karma-sinon": "^1.0.5",
"mocha": "^3.2.0",
"mocha-lcov-reporter": "^1.2.0",
"rimraf": "^2.5.4",
"sinon": "^1.17.6",
"sinon-chai": "^2.8.0"
},
"main": "./src/index.js",
"browser": "./src/browser.js",
"component": {
"scripts": {
"debug/index.js": "browser.js",
"debug/debug.js": "debug.js"
}
}
}

View File

@ -1,185 +0,0 @@
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
return true;
}
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return;
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit')
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
return window.localStorage;
} catch (e) {}
}

View File

@ -1,202 +0,0 @@
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
exports.formatters = {};
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
* @param {String} namespace
* @return {Number}
* @api private
*/
function selectColor(namespace) {
var hash = 0, i;
for (i in namespace) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return exports.colors[Math.abs(hash) % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
function debug() {
// disabled?
if (!debug.enabled) return;
var self = debug;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// turn the `arguments` into a proper Array
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %O
args.unshift('%O');
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting (colors, etc.)
exports.formatArgs.call(self, args);
var logFn = debug.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = exports.enabled(namespace);
debug.useColors = exports.useColors();
debug.color = selectColor(namespace);
// env-specific initialization logic for debug instances
if ('function' === typeof exports.init) {
exports.init(debug);
}
return debug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
exports.names = [];
exports.skips = [];
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}

View File

@ -1,10 +0,0 @@
/**
* Detect Electron renderer process, which is node, but we should
* treat as a browser.
*/
if (typeof process !== 'undefined' && process.type === 'renderer') {
module.exports = require('./browser.js');
} else {
module.exports = require('./node.js');
}

View File

@ -1,15 +0,0 @@
module.exports = inspectorLog;
// black hole
const nullStream = new (require('stream').Writable)();
nullStream._write = () => {};
/**
* Outputs a `console.log()` to the Node.js Inspector console *only*.
*/
function inspectorLog() {
const stdout = console._stdout;
console._stdout = nullStream;
console.log.apply(console, arguments);
console._stdout = stdout;
}

View File

@ -1,248 +0,0 @@
/**
* Module dependencies.
*/
var tty = require('tty');
var util = require('util');
/**
* This is the Node.js implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
/**
* Colors.
*/
exports.colors = [6, 2, 3, 4, 5, 1];
/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
*/
exports.inspectOpts = Object.keys(process.env).filter(function (key) {
return /^debug_/i.test(key);
}).reduce(function (obj, key) {
// camel-case
var prop = key
.substring(6)
.toLowerCase()
.replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
// coerce string value into JS value
var val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
else if (val === 'null') val = null;
else val = Number(val);
obj[prop] = val;
return obj;
}, {});
/**
* The file descriptor to write the `debug()` calls to.
* Set the `DEBUG_FD` env variable to override with another value. i.e.:
*
* $ DEBUG_FD=3 node script.js 3>debug.log
*/
var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
if (1 !== fd && 2 !== fd) {
util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')()
}
var stream = 1 === fd ? process.stdout :
2 === fd ? process.stderr :
createWritableStdioStream(fd);
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return 'colors' in exports.inspectOpts
? Boolean(exports.inspectOpts.colors)
: tty.isatty(fd);
}
/**
* Map %o to `util.inspect()`, all on a single line.
*/
exports.formatters.o = function(v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts)
.split('\n').map(function(str) {
return str.trim()
}).join(' ');
};
/**
* Map %o to `util.inspect()`, allowing multiple lines if needed.
*/
exports.formatters.O = function(v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts);
};
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs(args) {
var name = this.namespace;
var useColors = this.useColors;
if (useColors) {
var c = this.color;
var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
} else {
args[0] = new Date().toUTCString()
+ ' ' + name + ' ' + args[0];
}
}
/**
* Invokes `util.format()` with the specified arguments and writes to `stream`.
*/
function log() {
return stream.write(util.format.apply(util, arguments) + '\n');
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (null == namespaces) {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete process.env.DEBUG;
} else {
process.env.DEBUG = namespaces;
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Copied from `node/src/node.js`.
*
* XXX: It's lame that node doesn't expose this API out-of-the-box. It also
* relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
*/
function createWritableStdioStream (fd) {
var stream;
var tty_wrap = process.binding('tty_wrap');
// Note stream._type is used for test-module-load-list.js
switch (tty_wrap.guessHandleType(fd)) {
case 'TTY':
stream = new tty.WriteStream(fd);
stream._type = 'tty';
// Hack to have stream not keep the event loop alive.
// See https://github.com/joyent/node/issues/1726
if (stream._handle && stream._handle.unref) {
stream._handle.unref();
}
break;
case 'FILE':
var fs = require('fs');
stream = new fs.SyncWriteStream(fd, { autoClose: false });
stream._type = 'fs';
break;
case 'PIPE':
case 'TCP':
var net = require('net');
stream = new net.Socket({
fd: fd,
readable: false,
writable: true
});
// FIXME Should probably have an option in net.Socket to create a
// stream from an existing fd which is writable only. But for now
// we'll just add this hack and set the `readable` member to false.
// Test: ./node test/fixtures/echo.js < /etc/passwd
stream.readable = false;
stream.read = null;
stream._type = 'pipe';
// FIXME Hack to have stream not keep the event loop alive.
// See https://github.com/joyent/node/issues/1726
if (stream._handle && stream._handle.unref) {
stream._handle.unref();
}
break;
default:
// Probably an error on in uv_guess_handle()
throw new Error('Implement me. Unknown stream file type!');
}
// For supporting legacy API we put the FD here.
stream.fd = fd;
stream._isStdio = true;
return stream;
}
/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/
function init (debug) {
debug.inspectOpts = {};
var keys = Object.keys(exports.inspectOpts);
for (var i = 0; i < keys.length; i++) {
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
}
/**
* Enable namespaces listed in `process.env.DEBUG` initially.
*/
exports.enable(load());

Some files were not shown because too many files have changed in this diff Show More