Added remote folder

This commit is contained in:
Kasper Rynning-Tønnesen
2015-11-29 13:30:54 +01:00
parent 97e7dfd7c4
commit 95bb0c3919
3521 changed files with 331825 additions and 0 deletions

21
server/node_modules/gulp/node_modules/chalk/license generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

20
server/node_modules/gulp/node_modules/gulp-util/LICENSE generated vendored Executable file
View File

@@ -0,0 +1,20 @@
Copyright (c) 2014 Fractal <contact@wearefractal.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,146 @@
# gulp-util [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Dependency Status][depstat-image]][depstat-url]
## Information
<table>
<tr>
<td>Package</td><td>gulp-util</td>
</tr>
<tr>
<td>Description</td>
<td>Utility functions for gulp plugins</td>
</tr>
<tr>
<td>Node Version</td>
<td>>= 0.10</td>
</tr>
</table>
## Usage
```javascript
var gutil = require('gulp-util');
gutil.log('stuff happened', 'Really it did', gutil.colors.magenta('123'));
gutil.beep();
gutil.replaceExtension('file.coffee', '.js'); // file.js
var opt = {
name: 'todd',
file: someGulpFile
};
gutil.template('test <%= name %> <%= file.path %>', opt) // test todd /js/hi.js
```
### log(msg...)
Logs stuff. Already prefixed with [gulp] and all that. If you pass in multiple arguments it will join them by a space.
The default gulp coloring using gutil.colors.<color>:
```
values (files, module names, etc.) = cyan
numbers (times, counts, etc) = magenta
```
### colors
Is an instance of [chalk](https://github.com/sindresorhus/chalk).
### replaceExtension(path, newExtension)
Replaces a file extension in a path. Returns the new path.
### isStream(obj)
Returns true or false if an object is a stream.
### isBuffer(obj)
Returns true or false if an object is a Buffer.
### template(string[, data])
This is a lodash.template function wrapper. You must pass in a valid gulp file object so it is available to the user or it will error. You can not configure any of the delimiters. Look at the [lodash docs](http://lodash.com/docs#template) for more info.
## new File(obj)
This is just [vinyl](https://github.com/wearefractal/vinyl)
```javascript
var file = new gutil.File({
base: path.join(__dirname, './fixtures/'),
cwd: __dirname,
path: path.join(__dirname, './fixtures/test.coffee')
});
```
## noop()
Returns a stream that does nothing but pass data straight through.
```javascript
// gulp should be called like this :
// $ gulp --type production
gulp.task('scripts', function() {
gulp.src('src/**/*.js')
.pipe(concat('script.js'))
.pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())
.pipe(gulp.dest('dist/'));
});
```
## buffer(cb)
This is similar to es.wait but instead of buffering text into one string it buffers anything into an array (so very useful for file objects).
Returns a stream that can be piped to.
The stream will emit one data event after the stream piped to it has ended. The data will be the same array passed to the callback.
Callback is optional and receives two arguments: error and data
```javascript
gulp.src('stuff/*.js')
.pipe(gutil.buffer(function(err, files) {
}));
```
## new PluginError(pluginName, message[, options])
- pluginName should be the module name of your plugin
- message can be a string or an existing error
- By default the stack will not be shown. Set `options.showStack` to true if you think the stack is important for your error.
- If you pass an error in as the message the stack will be pulled from that, otherwise one will be created.
- Note that if you pass in a custom stack string you need to include the message along with that.
- Error properties will be included in `err.toString()`. Can be omitted by including `{showProperties: false}` in the options.
These are all acceptable forms of instantiation:
```javascript
var err = new gutil.PluginError('test', {
message: 'something broke'
});
var err = new gutil.PluginError({
plugin: 'test',
message: 'something broke'
});
var err = new gutil.PluginError('test', 'something broke');
var err = new gutil.PluginError('test', 'something broke', {showStack: true});
var existingError = new Error('OMG');
var err = new gutil.PluginError('test', existingError, {showStack: true});
```
[npm-url]: https://www.npmjs.com/package/gulp-util
[npm-image]: https://badge.fury.io/js/gulp-util.svg
[travis-url]: https://travis-ci.org/gulpjs/gulp-util
[travis-image]: https://img.shields.io/travis/gulpjs/gulp-util.svg?branch=master
[coveralls-url]: https://coveralls.io/r/gulpjs/gulp-util
[coveralls-image]: https://img.shields.io/coveralls/gulpjs/gulp-util.svg
[depstat-url]: https://david-dm.org/gulpjs/gulp-util
[depstat-image]: https://david-dm.org/gulpjs/gulp-util.svg

View File

@@ -0,0 +1,18 @@
module.exports = {
File: require('vinyl'),
replaceExtension: require('replace-ext'),
colors: require('chalk'),
date: require('dateformat'),
log: require('./lib/log'),
template: require('./lib/template'),
env: require('./lib/env'),
beep: require('beeper'),
noop: require('./lib/noop'),
isStream: require('./lib/isStream'),
isBuffer: require('./lib/isBuffer'),
isNull: require('./lib/isNull'),
linefeed: '\n',
combine: require('./lib/combine'),
buffer: require('./lib/buffer'),
PluginError: require('./lib/PluginError')
};

View File

@@ -0,0 +1,130 @@
var util = require('util');
var arrayDiffer = require('array-differ');
var arrayUniq = require('array-uniq');
var chalk = require('chalk');
var objectAssign = require('object-assign');
var nonEnumberableProperties = ['name', 'message', 'stack'];
var propertiesNotToDisplay = nonEnumberableProperties.concat(['plugin', 'showStack', 'showProperties', '__safety', '_stack']);
// wow what a clusterfuck
var parseOptions = function(plugin, message, opt) {
opt = opt || {};
if (typeof plugin === 'object') {
opt = plugin;
} else {
if (message instanceof Error) {
opt.error = message;
} else if (typeof message === 'object') {
opt = message;
} else {
opt.message = message;
}
opt.plugin = plugin;
}
return objectAssign({
showStack: false,
showProperties: true
}, opt);
};
function PluginError(plugin, message, opt) {
if (!(this instanceof PluginError)) throw new Error('Call PluginError using new');
Error.call(this);
var options = parseOptions(plugin, message, opt);
var self = this;
// if options has an error, grab details from it
if (options.error) {
// These properties are not enumerable, so we have to add them explicitly.
arrayUniq(Object.keys(options.error).concat(nonEnumberableProperties))
.forEach(function(prop) {
self[prop] = options.error[prop];
});
}
var properties = ['name', 'message', 'fileName', 'lineNumber', 'stack', 'showStack', 'showProperties', 'plugin'];
// options object can override
properties.forEach(function(prop) {
if (prop in options) this[prop] = options[prop];
}, this);
// defaults
if (!this.name) this.name = 'Error';
if (!this.stack) {
// Error.captureStackTrace appends a stack property which relies on the toString method of the object it is applied to.
// Since we are using our own toString method which controls when to display the stack trace if we don't go through this
// safety object, then we'll get stack overflow problems.
var safety = {
toString: function() {
return this._messageWithDetails() + '\nStack:';
}.bind(this)
};
Error.captureStackTrace(safety, arguments.callee || this.constructor);
this.__safety = safety;
}
if (!this.plugin) throw new Error('Missing plugin name');
if (!this.message) throw new Error('Missing error message');
}
util.inherits(PluginError, Error);
PluginError.prototype._messageWithDetails = function() {
var messageWithDetails = 'Message:\n ' + this.message;
var details = this._messageDetails();
if (details !== '') {
messageWithDetails += '\n' + details;
}
return messageWithDetails;
};
PluginError.prototype._messageDetails = function() {
if (!this.showProperties) {
return '';
}
var properties = arrayDiffer(Object.keys(this), propertiesNotToDisplay);
if (properties.length === 0) {
return '';
}
var self = this;
properties = properties.map(function stringifyProperty(prop) {
return ' ' + prop + ': ' + self[prop];
});
return 'Details:\n' + properties.join('\n');
};
PluginError.prototype.toString = function () {
var sig = chalk.red(this.name) + ' in plugin \'' + chalk.cyan(this.plugin) + '\'';
var detailsWithStack = function(stack) {
return this._messageWithDetails() + '\nStack:\n' + stack;
}.bind(this);
var msg;
if (this.showStack) {
if (this.__safety) { // There is no wrapped error, use the stack captured in the PluginError ctor
msg = this.__safety.stack;
} else if (this._stack) {
msg = detailsWithStack(this._stack);
} else { // Stack from wrapped error
msg = detailsWithStack(this.stack);
}
} else {
msg = this._messageWithDetails();
}
return sig + '\n' + msg;
};
module.exports = PluginError;

View File

@@ -0,0 +1,15 @@
var through = require('through2');
module.exports = function(fn) {
var buf = [];
var end = function(cb) {
this.push(buf);
cb();
if(fn) fn(null, buf);
};
var push = function(data, enc, cb) {
buf.push(data);
cb();
};
return through.obj(push, end);
};

View File

@@ -0,0 +1,11 @@
var pipeline = require('multipipe');
module.exports = function(){
var args = arguments;
if (args.length === 1 && Array.isArray(args[0])) {
args = args[0];
}
return function(){
return pipeline.apply(pipeline, args);
};
};

View File

@@ -0,0 +1,4 @@
var parseArgs = require('minimist');
var argv = parseArgs(process.argv.slice(2));
module.exports = argv;

View File

@@ -0,0 +1,7 @@
var buf = require('buffer');
var Buffer = buf.Buffer;
// could use Buffer.isBuffer but this is the same exact thing...
module.exports = function(o) {
return typeof o === 'object' && o instanceof Buffer;
};

View File

@@ -0,0 +1,3 @@
module.exports = function(v) {
return v === null;
};

View File

@@ -0,0 +1,5 @@
var Stream = require('stream').Stream;
module.exports = function(o) {
return !!o && o instanceof Stream;
};

View File

@@ -0,0 +1,14 @@
var hasGulplog = require('has-gulplog');
module.exports = function(){
if(hasGulplog()){
// specifically deferring loading here to keep from registering it globally
var gulplog = require('gulplog');
gulplog.info.apply(gulplog, arguments);
} else {
// specifically defering loading because it might not be used
var fancylog = require('fancy-log');
fancylog.apply(null, arguments);
}
return this;
};

View File

@@ -0,0 +1,5 @@
var through = require('through2');
module.exports = function () {
return through.obj();
};

View File

@@ -0,0 +1,23 @@
var template = require('lodash.template');
var reEscape = require('lodash._reescape');
var reEvaluate = require('lodash._reevaluate');
var reInterpolate = require('lodash._reinterpolate');
var forcedSettings = {
escape: reEscape,
evaluate: reEvaluate,
interpolate: reInterpolate
};
module.exports = function(tmpl, data) {
var fn = template(tmpl, forcedSettings);
var wrapped = function(o) {
if (typeof o === 'undefined' || typeof o.file === 'undefined') {
throw new Error('Failed to provide the current file as "file" to the template');
}
return fn(o);
};
return (data ? wrapped(data) : wrapped);
};

View File

@@ -0,0 +1 @@
../dateformat/bin/cli.js

View File

@@ -0,0 +1,7 @@
'use strict';
module.exports = function (arr) {
var rest = [].concat.apply([], [].slice.call(arguments, 1));
return arr.filter(function (el) {
return rest.indexOf(el) === -1;
});
};

View File

@@ -0,0 +1,61 @@
{
"name": "array-differ",
"version": "1.0.0",
"description": "Create an array with values that are present in the first input array but not additional ones",
"license": "MIT",
"repository": {
"type": "git",
"url": "git://github.com/sindresorhus/array-differ"
},
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "http://sindresorhus.com"
},
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "mocha"
},
"files": [
"index.js"
],
"keywords": [
"array",
"difference",
"diff",
"differ",
"filter",
"exclude"
],
"devDependencies": {
"mocha": "*"
},
"gitHead": "e91802976c4710eef8dea2090d48e48525cf41b1",
"bugs": {
"url": "https://github.com/sindresorhus/array-differ/issues"
},
"homepage": "https://github.com/sindresorhus/array-differ",
"_id": "array-differ@1.0.0",
"_shasum": "eff52e3758249d33be402b8bb8e564bb2b5d4031",
"_from": "array-differ@^1.0.0",
"_npmVersion": "1.4.14",
"_npmUser": {
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
},
"maintainers": [
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"dist": {
"shasum": "eff52e3758249d33be402b8bb8e564bb2b5d4031",
"tarball": "http://registry.npmjs.org/array-differ/-/array-differ-1.0.0.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/array-differ/-/array-differ-1.0.0.tgz",
"readme": "ERROR: No README data found!"
}

View File

@@ -0,0 +1,41 @@
# array-differ [![Build Status](https://travis-ci.org/sindresorhus/array-differ.svg?branch=master)](https://travis-ci.org/sindresorhus/array-differ)
> Create an array with values that are present in the first input array but not additional ones
## Install
```sh
$ npm install --save array-differ
```
## Usage
```js
var arrayDiffer = require('array-differ');
arrayDiffer([2, 3, 4], [3, 50]);
//=> [2, 4]
```
## API
### arrayDiffer(input, values, [values, ...])
Returns the new array.
#### input
Type: `array`
#### values
Type: `array`
Arrays of values to exclude.
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View File

@@ -0,0 +1,60 @@
'use strict';
// there's 3 implementations written in increasing order of efficiency
// 1 - no Set type is defined
function uniqNoSet(arr) {
var ret = [];
for (var i = 0; i < arr.length; i++) {
if (ret.indexOf(arr[i]) === -1) {
ret.push(arr[i]);
}
}
return ret;
}
// 2 - a simple Set type is defined
function uniqSet(arr) {
var seen = new Set();
return arr.filter(function (el) {
if (!seen.has(el)) {
seen.add(el);
return true;
}
});
}
// 3 - a standard Set type is defined and it has a forEach method
function uniqSetWithForEach(arr) {
var ret = [];
(new Set(arr)).forEach(function (el) {
ret.push(el);
});
return ret;
}
// V8 currently has a broken implementation
// https://github.com/joyent/node/issues/8449
function doesForEachActuallyWork() {
var ret = false;
(new Set([true])).forEach(function (el) {
ret = el;
});
return ret === true;
}
if ('Set' in global) {
if (typeof Set.prototype.forEach === 'function' && doesForEachActuallyWork()) {
module.exports = uniqSetWithForEach;
} else {
module.exports = uniqSet;
}
} else {
module.exports = uniqNoSet;
}

View File

@@ -0,0 +1,66 @@
{
"name": "array-uniq",
"version": "1.0.2",
"description": "Create an array without duplicates",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/sindresorhus/array-uniq"
},
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "http://sindresorhus.com"
},
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "mocha"
},
"files": [
"index.js"
],
"keywords": [
"array",
"arr",
"set",
"uniq",
"unique",
"es6",
"duplicate",
"remove"
],
"devDependencies": {
"es6-set": "^0.1.0",
"mocha": "*",
"require-uncached": "^1.0.2"
},
"gitHead": "d5e311f37692dfd25ec216490df10632ce5f69f3",
"bugs": {
"url": "https://github.com/sindresorhus/array-uniq/issues"
},
"homepage": "https://github.com/sindresorhus/array-uniq",
"_id": "array-uniq@1.0.2",
"_shasum": "5fcc373920775723cfd64d65c64bef53bf9eba6d",
"_from": "array-uniq@^1.0.2",
"_npmVersion": "2.1.5",
"_nodeVersion": "0.10.32",
"_npmUser": {
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
},
"maintainers": [
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"dist": {
"shasum": "5fcc373920775723cfd64d65c64bef53bf9eba6d",
"tarball": "http://registry.npmjs.org/array-uniq/-/array-uniq-1.0.2.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.2.tgz",
"readme": "ERROR: No README data found!"
}

View File

@@ -0,0 +1,30 @@
# array-uniq [![Build Status](https://travis-ci.org/sindresorhus/array-uniq.svg?branch=master)](https://travis-ci.org/sindresorhus/array-uniq)
> Create an array without duplicates
It's already pretty fast, but will be much faster when [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) becomes available in V8 (especially with large arrays).
## Install
```sh
$ npm install --save array-uniq
```
## Usage
```js
var arrayUniq = require('array-uniq');
arrayUniq([1, 1, 2, 3, 3]);
//=> [1, 2, 3]
arrayUniq(['foo', 'foo', 'bar', 'foo']);
//=> ['foo', 'bar']
```
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View File

@@ -0,0 +1,61 @@
'use strict';
var BEEP_DELAY = 500;
if (!process.stdout.isTTY ||
process.argv.indexOf('--no-beep') !== -1 ||
process.argv.indexOf('--beep=false') !== -1) {
module.exports = function () {};
return;
}
function beep() {
process.stdout.write('\u0007');
}
function melodicalBeep(val, cb) {
if (val.length === 0) {
cb();
return;
}
setTimeout(function () {
if (val.shift() === '*') {
beep();
}
melodicalBeep(val, cb);
}, BEEP_DELAY);
}
module.exports = function (val, cb) {
cb = cb || function () {};
if (val === parseInt(val)) {
if (val < 0) {
throw new TypeError('Negative numbers are not accepted');
}
if (val === 0) {
cb();
return;
}
for (var i = 0; i < val; i++) {
setTimeout(function (i) {
beep();
if (i === val - 1) {
cb();
}
}, BEEP_DELAY * i, i);
}
} else if (!val) {
beep();
cb();
} else if (typeof val === 'string') {
melodicalBeep(val.split(''), cb);
} else {
throw new TypeError('Not an accepted type');
}
};

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,68 @@
{
"name": "beeper",
"version": "1.1.0",
"description": "Make your terminal beep",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/sindresorhus/beeper"
},
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "node test.js"
},
"files": [
"index.js"
],
"keywords": [
"beep",
"beeper",
"boop",
"terminal",
"term",
"cli",
"console",
"ding",
"ping",
"alert",
"gulpfriendly"
],
"devDependencies": {
"hooker": "^0.2.3",
"tape": "^4.0.0"
},
"gitHead": "8beb0413a8028ca2d52dbb86c75f42069535591b",
"bugs": {
"url": "https://github.com/sindresorhus/beeper/issues"
},
"homepage": "https://github.com/sindresorhus/beeper",
"_id": "beeper@1.1.0",
"_shasum": "9ee6fc1ce7f54feaace7ce73588b056037866a2c",
"_from": "beeper@^1.0.0",
"_npmVersion": "2.10.1",
"_nodeVersion": "0.12.4",
"_npmUser": {
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
},
"dist": {
"shasum": "9ee6fc1ce7f54feaace7ce73588b056037866a2c",
"tarball": "http://registry.npmjs.org/beeper/-/beeper-1.1.0.tgz"
},
"maintainers": [
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"directories": {},
"_resolved": "https://registry.npmjs.org/beeper/-/beeper-1.1.0.tgz",
"readme": "ERROR: No README data found!"
}

View File

@@ -0,0 +1,55 @@
# beeper [![Build Status](https://travis-ci.org/sindresorhus/beeper.svg?branch=master)](https://travis-ci.org/sindresorhus/beeper)
> Make your terminal beep
![](https://cloud.githubusercontent.com/assets/170270/5261236/f8471100-7a49-11e4-81af-96cd09a522d9.gif)
Useful as an attention grabber e.g. when an error happens.
## Install
```
$ npm install --save beeper
```
## Usage
```js
var beeper = require('beeper');
beeper();
// beep one time
beeper(3);
// beep three times
beeper('****-*-*');
// beep, beep, beep, beep, pause, beep, pause, beep
```
## API
It will not beep if stdout is not TTY or if the user supplies the `--no-beep` flag.
### beeper([count|melody], [callback])
#### count
Type: `number`
Default: `1`
How many times you want it to beep.
#### melody
Type: `string`
Construct your own melody by supplying a string of `*` for beep `-` for pause.
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View File

@@ -0,0 +1,57 @@
# .gitignore <https://github.com/tunnckoCore/dotfiles>
#
# Copyright (c) 2014 Charlike Mike Reagent, contributors.
# Released under the MIT license.
#
# Always-ignore dirs #
# ####################
_gh_pages
node_modules
bower_components
components
vendor
build
dest
dist
src
lib-cov
coverage
nbproject
cache
temp
tmp
# Packages #
# ##########
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
# OS, Logs and databases #
# #########################
*.pid
*.dat
*.log
*.sql
*.sqlite
*~
~*
# Another files #
# ###############
Icon?
.DS_Store*
Thumbs.db
ehthumbs.db
Desktop.ini
npm-debug.log
.directory
._*
koa-better-body

View File

@@ -0,0 +1,4 @@
language: node_js
node_js:
- "0.11"
- "0.10"

View File

@@ -0,0 +1,20 @@
(c) 2007-2009 Steven Levithan <stevenlevithan.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,82 @@
# dateformat
A node.js package for Steven Levithan's excellent [dateFormat()][dateformat] function.
[![Build Status](https://travis-ci.org/felixge/node-dateformat.svg)](https://travis-ci.org/felixge/node-dateformat)
## Modifications
* Removed the `Date.prototype.format` method. Sorry folks, but extending native prototypes is for suckers.
* Added a `module.exports = dateFormat;` statement at the bottom
* Added the placeholder `N` to get the ISO 8601 numeric representation of the day of the week
## Installation
```bash
$ npm install dateformat
$ dateformat --help
```
## Usage
As taken from Steven's post, modified to match the Modifications listed above:
```js
var dateFormat = require('dateformat');
var now = new Date();
// Basic usage
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM
// You can use one of several named masks
dateFormat(now, "isoDateTime");
// 2007-06-09T17:46:21
// ...Or add your own
dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
dateFormat(now, "hammerTime");
// 17:46! Can't touch this!
// When using the standalone dateFormat function,
// you can also provide the date as a string
dateFormat("Jun 9 2007", "fullDate");
// Saturday, June 9, 2007
// Note that if you don't include the mask argument,
// dateFormat.masks.default is used
dateFormat(now);
// Sat Jun 09 2007 17:46:21
// And if you don't include the date argument,
// the current date and time is used
dateFormat();
// Sat Jun 09 2007 17:46:22
// You can also skip the date argument (as long as your mask doesn't
// contain any numbers), in which case the current date/time is used
dateFormat("longTime");
// 5:46:22 PM EST
// And finally, you can convert local time to UTC time. Simply pass in
// true as an additional argument (no argument skipping allowed in this case):
dateFormat(now, "longTime", true);
// 10:46:21 PM UTC
// ...Or add the prefix "UTC:" or "GMT:" to your mask.
dateFormat(now, "UTC:h:MM:ss TT Z");
// 10:46:21 PM UTC
// You can also get the ISO 8601 week of the year:
dateFormat(now, "W");
// 42
// and also get the ISO 8601 numeric representation of the day of the week:
dateFormat(now,"N");
// 6
```
## License
(c) 2007-2009 Steven Levithan [stevenlevithan.com][stevenlevithan], MIT license.
[dateformat]: http://blog.stevenlevithan.com/archives/date-time-format
[stevenlevithan]: http://stevenlevithan.com/

View File

@@ -0,0 +1,75 @@
#!/usr/bin/env node
/**
* dateformat <https://github.com/felixge/node-dateformat>
*
* Copyright (c) 2014 Charlike Mike Reagent (cli), contributors.
* Released under the MIT license.
*/
'use strict';
/**
* Module dependencies.
*/
var dateFormat = require('../lib/dateformat');
var meow = require('meow');
var stdin = require('get-stdin');
var cli = meow({
pkg: '../package.json',
help: [
'Options',
' --help Show this help',
' --version Current version of package',
' -d | --date Date that want to format (Date object as Number or String)',
' -m | --mask Mask that will use to format the date',
' -u | --utc Convert local time to UTC time or use `UTC:` prefix in mask',
' -g | --gmt You can use `GMT:` prefix in mask',
'',
'Usage',
' dateformat [date] [mask]',
' dateformat "Nov 26 2014" "fullDate"',
' dateformat 1416985417095 "dddd, mmmm dS, yyyy, h:MM:ss TT"',
' dateformat 1315361943159 "W"',
' dateformat "UTC:h:MM:ss TT Z"',
' dateformat "longTime" true',
' dateformat "longTime" false true',
' dateformat "Jun 9 2007" "fullDate" true',
' date +%s | dateformat',
''
].join('\n')
})
var date = cli.input[0] || cli.flags.d || cli.flags.date || Date.now();
var mask = cli.input[1] || cli.flags.m || cli.flags.mask || dateFormat.masks.default;
var utc = cli.input[2] || cli.flags.u || cli.flags.utc || false;
var gmt = cli.input[3] || cli.flags.g || cli.flags.gmt || false;
utc = utc === 'true' ? true : false;
gmt = gmt === 'true' ? true : false;
if (!cli.input.length) {
stdin(function(date) {
console.log(dateFormat(date, dateFormat.masks.default, utc, gmt));
});
return;
}
if (cli.input.length === 1 && date) {
mask = date;
date = Date.now();
console.log(dateFormat(date, mask, utc, gmt));
return;
}
if (cli.input.length >= 2 && date && mask) {
if (mask === 'true' || mask === 'false') {
utc = mask === 'true' ? true : false;
gmt = !utc;
mask = date
date = Date.now();
}
console.log(dateFormat(date, mask, utc, gmt));
return;
}

View File

@@ -0,0 +1,226 @@
/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/
(function(global) {
'use strict';
var dateFormat = (function() {
var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZWN]|'[^']*'|'[^']*'/g;
var timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g;
var timezoneClip = /[^-+\dA-Z]/g;
// Regexes and supporting functions are cached through closure
return function (date, mask, utc, gmt) {
// You can't provide utc if you skip other args (use the 'UTC:' mask prefix)
if (arguments.length === 1 && kindOf(date) === 'string' && !/\d/.test(date)) {
mask = date;
date = undefined;
}
date = date || new Date;
if(!(date instanceof Date)) {
date = new Date(date);
}
if (isNaN(date)) {
throw TypeError('Invalid date');
}
mask = String(dateFormat.masks[mask] || mask || dateFormat.masks['default']);
// Allow setting the utc/gmt argument via the mask
var maskSlice = mask.slice(0, 4);
if (maskSlice === 'UTC:' || maskSlice === 'GMT:') {
mask = mask.slice(4);
utc = true;
if (maskSlice === 'GMT:') {
gmt = true;
}
}
var _ = utc ? 'getUTC' : 'get';
var d = date[_ + 'Date']();
var D = date[_ + 'Day']();
var m = date[_ + 'Month']();
var y = date[_ + 'FullYear']();
var H = date[_ + 'Hours']();
var M = date[_ + 'Minutes']();
var s = date[_ + 'Seconds']();
var L = date[_ + 'Milliseconds']();
var o = utc ? 0 : date.getTimezoneOffset();
var W = getWeek(date);
var N = getDayOfWeek(date);
var flags = {
d: d,
dd: pad(d),
ddd: dateFormat.i18n.dayNames[D],
dddd: dateFormat.i18n.dayNames[D + 7],
m: m + 1,
mm: pad(m + 1),
mmm: dateFormat.i18n.monthNames[m],
mmmm: dateFormat.i18n.monthNames[m + 12],
yy: String(y).slice(2),
yyyy: y,
h: H % 12 || 12,
hh: pad(H % 12 || 12),
H: H,
HH: pad(H),
M: M,
MM: pad(M),
s: s,
ss: pad(s),
l: pad(L, 3),
L: pad(Math.round(L / 10)),
t: H < 12 ? 'a' : 'p',
tt: H < 12 ? 'am' : 'pm',
T: H < 12 ? 'A' : 'P',
TT: H < 12 ? 'AM' : 'PM',
Z: gmt ? 'GMT' : utc ? 'UTC' : (String(date).match(timezone) || ['']).pop().replace(timezoneClip, ''),
o: (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
S: ['th', 'st', 'nd', 'rd'][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10],
W: W,
N: N
};
return mask.replace(token, function (match) {
if (match in flags) {
return flags[match];
}
return match.slice(1, match.length - 1);
});
};
})();
dateFormat.masks = {
'default': 'ddd mmm dd yyyy HH:MM:ss',
'shortDate': 'm/d/yy',
'mediumDate': 'mmm d, yyyy',
'longDate': 'mmmm d, yyyy',
'fullDate': 'dddd, mmmm d, yyyy',
'shortTime': 'h:MM TT',
'mediumTime': 'h:MM:ss TT',
'longTime': 'h:MM:ss TT Z',
'isoDate': 'yyyy-mm-dd',
'isoTime': 'HH:MM:ss',
'isoDateTime': 'yyyy-mm-dd\'T\'HH:MM:sso',
'isoUtcDateTime': 'UTC:yyyy-mm-dd\'T\'HH:MM:ss\'Z\'',
'expiresHeaderFormat': 'ddd, dd mmm yyyy HH:MM:ss Z'
};
// Internationalization strings
dateFormat.i18n = {
dayNames: [
'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat',
'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
],
monthNames: [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'
]
};
function pad(val, len) {
val = String(val);
len = len || 2;
while (val.length < len) {
val = '0' + val;
}
return val;
}
/**
* Get the ISO 8601 week number
* Based on comments from
* http://techblog.procurios.nl/k/n618/news/view/33796/14863/Calculate-ISO-8601-week-and-year-in-javascript.html
*
* @param {Object} `date`
* @return {Number}
*/
function getWeek(date) {
// Remove time components of date
var targetThursday = new Date(date.getFullYear(), date.getMonth(), date.getDate());
// Change date to Thursday same week
targetThursday.setDate(targetThursday.getDate() - ((targetThursday.getDay() + 6) % 7) + 3);
// Take January 4th as it is always in week 1 (see ISO 8601)
var firstThursday = new Date(targetThursday.getFullYear(), 0, 4);
// Change date to Thursday same week
firstThursday.setDate(firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3);
// Check if daylight-saving-time-switch occured and correct for it
var ds = targetThursday.getTimezoneOffset() - firstThursday.getTimezoneOffset();
targetThursday.setHours(targetThursday.getHours() - ds);
// Number of weeks between target Thursday and first Thursday
var weekDiff = (targetThursday - firstThursday) / (86400000*7);
return 1 + Math.floor(weekDiff);
}
/**
* Get ISO-8601 numeric representation of the day of the week
* 1 (for Monday) through 7 (for Sunday)
*
* @param {Object} `date`
* @return {Number}
*/
function getDayOfWeek(date) {
var dow = date.getDay();
if(dow === 0) {
dow = 7;
}
return dow;
}
/**
* kind-of shortcut
* @param {*} val
* @return {String}
*/
function kindOf(val) {
if (val === null) {
return 'null';
}
if (val === undefined) {
return 'undefined';
}
if (typeof val !== 'object') {
return typeof val;
}
if (Array.isArray(val)) {
return 'array';
}
return {}.toString.call(val)
.slice(8, -1).toLowerCase();
};
if (typeof define === 'function' && define.amd) {
define(function () {
return dateFormat;
});
} else if (typeof exports === 'object') {
module.exports = dateFormat;
} else {
global.dateFormat = dateFormat;
}
})(this);

View File

@@ -0,0 +1,49 @@
'use strict';
module.exports = function (cb) {
var stdin = process.stdin;
var ret = '';
if (stdin.isTTY) {
setImmediate(cb, '');
return;
}
stdin.setEncoding('utf8');
stdin.on('readable', function () {
var chunk;
while (chunk = stdin.read()) {
ret += chunk;
}
});
stdin.on('end', function () {
cb(ret);
});
};
module.exports.buffer = function (cb) {
var stdin = process.stdin;
var ret = [];
var len = 0;
if (stdin.isTTY) {
setImmediate(cb, new Buffer(''));
return;
}
stdin.on('readable', function () {
var chunk;
while (chunk = stdin.read()) {
ret.push(chunk);
len += chunk.length;
}
});
stdin.on('end', function () {
cb(Buffer.concat(ret, len));
});
};

View File

@@ -0,0 +1,64 @@
{
"name": "get-stdin",
"version": "4.0.1",
"description": "Easier stdin",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/sindresorhus/get-stdin"
},
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "http://sindresorhus.com"
},
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "node test.js && node test-buffer.js && echo unicorns | node test-real.js"
},
"files": [
"index.js"
],
"keywords": [
"std",
"stdin",
"stdio",
"concat",
"buffer",
"stream",
"process",
"stream"
],
"devDependencies": {
"ava": "0.0.4",
"buffer-equal": "0.0.1"
},
"gitHead": "65c744975229b25d6cc5c7546f49b6ad9099553f",
"bugs": {
"url": "https://github.com/sindresorhus/get-stdin/issues"
},
"homepage": "https://github.com/sindresorhus/get-stdin",
"_id": "get-stdin@4.0.1",
"_shasum": "b968c6b0a04384324902e8bf1a5df32579a450fe",
"_from": "get-stdin@^4.0.1",
"_npmVersion": "1.4.28",
"_npmUser": {
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
},
"maintainers": [
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"dist": {
"shasum": "b968c6b0a04384324902e8bf1a5df32579a450fe",
"tarball": "http://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz",
"readme": "ERROR: No README data found!"
}

View File

@@ -0,0 +1,44 @@
# get-stdin [![Build Status](https://travis-ci.org/sindresorhus/get-stdin.svg?branch=master)](https://travis-ci.org/sindresorhus/get-stdin)
> Easier stdin
## Install
```sh
$ npm install --save get-stdin
```
## Usage
```js
// example.js
var stdin = require('get-stdin');
stdin(function (data) {
console.log(data);
//=> unicorns
});
```
```sh
$ echo unicorns | node example.js
unicorns
```
## API
### stdin(callback)
Get `stdin` as a string.
### stdin.buffer(callback)
Get `stdin` as a buffer.
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View File

@@ -0,0 +1,74 @@
'use strict';
var path = require('path');
var minimist = require('minimist');
var objectAssign = require('object-assign');
var camelcaseKeys = require('camelcase-keys');
var trimNewlines = require('trim-newlines');
var redent = require('redent');
var readPkgUp = require('read-pkg-up');
var loudRejection = require('loud-rejection');
var normalizePackageData = require('normalize-package-data');
// get the uncached parent
delete require.cache[__filename];
var parentDir = path.dirname(module.parent.filename);
module.exports = function (opts, minimistOpts) {
loudRejection();
if (Array.isArray(opts) || typeof opts === 'string') {
opts = {help: opts};
}
opts = objectAssign({
pkg: readPkgUp.sync({
cwd: parentDir,
normalize: false
}).pkg,
argv: process.argv.slice(2)
}, opts);
if (Array.isArray(opts.help)) {
opts.help = opts.help.join('\n');
}
var pkg = typeof opts.pkg === 'string' ? require(path.join(parentDir, opts.pkg)) : opts.pkg;
var argv = minimist(opts.argv, minimistOpts);
var help = redent(trimNewlines(opts.help || ''), 2);
normalizePackageData(pkg);
process.title = pkg.bin ? Object.keys(pkg.bin)[0] : pkg.name;
var description = opts.description;
if (!description && description !== false) {
description = pkg.description;
}
help = (description ? '\n ' + description + '\n' : '') + (help ? '\n' + help : '\n');
var showHelp = function (code) {
console.log(help);
process.exit(code || 0);
};
if (argv.version && opts.version !== false) {
console.log(typeof opts.version === 'string' ? opts.version : pkg.version);
process.exit();
}
if (argv.help && opts.help !== false) {
showHelp();
}
var _ = argv._;
delete argv._;
return {
input: _,
flags: camelcaseKeys(argv),
pkg: pkg,
help: help,
showHelp: showHelp
};
};

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,9 @@
'use strict';
var mapObj = require('map-obj');
var camelCase = require('camelcase');
module.exports = function (obj) {
return mapObj(obj, function (key, val) {
return [camelCase(key), val];
});
};

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,35 @@
'use strict';
module.exports = function () {
var str = [].map.call(arguments, function (str) {
return str.trim();
}).filter(function (str) {
return str.length;
}).join('-');
if (!str.length) {
return '';
}
if (str.length === 1) {
return str;
}
if (!(/[_.\- ]+/).test(str)) {
if (str === str.toUpperCase()) {
return str.toLowerCase();
}
if (str[0] !== str[0].toLowerCase()) {
return str[0].toLowerCase() + str.slice(1);
}
return str;
}
return str
.replace(/^[_.\- ]+/, '')
.toLowerCase()
.replace(/[_.\- ]+(\w|$)/g, function (m, p1) {
return p1.toUpperCase();
});
};

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,69 @@
{
"name": "camelcase",
"version": "2.0.1",
"description": "Convert a dash/dot/underscore/space separated string to camelCase: foo-bar → fooBar",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/sindresorhus/camelcase"
},
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "http://sindresorhus.com"
},
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js"
],
"keywords": [
"camelcase",
"camel-case",
"camel",
"case",
"dash",
"hyphen",
"dot",
"underscore",
"separator",
"string",
"text",
"convert"
],
"devDependencies": {
"ava": "*",
"xo": "*"
},
"gitHead": "fb178b39412e3b63ef86bf6933089282d74d85c4",
"bugs": {
"url": "https://github.com/sindresorhus/camelcase/issues"
},
"homepage": "https://github.com/sindresorhus/camelcase",
"_id": "camelcase@2.0.1",
"_shasum": "57568d687b8da56c4c1d17b4c74a3cee26d73aeb",
"_from": "camelcase@^2.0.0",
"_npmVersion": "2.14.7",
"_nodeVersion": "4.2.1",
"_npmUser": {
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
},
"dist": {
"shasum": "57568d687b8da56c4c1d17b4c74a3cee26d73aeb",
"tarball": "http://registry.npmjs.org/camelcase/-/camelcase-2.0.1.tgz"
},
"maintainers": [
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"directories": {},
"_resolved": "https://registry.npmjs.org/camelcase/-/camelcase-2.0.1.tgz",
"readme": "ERROR: No README data found!"
}

View File

@@ -0,0 +1,57 @@
# camelcase [![Build Status](https://travis-ci.org/sindresorhus/camelcase.svg?branch=master)](https://travis-ci.org/sindresorhus/camelcase)
> Convert a dash/dot/underscore/space separated string to camelCase: `foo-bar` → `fooBar`
## Install
```
$ npm install --save camelcase
```
## Usage
```js
const camelCase = require('camelcase');
camelCase('foo-bar');
//=> 'fooBar'
camelCase('foo_bar');
//=> 'fooBar'
camelCase('Foo-Bar');
//=> 'fooBar'
camelCase('--foo.bar');
//=> 'fooBar'
camelCase('__foo__bar__');
//=> 'fooBar'
camelCase('foo bar');
//=> 'fooBar'
console.log(process.argv[3]);
//=> '--foo-bar'
camelCase(process.argv[3]);
//=> 'fooBar'
camelCase('foo', 'bar');
//=> 'fooBar'
camelCase('__foo__', '--bar');
//=> 'fooBar'
```
## Related
- [decamelize](https://github.com/sindresorhus/decamelize) - The inverse of this module
- [uppercamelcase](https://github.com/SamVerschueren/uppercamelcase) - Like this module, but to PascalCase instead of camelCase
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View File

@@ -0,0 +1,13 @@
'use strict';
module.exports = function (obj, cb) {
var ret = {};
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var res = cb(key, obj[key], obj);
ret[res[0]] = res[1];
}
return ret;
};

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,66 @@
{
"name": "map-obj",
"version": "1.0.1",
"description": "Map object keys and values into a new object",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/sindresorhus/map-obj"
},
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "node test.js"
},
"files": [
"index.js"
],
"keywords": [
"map",
"obj",
"object",
"key",
"keys",
"value",
"values",
"val",
"iterate",
"iterator"
],
"devDependencies": {
"ava": "0.0.4"
},
"gitHead": "a4f2d49ae6b5f7c0e55130b49ab0412298b797bc",
"bugs": {
"url": "https://github.com/sindresorhus/map-obj/issues"
},
"homepage": "https://github.com/sindresorhus/map-obj",
"_id": "map-obj@1.0.1",
"_shasum": "d933ceb9205d82bdcf4886f6742bdc2b4dea146d",
"_from": "map-obj@^1.0.0",
"_npmVersion": "2.7.4",
"_nodeVersion": "0.12.2",
"_npmUser": {
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
},
"dist": {
"shasum": "d933ceb9205d82bdcf4886f6742bdc2b4dea146d",
"tarball": "http://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz"
},
"maintainers": [
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"directories": {},
"_resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz",
"readme": "ERROR: No README data found!"
}

View File

@@ -0,0 +1,29 @@
# map-obj [![Build Status](https://travis-ci.org/sindresorhus/map-obj.svg?branch=master)](https://travis-ci.org/sindresorhus/map-obj)
> Map object keys and values into a new object
## Install
```
$ npm install --save map-obj
```
## Usage
```js
var mapObj = require('map-obj');
var newObject = mapObj({foo: 'bar'}, function (key, value, object) {
// first element is the new key and second is the new value
// here we reverse the order
return [value, key];
});
//=> {bar: 'foo'}
```
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View File

@@ -0,0 +1,82 @@
{
"name": "camelcase-keys",
"version": "2.0.0",
"description": "Convert object keys to camelCase",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/sindresorhus/camelcase-keys"
},
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "http://sindresorhus.com"
},
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js"
],
"keywords": [
"map",
"obj",
"object",
"key",
"keys",
"value",
"values",
"val",
"iterate",
"camelcase",
"camel-case",
"camel",
"case",
"dash",
"hyphen",
"dot",
"underscore",
"separator",
"string",
"text",
"convert"
],
"devDependencies": {
"ava": "*",
"xo": "*"
},
"dependencies": {
"camelcase": "^2.0.0",
"map-obj": "^1.0.0"
},
"gitHead": "6d88badb1d6908ef6eedf4140c8dfc5d515b5428",
"bugs": {
"url": "https://github.com/sindresorhus/camelcase-keys/issues"
},
"homepage": "https://github.com/sindresorhus/camelcase-keys",
"_id": "camelcase-keys@2.0.0",
"_shasum": "ab87e740d72a1ffcb12a43cc04c14b39d549eab9",
"_from": "camelcase-keys@^2.0.0",
"_npmVersion": "2.14.7",
"_nodeVersion": "4.2.1",
"_npmUser": {
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
},
"dist": {
"shasum": "ab87e740d72a1ffcb12a43cc04c14b39d549eab9",
"tarball": "http://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.0.0.tgz"
},
"maintainers": [
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"directories": {},
"_resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.0.0.tgz",
"readme": "ERROR: No README data found!"
}

View File

@@ -0,0 +1,32 @@
# camelcase-keys [![Build Status](https://travis-ci.org/sindresorhus/camelcase-keys.svg?branch=master)](https://travis-ci.org/sindresorhus/camelcase-keys)
> Convert object keys to camelCase using [`camelcase`](https://github.com/sindresorhus/camelcase)
## Install
```
$ npm install --save camelcase-keys
```
## Usage
```js
const camelcaseKeys = require('camelcase-keys');
camelcaseKeys({'foo-bar': true});
//=> {fooBar: true}
const argv = require('minimist')(process.argv.slice(2));
//=> {_: [], 'foo-bar': true}
camelcaseKeys(argv);
//=> {_: [], fooBar: true}
```
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View File

@@ -0,0 +1,32 @@
'use strict';
// WARNING: This undocumented API is subject to change.
module.exports = function (process) {
var unhandledRejections = [];
process.on('unhandledRejection', function (reason, p) {
unhandledRejections.push({reason: reason, promise: p});
});
process.on('rejectionHandled', function (p) {
var index = unhandledRejections.reduce(function (result, item, idx) {
return (item.promise === p ? idx : result);
}, -1);
unhandledRejections.splice(index, 1);
});
function currentlyUnhandled() {
return unhandledRejections.map(function (entry) {
return {
reason: entry.reason,
promise: entry.promise
};
});
}
return {
currentlyUnhandled: currentlyUnhandled
};
};

View File

@@ -0,0 +1,37 @@
'use strict';
var onExit = require('signal-exit');
var api = require('./api');
var installed = false;
function outputRejectedMessage(err) {
if (err instanceof Error) {
console.error(err.stack);
} else if (typeof err === 'undefined') {
console.error('Promise rejected no value');
} else {
console.error('Promise rejected with value:', err);
}
}
module.exports = function () {
if (installed) {
console.trace('WARN: loud rejection called more than once');
return;
}
installed = true;
var tracker = api(process);
onExit(function () {
var unhandledRejections = tracker.currentlyUnhandled();
if (unhandledRejections.length > 0) {
unhandledRejections.forEach(function (x) {
outputRejectedMessage(x.reason);
});
process.exitCode = 1;
}
});
};

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,4 @@
node_modules
.DS_Store
nyc_output
coverage

View File

@@ -0,0 +1,7 @@
sudo: false
language: node_js
node_js:
- '0.12'
- '0.10'
- iojs
after_success: npm run coverage

View File

@@ -0,0 +1,14 @@
Copyright (c) 2015, Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice
appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE
LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@@ -0,0 +1,38 @@
# signal-exit
[![Build Status](https://travis-ci.org/bcoe/signal-exit.png)](https://travis-ci.org/bcoe/signal-exit)
[![Coverage Status](https://coveralls.io/repos/bcoe/signal-exit/badge.svg?branch=)](https://coveralls.io/r/bcoe/signal-exit?branch=)
[![NPM version](https://img.shields.io/npm/v/signal-exit.svg)](https://www.npmjs.com/package/signal-exit)
When you want to fire an event no matter how a process exits:
* reaching the end of execution.
* explicitly having `process.exit(code)` called.
* having `process.kill(pid, sig)` called.
* receiving a fatal signal from outside the process
Use `signal-exit`.
```js
var onExit = require('signal-exit')
onExit(function (code, signal) {
console.log('process exited!')
})
```
## API
`var remove = onExit(function (code, signal) {}, options)`
The return value of the function is a function that will remove the
handler.
Note that the function *only* fires for signals if the signal would
cause the proces to exit. That is, there are no other listeners, and
it is a fatal signal.
## Options
* `alwaysLast`: Run this handler after any other signal or exit
handlers. This causes `process.emit` to be monkeypatched.

View File

@@ -0,0 +1,148 @@
// Note: since nyc uses this module to output coverage, any lines
// that are in the direct sync flow of nyc's outputCoverage are
// ignored, since we can never get coverage for them.
var assert = require('assert')
var signals = require('./signals.js')
var EE = require('events')
/* istanbul ignore if */
if (typeof EE !== 'function') {
EE = EE.EventEmitter
}
var emitter
if (process.__signal_exit_emitter__) {
emitter = process.__signal_exit_emitter__
} else {
emitter = process.__signal_exit_emitter__ = new EE()
emitter.count = 0
emitter.emitted = {}
}
module.exports = function (cb, opts) {
assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler')
if (loaded === false) {
load()
}
var ev = 'exit'
if (opts && opts.alwaysLast) {
ev = 'afterexit'
}
var remove = function () {
emitter.removeListener(ev, cb)
if (emitter.listeners('exit').length === 0 &&
emitter.listeners('afterexit').length === 0) {
unload()
}
}
emitter.on(ev, cb)
return remove
}
module.exports.unload = unload
function unload () {
if (!loaded) {
return
}
loaded = false
signals.forEach(function (sig) {
try {
process.removeListener(sig, sigListeners[sig])
} catch (er) {}
})
process.emit = originalProcessEmit
process.reallyExit = originalProcessReallyExit
emitter.count -= 1
}
function emit (event, code, signal) {
if (emitter.emitted[event]) {
return
}
emitter.emitted[event] = true
emitter.emit(event, code, signal)
}
// { <signal>: <listener fn>, ... }
var sigListeners = {}
signals.forEach(function (sig) {
sigListeners[sig] = function listener () {
// If there are no other listeners, an exit is coming!
// Simplest way: remove us and then re-send the signal.
// We know that this will kill the process, so we can
// safely emit now.
var listeners = process.listeners(sig)
if (listeners.length === emitter.count) {
unload()
emit('exit', null, sig)
/* istanbul ignore next */
emit('afterexit', null, sig)
/* istanbul ignore next */
process.kill(process.pid, sig)
}
}
})
module.exports.signals = function () {
return signals
}
module.exports.load = load
var loaded = false
function load () {
if (loaded) {
return
}
loaded = true
// This is the number of onSignalExit's that are in play.
// It's important so that we can count the correct number of
// listeners on signals, and don't wait for the other one to
// handle it instead of us.
emitter.count += 1
signals = signals.filter(function (sig) {
try {
process.on(sig, sigListeners[sig])
return true
} catch (er) {
return false
}
})
process.emit = processEmit
process.reallyExit = processReallyExit
}
var originalProcessReallyExit = process.reallyExit
function processReallyExit (code) {
process.exitCode = code || 0
emit('exit', process.exitCode, null)
/* istanbul ignore next */
emit('afterexit', process.exitCode, null)
/* istanbul ignore next */
originalProcessReallyExit.call(process, process.exitCode)
}
var originalProcessEmit = process.emit
function processEmit (ev, arg) {
if (ev === 'exit') {
if (arg !== undefined) {
process.exitCode = arg
}
var ret = originalProcessEmit.apply(this, arguments)
emit('exit', process.exitCode, null)
/* istanbul ignore next */
emit('afterexit', process.exitCode, null)
return ret
} else {
return originalProcessEmit.apply(this, arguments)
}
}

View File

@@ -0,0 +1,61 @@
{
"name": "signal-exit",
"version": "2.1.2",
"description": "when you want to fire an event no matter how a process exits.",
"main": "index.js",
"scripts": {
"test": "standard && nyc tap --timeout=240 ./test/*.js",
"coverage": "nyc report --reporter=text-lcov | coveralls"
},
"repository": {
"type": "git",
"url": "git+https://github.com/bcoe/signal-exit.git"
},
"keywords": [
"signal",
"exit"
],
"author": {
"name": "Ben Coe",
"email": "ben@npmjs.com"
},
"license": "ISC",
"bugs": {
"url": "https://github.com/bcoe/signal-exit/issues"
},
"homepage": "https://github.com/bcoe/signal-exit",
"devDependencies": {
"chai": "^2.3.0",
"coveralls": "^2.11.2",
"nyc": "^2.1.2",
"standard": "^3.9.0",
"tap": "1.0.4"
},
"gitHead": "8d50231bda6d0d1c4d39de20fc09d11487eb9951",
"_id": "signal-exit@2.1.2",
"_shasum": "375879b1f92ebc3b334480d038dc546a6d558564",
"_from": "signal-exit@^2.1.2",
"_npmVersion": "2.9.0",
"_nodeVersion": "2.0.2",
"_npmUser": {
"name": "bcoe",
"email": "ben@npmjs.com"
},
"dist": {
"shasum": "375879b1f92ebc3b334480d038dc546a6d558564",
"tarball": "http://registry.npmjs.org/signal-exit/-/signal-exit-2.1.2.tgz"
},
"maintainers": [
{
"name": "bcoe",
"email": "ben@npmjs.com"
},
{
"name": "isaacs",
"email": "isaacs@npmjs.com"
}
],
"directories": {},
"_resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-2.1.2.tgz",
"readme": "ERROR: No README data found!"
}

View File

@@ -0,0 +1,47 @@
// This is not the set of all possible signals.
//
// It IS, however, the set of all signals that trigger
// an exit on either Linux or BSD systems. Linux is a
// superset of the signal names supported on BSD, and
// the unknown signals just fail to register, so we can
// catch that easily enough.
//
// Don't bother with SIGKILL. It's uncatchable, which
// means that we can't fire any callbacks anyway.
//
// If a user does happen to register a handler on a non-
// fatal signal like SIGWINCH or something, and then
// exit, it'll end up firing `process.emit('exit')`, so
// the handler will be fired anyway.
module.exports = [
'SIGABRT',
'SIGALRM',
'SIGBUS',
'SIGFPE',
'SIGHUP',
'SIGILL',
'SIGINT',
'SIGIOT',
'SIGPIPE',
'SIGPROF',
'SIGQUIT',
'SIGSEGV',
'SIGSYS',
'SIGTERM',
'SIGTRAP',
'SIGUSR2',
'SIGVTALRM',
'SIGXCPU',
'SIGXFSZ'
]
if (process.platform === 'linux') {
module.exports.push(
'SIGIO',
'SIGPOLL',
'SIGPWR',
'SIGSTKFLT',
'SIGUNUSED'
)
}

View File

@@ -0,0 +1,94 @@
/* global describe, it */
var exec = require('child_process').exec,
assert = require('assert')
require('chai').should()
require('tap').mochaGlobals()
var onSignalExit = require('../')
describe('all-signals-integration-test', function () {
// These are signals that are aliases for other signals, so
// the result will sometimes be one of the others. For these,
// we just verify that we GOT a signal, not what it is.
function weirdSignal (sig) {
return sig === 'SIGIOT' ||
sig === 'SIGIO' ||
sig === 'SIGSYS' ||
sig === 'SIGIOT' ||
sig === 'SIGABRT' ||
sig === 'SIGPOLL' ||
sig === 'SIGUNUSED'
}
// Exhaustively test every signal, and a few numbers.
var signals = onSignalExit.signals()
signals.concat('', 0, 1, 2, 3, 54).forEach(function (sig) {
var node = process.execPath
var js = require.resolve('./fixtures/exiter.js')
it('exits properly: ' + sig, function (done) {
// travis has issues with SIGUSR1 on Node 0.x.10.
if (process.env.TRAVIS && sig === 'SIGUSR1') return done()
exec(node + ' ' + js + ' ' + sig, function (err, stdout, stderr) {
if (sig) {
assert(err)
if (!isNaN(sig)) {
assert.equal(err.code, sig)
} else if (!weirdSignal(sig)) {
if (!process.env.TRAVIS) err.signal.should.equal(sig)
} else if (sig) {
if (!process.env.TRAVIS) assert(err.signal)
}
} else {
assert.ifError(err)
}
try {
var data = JSON.parse(stdout)
} catch (er) {
console.error('invalid json: %j', stdout, stderr)
throw er
}
if (weirdSignal(sig)) {
data.wanted[1] = true
data.found[1] = !!data.found[1]
}
assert.deepEqual(data.found, data.wanted)
done()
})
})
})
signals.forEach(function (sig) {
var node = process.execPath
var js = require.resolve('./fixtures/parent.js')
it('exits properly: (external sig) ' + sig, function (done) {
// travis has issues with SIGUSR1 on Node 0.x.10.
if (process.env.TRAVIS && sig === 'SIGUSR1') return done()
var cmd = node + ' ' + js + ' ' + sig
exec(cmd, function (err, stdout, stderr) {
assert.ifError(err)
try {
var data = JSON.parse(stdout)
} catch (er) {
console.error('invalid json: %j', stdout, stderr)
throw er
}
if (weirdSignal(sig)) {
data.wanted[1] = true
data.found[1] = !!data.found[1]
data.external[1] = !!data.external[1]
}
assert.deepEqual(data.found, data.wanted)
assert.deepEqual(data.external, data.wanted)
done()
})
})
})
})

View File

@@ -0,0 +1,35 @@
var expectSignal = process.argv[2]
if (!expectSignal || !isNaN(expectSignal)) {
throw new Error('signal not provided')
}
var onSignalExit = require('../../')
onSignalExit(function (code, signal) {
// some signals don't always get recognized properly, because
// they have the same numeric code.
if (wanted[1] === true) {
signal = !!signal
}
console.log('%j', {
found: [ code, signal ],
wanted: wanted
})
})
var wanted
switch (expectSignal) {
case 'SIGIOT':
case 'SIGUNUSED':
case 'SIGPOLL':
wanted = [ null, true ]
break
default:
wanted = [ null, expectSignal ]
break
}
console.error('want', wanted)
setTimeout(function () {}, 1000)

View File

@@ -0,0 +1,800 @@
{
"explicit 0 nochange sigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 0,
"actualSignal": null,
"stderr": [
"first code=0",
"second code=0"
]
},
"explicit 0 nochange nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 0,
"actualSignal": null,
"stderr": [
"first code=0",
"second code=0"
]
},
"explicit 0 change sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"explicit 0 change nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"explicit 0 code sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"second code=0"
]
},
"explicit 0 code nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"second code=0"
]
},
"explicit 0 twice sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"explicit 0 twice nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"explicit 0 twicecode sigexit": {
"code": 6,
"signal": null,
"exitCode": 6,
"actualCode": 6,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"set code from 5 to 6"
]
},
"explicit 0 twicecode nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 6,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"set code from 5 to 6"
]
},
"explicit 2 nochange sigexit": {
"code": 2,
"signal": null,
"exitCode": 2,
"actualCode": 2,
"actualSignal": null,
"stderr": [
"first code=2",
"second code=2"
]
},
"explicit 2 nochange nosigexit": {
"code": 2,
"signal": null,
"exitCode": 2,
"actualCode": 2,
"actualSignal": null,
"stderr": [
"first code=2",
"second code=2"
]
},
"explicit 2 change sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=2",
"set code from 2 to 5"
]
},
"explicit 2 change nosigexit": {
"code": 2,
"signal": null,
"exitCode": 2,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=2",
"set code from 2 to 5"
]
},
"explicit 2 code sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=2",
"set code from 2 to 5",
"second code=2"
]
},
"explicit 2 code nosigexit": {
"code": 2,
"signal": null,
"exitCode": 2,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=2",
"set code from 2 to 5",
"second code=2"
]
},
"explicit 2 twice sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=2",
"set code from 2 to 5"
]
},
"explicit 2 twice nosigexit": {
"code": 2,
"signal": null,
"exitCode": 2,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=2",
"set code from 2 to 5"
]
},
"explicit 2 twicecode sigexit": {
"code": 6,
"signal": null,
"exitCode": 6,
"actualCode": 6,
"actualSignal": null,
"stderr": [
"first code=2",
"set code from 2 to 5",
"set code from 5 to 6"
]
},
"explicit 2 twicecode nosigexit": {
"code": 2,
"signal": null,
"exitCode": 2,
"actualCode": 6,
"actualSignal": null,
"stderr": [
"first code=2",
"set code from 2 to 5",
"set code from 5 to 6"
]
},
"explicit null nochange sigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 0,
"actualSignal": null,
"stderr": [
"first code=0",
"second code=0"
]
},
"explicit null nochange nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 0,
"actualSignal": null,
"stderr": [
"first code=0",
"second code=0"
]
},
"explicit null change sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"explicit null change nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"explicit null code sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"second code=0"
]
},
"explicit null code nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"second code=0"
]
},
"explicit null twice sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"explicit null twice nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"explicit null twicecode sigexit": {
"code": 6,
"signal": null,
"exitCode": 6,
"actualCode": 6,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"set code from 5 to 6"
]
},
"explicit null twicecode nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 6,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"set code from 5 to 6"
]
},
"code 0 nochange sigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 0,
"actualSignal": null,
"stderr": [
"first code=0",
"second code=0"
]
},
"code 0 nochange nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 0,
"actualSignal": null,
"stderr": [
"first code=0",
"second code=0"
]
},
"code 0 change sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"code 0 change nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"code 0 code sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"second code=0"
]
},
"code 0 code nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"second code=0"
]
},
"code 0 twice sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"code 0 twice nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"code 0 twicecode sigexit": {
"code": 6,
"signal": null,
"exitCode": 6,
"actualCode": 6,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"set code from 5 to 6"
]
},
"code 0 twicecode nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 6,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"set code from 5 to 6"
]
},
"code 2 nochange sigexit": {
"code": 2,
"signal": null,
"exitCode": 2,
"actualCode": 2,
"actualSignal": null,
"stderr": [
"first code=2",
"second code=2"
]
},
"code 2 nochange nosigexit": {
"code": 2,
"signal": null,
"exitCode": 2,
"actualCode": 2,
"actualSignal": null,
"stderr": [
"first code=2",
"second code=2"
]
},
"code 2 change sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=2",
"set code from 2 to 5"
]
},
"code 2 change nosigexit": {
"code": 2,
"signal": null,
"exitCode": 2,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=2",
"set code from 2 to 5"
]
},
"code 2 code sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=2",
"set code from 2 to 5",
"second code=2"
]
},
"code 2 code nosigexit": {
"code": 2,
"signal": null,
"exitCode": 2,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=2",
"set code from 2 to 5",
"second code=2"
]
},
"code 2 twice sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=2",
"set code from 2 to 5"
]
},
"code 2 twice nosigexit": {
"code": 2,
"signal": null,
"exitCode": 2,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=2",
"set code from 2 to 5"
]
},
"code 2 twicecode sigexit": {
"code": 6,
"signal": null,
"exitCode": 6,
"actualCode": 6,
"actualSignal": null,
"stderr": [
"first code=2",
"set code from 2 to 5",
"set code from 5 to 6"
]
},
"code 2 twicecode nosigexit": {
"code": 2,
"signal": null,
"exitCode": 2,
"actualCode": 6,
"actualSignal": null,
"stderr": [
"first code=2",
"set code from 2 to 5",
"set code from 5 to 6"
]
},
"code null nochange sigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 0,
"actualSignal": null,
"stderr": [
"first code=0",
"second code=0"
]
},
"code null nochange nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 0,
"actualSignal": null,
"stderr": [
"first code=0",
"second code=0"
]
},
"code null change sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"code null change nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"code null code sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"second code=0"
]
},
"code null code nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"second code=0"
]
},
"code null twice sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"code null twice nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"code null twicecode sigexit": {
"code": 6,
"signal": null,
"exitCode": 6,
"actualCode": 6,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"set code from 5 to 6"
]
},
"code null twicecode nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 6,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"set code from 5 to 6"
]
},
"normal 0 nochange sigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 0,
"actualSignal": null,
"stderr": [
"first code=0",
"second code=0"
]
},
"normal 0 nochange nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 0,
"actualSignal": null,
"stderr": [
"first code=0",
"second code=0"
]
},
"normal 0 change sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"normal 0 change nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"normal 0 code sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"second code=0"
]
},
"normal 0 code nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"second code=0"
]
},
"normal 0 twice sigexit": {
"code": 5,
"signal": null,
"exitCode": 5,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"normal 0 twice nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 5,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5"
]
},
"normal 0 twicecode sigexit": {
"code": 6,
"signal": null,
"exitCode": 6,
"actualCode": 6,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"set code from 5 to 6"
]
},
"normal 0 twicecode nosigexit": {
"code": 0,
"signal": null,
"exitCode": 0,
"actualCode": 6,
"actualSignal": null,
"stderr": [
"first code=0",
"set code from 0 to 5",
"set code from 5 to 6"
]
}
}

View File

@@ -0,0 +1,96 @@
if (process.argv.length === 2) {
var types = [ 'explicit', 'code', 'normal' ]
var codes = [ 0, 2, 'null' ]
var changes = [ 'nochange', 'change', 'code', 'twice', 'twicecode']
var handlers = [ 'sigexit', 'nosigexit' ]
var opts = []
types.forEach(function (type) {
var testCodes = type === 'normal' ? [ 0 ] : codes
testCodes.forEach(function (code) {
changes.forEach(function (change) {
handlers.forEach(function (handler) {
opts.push([type, code, change, handler].join(' '))
})
})
})
})
var results = {}
var exec = require('child_process').exec
run(opts.shift())
} else {
var type = process.argv[2]
var code = +process.argv[3]
var change = process.argv[4]
var sigexit = process.argv[5] !== 'nosigexit'
if (sigexit) {
var onSignalExit = require('../../')
onSignalExit(listener)
} else {
process.on('exit', listener)
}
process.on('exit', function (code) {
console.error('first code=%j', code)
})
if (change !== 'nochange') {
process.once('exit', function (code) {
console.error('set code from %j to %j', code, 5)
if (change === 'code' || change === 'twicecode') {
process.exitCode = 5
} else {
process.exit(5)
}
})
if (change === 'twicecode' || change === 'twice') {
process.once('exit', function (code) {
code = process.exitCode || code
console.error('set code from %j to %j', code, code + 1)
process.exit(code + 1)
})
}
}
process.on('exit', function (code) {
console.error('second code=%j', code)
})
if (type === 'explicit') {
if (code || code === 0) {
process.exit(code)
} else {
process.exit()
}
} else if (type === 'code') {
process.exitCode = +code || 0
}
}
function listener (code, signal) {
signal = signal || null
console.log('%j', { code: code, signal: signal, exitCode: process.exitCode || 0 })
}
function run (opt) {
console.error(opt)
exec(process.execPath + ' ' + __filename + ' ' + opt, function (err, stdout, stderr) {
var res = JSON.parse(stdout)
if (err) {
res.actualCode = err.code
res.actualSignal = err.signal
} else {
res.actualCode = 0
res.actualSignal = null
}
res.stderr = stderr.trim().split('\n')
results[opt] = res
if (opts.length) {
run(opts.shift())
} else {
console.log(JSON.stringify(results, null, 2))
}
})
}

View File

@@ -0,0 +1,5 @@
var onSignalExit = require('../../')
onSignalExit(function (code, signal) {
console.log('reached end of execution, ' + code + ', ' + signal)
})

View File

@@ -0,0 +1,14 @@
var onSignalExit = require('../../')
var counter = 0
onSignalExit(function (code, signal) {
counter++
console.log('last counter=%j, code=%j, signal=%j',
counter, code, signal)
}, {alwaysLast: true})
onSignalExit(function (code, signal) {
counter++
console.log('first counter=%j, code=%j, signal=%j',
counter, code, signal)
})

View File

@@ -0,0 +1,7 @@
var onSignalExit = require('../../')
onSignalExit(function (code, signal) {
console.log('exited with process.exit(), ' + code + ', ' + signal)
})
process.exit(32)

View File

@@ -0,0 +1,45 @@
var exit = process.argv[2] || 0
var onSignalExit = require('../../')
onSignalExit(function (code, signal) {
// some signals don't always get recognized properly, because
// they have the same numeric code.
if (wanted[1] === true) {
signal = !!signal
}
console.log('%j', {
found: [ code, signal ],
wanted: wanted
})
})
var wanted
if (isNaN(exit)) {
switch (exit) {
case 'SIGIOT':
case 'SIGUNUSED':
case 'SIGPOLL':
wanted = [ null, true ]
break
default:
wanted = [ null, exit ]
break
}
try {
process.kill(process.pid, exit)
setTimeout(function () {}, 1000)
} catch (er) {
wanted = [ 0, null ]
}
} else {
exit = +exit
wanted = [ exit, null ]
// If it's explicitly requested 0, then explicitly call it.
// "no arg" = "exit naturally"
if (exit || process.argv[2]) {
process.exit(exit)
}
}

View File

@@ -0,0 +1,7 @@
// just be silly with calling these functions a bunch
// mostly just to get coverage of the guard branches
var onSignalExit = require('../../')
onSignalExit.load()
onSignalExit.load()
onSignalExit.unload()
onSignalExit.unload()

View File

@@ -0,0 +1,52 @@
// simulate cases where the module could be loaded from multiple places
var onSignalExit = require('../../')
var counter = 0
onSignalExit(function (code, signal) {
counter++
console.log('last counter=%j, code=%j, signal=%j',
counter, code, signal)
}, {alwaysLast: true})
onSignalExit(function (code, signal) {
counter++
console.log('first counter=%j, code=%j, signal=%j',
counter, code, signal)
})
delete require('module')._cache[require.resolve('../../')]
var onSignalExit = require('../../')
onSignalExit(function (code, signal) {
counter++
console.log('last counter=%j, code=%j, signal=%j',
counter, code, signal)
}, {alwaysLast: true})
onSignalExit(function (code, signal) {
counter++
console.log('first counter=%j, code=%j, signal=%j',
counter, code, signal)
})
// Lastly, some that should NOT be shown
delete require('module')._cache[require.resolve('../../')]
var onSignalExit = require('../../')
var unwrap = onSignalExit(function (code, signal) {
counter++
console.log('last counter=%j, code=%j, signal=%j',
counter, code, signal)
}, {alwaysLast: true})
unwrap()
unwrap = onSignalExit(function (code, signal) {
counter++
console.log('first counter=%j, code=%j, signal=%j',
counter, code, signal)
})
unwrap()
process.kill(process.pid, 'SIGHUP')
setTimeout(function () {}, 1000)

View File

@@ -0,0 +1,51 @@
var signal = process.argv[2]
var gens = +process.argv[3] || 0
if (!signal || !isNaN(signal)) {
throw new Error('signal not provided')
}
var spawn = require('child_process').spawn
var file = require.resolve('./awaiter.js')
console.error(process.pid, signal, gens)
if (gens > 0) {
file = __filename
}
var child = spawn(process.execPath, [file, signal, gens - 1], {
stdio: [ 0, 'pipe', 'pipe' ]
})
if (!gens) {
child.stderr.on('data', function () {
child.kill(signal)
})
}
var result = ''
child.stdout.on('data', function (c) {
result += c
})
child.on('close', function (code, sig) {
try {
result = JSON.parse(result)
} catch (er) {
console.log('%j', {
error: 'failed to parse json\n' + er.message,
result: result,
pid: process.pid,
child: child.pid,
gens: gens,
expect: [ null, signal ],
actual: [ code, sig ]
})
return
}
if (result.wanted[1] === true) {
sig = !!sig
}
result.external = result.external || [ code, sig ]
console.log('%j', result)
})

View File

@@ -0,0 +1,11 @@
var onSignalExit = require('../../')
onSignalExit(function (code, signal) {
console.log('exited with sigint, ' + code + ', ' + signal)
})
// For some reason, signals appear to not always be fast enough
// to come in before the process exits. Just a few ticks needed.
setTimeout(function () {}, 1000)
process.kill(process.pid, 'SIGINT')

View File

@@ -0,0 +1,19 @@
// SIGKILL can't be caught, and in fact, even trying to add the
// listener will throw an error.
// We handle that nicely.
//
// This is just here to get another few more lines of test
// coverage. That's also why it lies about being on a linux
// platform so that we pull in those other event types.
Object.defineProperty(process, 'platform', {
value: 'linux',
writable: false,
enumerable: true,
configurable: true
})
var signals = require('../../signals.js')
signals.push('SIGKILL')
var onSignalExit = require('../../')
onSignalExit.load()

View File

@@ -0,0 +1,99 @@
// This fixture is not used in any tests. It is here merely as a way to
// do research into the various signal behaviors on Linux and Darwin.
// Run with no args to cycle through every signal type. Run with a signal
// arg to learn about how that signal behaves.
if (process.argv[2]) {
child(process.argv[2])
} else {
var signals = [
'SIGABRT',
'SIGALRM',
'SIGBUS',
'SIGCHLD',
'SIGCLD',
'SIGCONT',
'SIGEMT',
'SIGFPE',
'SIGHUP',
'SIGILL',
'SIGINFO',
'SIGINT',
'SIGIO',
'SIGIOT',
'SIGKILL',
'SIGLOST',
'SIGPIPE',
'SIGPOLL',
'SIGPROF',
'SIGPWR',
'SIGQUIT',
'SIGSEGV',
'SIGSTKFLT',
'SIGSTOP',
'SIGSYS',
'SIGTERM',
'SIGTRAP',
'SIGTSTP',
'SIGTTIN',
'SIGTTOU',
'SIGUNUSED',
'SIGURG',
'SIGUSR1',
'SIGUSR2',
'SIGVTALRM',
'SIGWINCH',
'SIGXCPU',
'SIGXFSZ'
]
var spawn = require('child_process').spawn
;(function test (signal) {
if (!signal) {
return
}
var child = spawn(process.execPath, [__filename, signal], { stdio: 'inherit' })
var timer = setTimeout(function () {
console.log('requires SIGCONT')
process.kill(child.pid, 'SIGCONT')
}, 750)
child.on('close', function (code, signal) {
console.log('code=%j signal=%j\n', code, signal)
clearTimeout(timer)
test(signals.pop())
})
})(signals.pop())
}
function child (signal) {
console.log('signal=%s', signal)
// set a timeout so we know whether or not the process terminated.
setTimeout(function () {
console.log('not terminated')
}, 200)
process.on('exit', function (code) {
console.log('emit exit code=%j', code)
})
try {
process.on(signal, function fn () {
console.log('signal is catchable', signal)
process.removeListener(signal, fn)
setTimeout(function () {
console.error('signal again')
process.kill(process.pid, signal)
})
})
} catch (er) {
console.log('not listenable')
}
try {
process.kill(process.pid, signal)
} catch (er) {
console.log('not issuable')
}
}

View File

@@ -0,0 +1,17 @@
var onSignalExit = require('../../')
var counter = 0
onSignalExit(function (code, signal) {
counter++
console.log('last counter=%j, code=%j, signal=%j',
counter, code, signal)
}, {alwaysLast: true})
onSignalExit(function (code, signal) {
counter++
console.log('first counter=%j, code=%j, signal=%j',
counter, code, signal)
})
process.kill(process.pid, 'SIGHUP')
setTimeout(function () {}, 1000)

View File

@@ -0,0 +1,23 @@
var onSignalExit = require('../../')
setTimeout(function () {})
var calledListener = 0
onSignalExit(function (code, signal) {
console.log('exited calledListener=%j, code=%j, signal=%j',
calledListener, code, signal)
})
process.on('SIGHUP', listener)
process.kill(process.pid, 'SIGHUP')
function listener () {
calledListener++
if (calledListener > 3) {
process.removeListener('SIGHUP', listener)
}
setTimeout(function () {
process.kill(process.pid, 'SIGHUP')
})
}

View File

@@ -0,0 +1,8 @@
var onSignalExit = require('../..')
onSignalExit(function (code, signal) {
console.error('onSignalExit(%j,%j)', code, signal)
})
setTimeout(function () {
console.log('hello')
})
process.kill(process.pid, 'SIGPIPE')

View File

@@ -0,0 +1,9 @@
var onSignalExit = require('../../')
onSignalExit(function (code, signal) {
console.log('exited with sigterm, ' + code + ', ' + signal)
})
setTimeout(function () {}, 1000)
process.kill(process.pid, 'SIGTERM')

View File

@@ -0,0 +1,37 @@
// simulate cases where the module could be loaded from multiple places
// Need to lie about this a little bit, since nyc uses this module
// for its coverage wrap-up handling
if (process.env.NYC_CWD) {
var emitter = process.__signal_exit_emitter__
var listeners = emitter.listeners('afterexit')
process.removeAllListeners('SIGHUP')
delete process.__signal_exit_emitter__
delete require('module')._cache[require.resolve('../../')]
}
var onSignalExit = require('../../')
var counter = 0
var unwrap = onSignalExit(function (code, signal) {
counter++
console.log('last counter=%j, code=%j, signal=%j',
counter, code, signal)
}, {alwaysLast: true})
unwrap()
unwrap = onSignalExit(function (code, signal) {
counter++
console.log('first counter=%j, code=%j, signal=%j',
counter, code, signal)
})
unwrap()
if (global.__coverage__ && listeners && listeners.length) {
listeners.forEach(function (fn) {
onSignalExit(fn, { alwaysLast: true })
})
}
process.kill(process.pid, 'SIGHUP')
setTimeout(function () {}, 1000)

View File

@@ -0,0 +1,58 @@
var exec = require('child_process').exec,
t = require('tap')
var fixture = require.resolve('./fixtures/change-code.js')
var expect = require('./fixtures/change-code-expect.json')
// process.exitCode has problems prior to:
// https://github.com/joyent/node/commit/c0d81f90996667a658aa4403123e02161262506a
function isZero10 () {
return /^v0\.10\..+$/.test(process.version)
}
// process.exit(code), process.exitCode = code, normal exit
var types = [ 'explicit', 'normal' ]
if (!isZero10()) types.push('code')
// initial code that is set. Note, for 'normal' exit, there's no
// point doing these, because we just exit without modifying code
var codes = [ 0, 2, 'null' ]
// do not change, change to 5 with exit(), change to 5 with exitCode,
// change to 5 and then to 2 with exit(), change twice with exitcode
var changes = [ 'nochange', 'change', 'twice']
if (!isZero10()) changes.push('code', 'twicecode')
// use signal-exit, use process.on('exit')
var handlers = [ 'sigexit', 'nosigexit' ]
var opts = []
types.forEach(function (type) {
var testCodes = type === 'normal' ? [0] : codes
testCodes.forEach(function (code) {
changes.forEach(function (change) {
handlers.forEach(function (handler) {
opts.push([type, code, change, handler].join(' '))
})
})
})
})
opts.forEach(function (opt) {
t.test(opt, function (t) {
var cmd = process.execPath + ' ' + fixture + ' ' + opt
exec(cmd, function (err, stdout, stderr) {
var res = JSON.parse(stdout)
if (err) {
res.actualCode = err.code
res.actualSignal = err.signal
} else {
res.actualCode = 0
res.actualSignal = null
}
res.stderr = stderr.trim().split('\n')
t.same(res, expect[opt])
t.end()
})
})
})

View File

@@ -0,0 +1,108 @@
/* global describe, it */
var exec = require('child_process').exec,
expect = require('chai').expect,
assert = require('assert')
require('chai').should()
require('tap').mochaGlobals()
describe('signal-exit', function () {
it('receives an exit event when a process exits normally', function (done) {
exec(process.execPath + ' ./test/fixtures/end-of-execution.js', function (err, stdout, stderr) {
expect(err).to.equal(null)
stdout.should.match(/reached end of execution, 0, null/)
done()
})
})
it('receives an exit event when a process is terminated with sigint', function (done) {
exec(process.execPath + ' ./test/fixtures/sigint.js', function (err, stdout, stderr) {
assert(err)
stdout.should.match(/exited with sigint, null, SIGINT/)
done()
})
})
it('receives an exit event when a process is terminated with sigterm', function (done) {
exec(process.execPath + ' ./test/fixtures/sigterm.js', function (err, stdout, stderr) {
assert(err)
stdout.should.match(/exited with sigterm, null, SIGTERM/)
done()
})
})
it('receives an exit event when process.exit() is called', function (done) {
exec(process.execPath + ' ./test/fixtures/exit.js', function (err, stdout, stderr) {
err.code.should.equal(32)
stdout.should.match(/exited with process\.exit\(\), 32, null/)
done()
})
})
it('does not exit if user handles signal', function (done) {
exec(process.execPath + ' ./test/fixtures/signal-listener.js', function (err, stdout, stderr) {
assert(err)
assert.equal(stdout, 'exited calledListener=4, code=null, signal="SIGHUP"\n')
done()
})
})
it('ensures that if alwaysLast=true, the handler is run last (signal)', function (done) {
exec(process.execPath + ' ./test/fixtures/signal-last.js', function (err, stdout, stderr) {
assert(err)
stdout.should.match(/first counter=1/)
stdout.should.match(/last counter=2/)
done()
})
})
it('ensures that if alwaysLast=true, the handler is run last (normal exit)', function (done) {
exec(process.execPath + ' ./test/fixtures/exit-last.js', function (err, stdout, stderr) {
assert.ifError(err)
stdout.should.match(/first counter=1/)
stdout.should.match(/last counter=2/)
done()
})
})
it('works when loaded multiple times', function (done) {
exec(process.execPath + ' ./test/fixtures/multiple-load.js', function (err, stdout, stderr) {
assert(err)
stdout.should.match(/first counter=1, code=null, signal="SIGHUP"/)
stdout.should.match(/first counter=2, code=null, signal="SIGHUP"/)
stdout.should.match(/last counter=3, code=null, signal="SIGHUP"/)
stdout.should.match(/last counter=4, code=null, signal="SIGHUP"/)
done()
})
})
// TODO: test on a few non-OSX machines.
it('removes handlers when fully unwrapped', function (done) {
exec(process.execPath + ' ./test/fixtures/unwrap.js', function (err, stdout, stderr) {
// on Travis CI no err.signal is populated but
// err.code is 129 (which I think tends to be SIGHUP).
var expectedCode = process.env.TRAVIS ? 129 : null
assert(err)
if (!process.env.TRAVIS) err.signal.should.equal('SIGHUP')
expect(err.code).to.equal(expectedCode)
done()
})
})
it('does not load() or unload() more than once', function (done) {
exec(process.execPath + ' ./test/fixtures/load-unload.js', function (err, stdout, stderr) {
assert.ifError(err)
done()
})
})
it('handles uncatchable signals with grace and poise', function (done) {
exec(process.execPath + ' ./test/fixtures/sigkill.js', function (err, stdout, stderr) {
assert.ifError(err)
done()
})
})
})

View File

@@ -0,0 +1,96 @@
{
"name": "loud-rejection",
"version": "1.2.0",
"description": "Make unhandled promise rejections fail loudly instead of the default silent fail",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/sindresorhus/loud-rejection"
},
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "xo && nyc ava",
"coveralls": "nyc report --reporter=text-lcov | coveralls"
},
"files": [
"index.js",
"register.js",
"api.js"
],
"keywords": [
"promise",
"promises",
"unhandled",
"uncaught",
"rejection",
"loud",
"fail",
"catch",
"throw",
"handler",
"exit",
"debug",
"debugging",
"verbose"
],
"dependencies": {
"signal-exit": "^2.1.2"
},
"devDependencies": {
"ava": "*",
"bluebird": "^3.0.5",
"coveralls": "^2.11.4",
"delay": "^1.0.0",
"get-stream": "^1.0.0",
"nyc": "^3.2.2",
"xo": "*"
},
"xo": {
"ignores": [
"test.js"
]
},
"config": {
"nyc": {
"exclude": [
"node_modules",
"test.js",
"fixture.js"
]
}
},
"gitHead": "5ed228786d1ae9a603deafb4c751410ece432802",
"bugs": {
"url": "https://github.com/sindresorhus/loud-rejection/issues"
},
"homepage": "https://github.com/sindresorhus/loud-rejection",
"_id": "loud-rejection@1.2.0",
"_shasum": "f4f87db6abec3b7fe47834531ecf6a011143e58d",
"_from": "loud-rejection@^1.0.0",
"_npmVersion": "2.14.7",
"_nodeVersion": "4.2.1",
"_npmUser": {
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
},
"dist": {
"shasum": "f4f87db6abec3b7fe47834531ecf6a011143e58d",
"tarball": "http://registry.npmjs.org/loud-rejection/-/loud-rejection-1.2.0.tgz"
},
"maintainers": [
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"directories": {},
"_resolved": "https://registry.npmjs.org/loud-rejection/-/loud-rejection-1.2.0.tgz",
"readme": "ERROR: No README data found!"
}

View File

@@ -0,0 +1,55 @@
# loud-rejection [![Build Status](https://travis-ci.org/sindresorhus/loud-rejection.svg?branch=master)](https://travis-ci.org/sindresorhus/loud-rejection) [![Coverage Status](https://coveralls.io/repos/sindresorhus/loud-rejection/badge.svg?branch=master&service=github)](https://coveralls.io/github/sindresorhus/loud-rejection?branch=master)
> Make unhandled promise rejections fail loudly instead of the default [silent fail](https://gist.github.com/benjamingr/0237932cee84712951a2)
By default, promises fail silently if you don't attach a `.catch()` handler to them.
Use it in top-level things like tests, CLI tools, apps, etc, **but not in reusable modules.**
## Install
```
$ npm install --save loud-rejection
```
## Usage
```js
const loudRejection = require('loud-rejection');
const promiseFn = require('promise-fn');
// Install the unhandledRejection listeners
loudRejection();
promiseFn();
```
Without this module it's more verbose and you might even miss some that will fail silently:
```js
const promiseFn = require('promise-fn');
function error(err) {
console.error(err.stack);
process.exit(1);
}
promiseFn().catch(error);
```
### Register script
Alternatively to the above, you may simply require `loud-rejection/register` and the unhandledRejection listener will be automagically installed for you.
This is handy for ES2015 imports:
```js
import 'loud-rejection/register';
```
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View File

@@ -0,0 +1,3 @@
'use strict';
require('./')();

View File

@@ -0,0 +1,3 @@
language: node_js
node_js:
- "0.10"

View File

@@ -0,0 +1,4 @@
# Names sorted by how much code was originally theirs.
Isaac Z. Schlueter <i@izs.me>
Meryn Stol <merynstol@gmail.com>
Robert Kowalski <rok@kowalski.gd>

View File

@@ -0,0 +1,30 @@
This package contains code originally written by Isaac Z. Schlueter.
Used with permission.
Copyright (c) Meryn Stol ("Author")
All rights reserved.
The BSD License
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,107 @@
# normalize-package-data [![Build Status](https://travis-ci.org/npm/normalize-package-data.png?branch=master)](https://travis-ci.org/npm/normalize-package-data)
normalize-package data exports a function that normalizes package metadata. This data is typically found in a package.json file, but in principle could come from any source - for example the npm registry.
normalize-package-data is used by [read-package-json](https://npmjs.org/package/read-package-json) to normalize the data it reads from a package.json file. In turn, read-package-json is used by [npm](https://npmjs.org/package/npm) and various npm-related tools.
## Installation
```
npm install normalize-package-data
```
## Usage
Basic usage is really simple. You call the function that normalize-package-data exports. Let's call it `normalizeData`.
```javascript
normalizeData = require('normalize-package-data')
packageData = fs.readFileSync("package.json")
normalizeData(packageData)
// packageData is now normalized
```
#### Strict mode
You may activate strict validation by passing true as the second argument.
```javascript
normalizeData = require('normalize-package-data')
packageData = fs.readFileSync("package.json")
warnFn = function(msg) { console.error(msg) }
normalizeData(packageData, true)
// packageData is now normalized
```
If strict mode is activated, only Semver 2.0 version strings are accepted. Otherwise, Semver 1.0 strings are accepted as well. Packages must have a name, and the name field must not have contain leading or trailing whitespace.
#### Warnings
Optionally, you may pass a "warning" function. It gets called whenever the `normalizeData` function encounters something that doesn't look right. It indicates less than perfect input data.
```javascript
normalizeData = require('normalize-package-data')
packageData = fs.readFileSync("package.json")
warnFn = function(msg) { console.error(msg) }
normalizeData(packageData, warnFn)
// packageData is now normalized. Any number of warnings may have been logged.
```
You may combine strict validation with warnings by passing `true` as the second argument, and `warnFn` as third.
When `private` field is set to `true`, warnings will be suppressed.
### Potential exceptions
If the supplied data has an invalid name or version vield, `normalizeData` will throw an error. Depending on where you call `normalizeData`, you may want to catch these errors so can pass them to a callback.
## What normalization (currently) entails
* The value of `name` field gets trimmed (unless in strict mode).
* The value of the `version` field gets cleaned by `semver.clean`. See [documentation for the semver module](https://github.com/isaacs/node-semver).
* If `name` and/or `version` fields are missing, they are set to empty strings.
* If `files` field is not an array, it will be removed.
* If `bin` field is a string, then `bin` field will become an object with `name` set to the value of the `name` field, and `bin` set to the original string value.
* If `man` field is a string, it will become an array with the original string as its sole member.
* If `keywords` field is string, it is considered to be a list of keywords separated by one or more white-space characters. It gets converted to an array by splitting on `\s+`.
* All people fields (`author`, `maintainers`, `contributors`) get converted into objects with name, email and url properties.
* If `bundledDependencies` field (a typo) exists and `bundleDependencies` field does not, `bundledDependencies` will get renamed to `bundleDependencies`.
* If the value of any of the dependencies fields (`dependencies`, `devDependencies`, `optionalDependencies`) is a string, it gets converted into an object with familiar `name=>value` pairs.
* The values in `optionalDependencies` get added to `dependencies`. The `optionalDependencies` array is left untouched.
* As of v2: Dependencies that point at known hosted git providers (currently: github, bitbucket, gitlab) will have their URLs canonicalized, but protocols will be preserved.
* As of v2: Dependencies that use shortcuts for hosted git providers (`org/proj`, `github:org/proj`, `bitbucket:org/proj`, `gitlab:org/proj`, `gist:docid`) will have the shortcut left in place. (In the case of github, the `org/proj` form will be expanded to `github:org/proj`.) THIS MARKS A BREAKING CHANGE FROM V1, where the shorcut was previously expanded to a URL.
* If `description` field does not exist, but `readme` field does, then (more or less) the first paragraph of text that's found in the readme is taken as value for `description`.
* If `repository` field is a string, it will become an object with `url` set to the original string value, and `type` set to `"git"`.
* If `repository.url` is not a valid url, but in the style of "[owner-name]/[repo-name]", `repository.url` will be set to git+https://github.com/[owner-name]/[repo-name].git
* If `bugs` field is a string, the value of `bugs` field is changed into an object with `url` set to the original string value.
* If `bugs` field does not exist, but `repository` field points to a repository hosted on GitHub, the value of the `bugs` field gets set to an url in the form of https://github.com/[owner-name]/[repo-name]/issues . If the repository field points to a GitHub Gist repo url, the associated http url is chosen.
* If `bugs` field is an object, the resulting value only has email and url properties. If email and url properties are not strings, they are ignored. If no valid values for either email or url is found, bugs field will be removed.
* If `homepage` field is not a string, it will be removed.
* If the url in the `homepage` field does not specify a protocol, then http is assumed. For example, `myproject.org` will be changed to `http://myproject.org`.
* If `homepage` field does not exist, but `repository` field points to a repository hosted on GitHub, the value of the `homepage` field gets set to an url in the form of https://github.com/[owner-name]/[repo-name]/ . If the repository field points to a GitHub Gist repo url, the associated http url is chosen.
### Rules for name field
If `name` field is given, the value of the name field must be a string. The string may not:
* start with a period.
* contain the following characters: `/@\s+%`
* contain and characters that would need to be encoded for use in urls.
* resemble the word `node_modules` or `favicon.ico` (case doesn't matter).
### Rules for version field
If `version` field is given, the value of the version field must be a valid *semver* string, as determined by the `semver.valid` method. See [documentation for the semver module](https://github.com/isaacs/node-semver).
### Rules for license field
The `license` field should be a valid *SPDX license expression* or one of the special values allowed by [validate-npm-package-license](https://npmjs.com/packages/validate-npm-package-license). See [documentation for the license field in package.json](https://docs.npmjs.com/files/package.json#license).
## Credits
This package contains code based on read-package-json written by Isaac Z. Schlueter. Used with permisson.
## License
normalize-package-data is released under the [BSD 2-Clause License](http://opensource.org/licenses/MIT).
Copyright (c) 2013 Meryn Stol

View File

@@ -0,0 +1,14 @@
module.exports = extractDescription
// Extracts description from contents of a readme file in markdown format
function extractDescription (d) {
if (!d) return;
if (d === "ERROR: No README data found!") return;
// the first block of text before the first heading
// that isn't the first line heading
d = d.trim().split('\n')
for (var s = 0; d[s] && d[s].trim().match(/^(#|$)/); s ++);
var l = d.length
for (var e = s + 1; e < l && d[e].trim(); e ++);
return d.slice(s, e).join(' ').trim()
}

View File

@@ -0,0 +1,418 @@
var semver = require("semver")
var validateLicense = require('validate-npm-package-license');
var hostedGitInfo = require("hosted-git-info")
var isBuiltinModule = require("is-builtin-module")
var depTypes = ["dependencies","devDependencies","optionalDependencies"]
var extractDescription = require("./extract_description")
var url = require("url")
var typos = require("./typos")
var fixer = module.exports = {
// default warning function
warn: function() {},
fixRepositoryField: function(data) {
if (data.repositories) {
this.warn("repositories");
data.repository = data.repositories[0]
}
if (!data.repository) return this.warn("missingRepository")
if (typeof data.repository === "string") {
data.repository = {
type: "git",
url: data.repository
}
}
var r = data.repository.url || ""
if (r) {
var hosted = hostedGitInfo.fromUrl(r)
if (hosted) {
r = data.repository.url
= hosted.getDefaultRepresentation() == "shortcut" ? hosted.https() : hosted.toString()
}
}
if (r.match(/github.com\/[^\/]+\/[^\/]+\.git\.git$/)) {
this.warn("brokenGitUrl", r)
}
}
, fixTypos: function(data) {
Object.keys(typos.topLevel).forEach(function (d) {
if (data.hasOwnProperty(d)) {
this.warn("typo", d, typos.topLevel[d])
}
}, this)
}
, fixScriptsField: function(data) {
if (!data.scripts) return
if (typeof data.scripts !== "object") {
this.warn("nonObjectScripts")
delete data.scripts
return
}
Object.keys(data.scripts).forEach(function (k) {
if (typeof data.scripts[k] !== "string") {
this.warn("nonStringScript")
delete data.scripts[k]
} else if (typos.script[k] && !data.scripts[typos.script[k]]) {
this.warn("typo", k, typos.script[k], "scripts")
}
}, this)
}
, fixFilesField: function(data) {
var files = data.files
if (files && !Array.isArray(files)) {
this.warn("nonArrayFiles")
delete data.files
} else if (data.files) {
data.files = data.files.filter(function(file) {
if (!file || typeof file !== "string") {
this.warn("invalidFilename", file)
return false
} else {
return true
}
}, this)
}
}
, fixBinField: function(data) {
if (!data.bin) return;
if (typeof data.bin === "string") {
var b = {}
var match
if (match = data.name.match(/^@[^/]+[/](.*)$/)) {
b[match[1]] = data.bin
} else {
b[data.name] = data.bin
}
data.bin = b
}
}
, fixManField: function(data) {
if (!data.man) return;
if (typeof data.man === "string") {
data.man = [ data.man ]
}
}
, fixBundleDependenciesField: function(data) {
var bdd = "bundledDependencies"
var bd = "bundleDependencies"
if (data[bdd] && !data[bd]) {
data[bd] = data[bdd]
delete data[bdd]
}
if (data[bd] && !Array.isArray(data[bd])) {
this.warn("nonArrayBundleDependencies")
delete data[bd]
} else if (data[bd]) {
data[bd] = data[bd].filter(function(bd) {
if (!bd || typeof bd !== 'string') {
this.warn("nonStringBundleDependency", bd)
return false
} else {
if (!data.dependencies) {
data.dependencies = {}
}
if (!data.dependencies.hasOwnProperty(bd)) {
this.warn("nonDependencyBundleDependency", bd)
data.dependencies[bd] = "*"
}
return true
}
}, this)
}
}
, fixDependencies: function(data, strict) {
var loose = !strict
objectifyDeps(data, this.warn)
addOptionalDepsToDeps(data, this.warn)
this.fixBundleDependenciesField(data)
;['dependencies','devDependencies'].forEach(function(deps) {
if (!(deps in data)) return
if (!data[deps] || typeof data[deps] !== "object") {
this.warn("nonObjectDependencies", deps)
delete data[deps]
return
}
Object.keys(data[deps]).forEach(function (d) {
var r = data[deps][d]
if (typeof r !== 'string') {
this.warn("nonStringDependency", d, JSON.stringify(r))
delete data[deps][d]
}
var hosted = hostedGitInfo.fromUrl(data[deps][d])
if (hosted) data[deps][d] = hosted.toString()
}, this)
}, this)
}
, fixModulesField: function (data) {
if (data.modules) {
this.warn("deprecatedModules")
delete data.modules
}
}
, fixKeywordsField: function (data) {
if (typeof data.keywords === "string") {
data.keywords = data.keywords.split(/,\s+/)
}
if (data.keywords && !Array.isArray(data.keywords)) {
delete data.keywords
this.warn("nonArrayKeywords")
} else if (data.keywords) {
data.keywords = data.keywords.filter(function(kw) {
if (typeof kw !== "string" || !kw) {
this.warn("nonStringKeyword");
return false
} else {
return true
}
}, this)
}
}
, fixVersionField: function(data, strict) {
// allow "loose" semver 1.0 versions in non-strict mode
// enforce strict semver 2.0 compliance in strict mode
var loose = !strict
if (!data.version) {
data.version = ""
return true
}
if (!semver.valid(data.version, loose)) {
throw new Error('Invalid version: "'+ data.version + '"')
}
data.version = semver.clean(data.version, loose)
return true
}
, fixPeople: function(data) {
modifyPeople(data, unParsePerson)
modifyPeople(data, parsePerson)
}
, fixNameField: function(data, options) {
if (typeof options === "boolean") options = {strict: options}
else if (typeof options === "undefined") options = {}
var strict = options.strict
if (!data.name && !strict) {
data.name = ""
return
}
if (typeof data.name !== "string") {
throw new Error("name field must be a string.")
}
if (!strict)
data.name = data.name.trim()
ensureValidName(data.name, strict, options.allowLegacyCase)
if (isBuiltinModule(data.name))
this.warn("conflictingName", data.name)
}
, fixDescriptionField: function (data) {
if (data.description && typeof data.description !== 'string') {
this.warn("nonStringDescription")
delete data.description
}
if (data.readme && !data.description)
data.description = extractDescription(data.readme)
if(data.description === undefined) delete data.description;
if (!data.description) this.warn("missingDescription")
}
, fixReadmeField: function (data) {
if (!data.readme) {
this.warn("missingReadme")
data.readme = "ERROR: No README data found!"
}
}
, fixBugsField: function(data) {
if (!data.bugs && data.repository && data.repository.url) {
var hosted = hostedGitInfo.fromUrl(data.repository.url)
if(hosted && hosted.bugs()) {
data.bugs = {url: hosted.bugs()}
}
}
else if(data.bugs) {
var emailRe = /^.+@.*\..+$/
if(typeof data.bugs == "string") {
if(emailRe.test(data.bugs))
data.bugs = {email:data.bugs}
else if(url.parse(data.bugs).protocol)
data.bugs = {url: data.bugs}
else
this.warn("nonEmailUrlBugsString")
}
else {
bugsTypos(data.bugs, this.warn)
var oldBugs = data.bugs
data.bugs = {}
if(oldBugs.url) {
if(typeof(oldBugs.url) == "string" && url.parse(oldBugs.url).protocol)
data.bugs.url = oldBugs.url
else
this.warn("nonUrlBugsUrlField")
}
if(oldBugs.email) {
if(typeof(oldBugs.email) == "string" && emailRe.test(oldBugs.email))
data.bugs.email = oldBugs.email
else
this.warn("nonEmailBugsEmailField")
}
}
if(!data.bugs.email && !data.bugs.url) {
delete data.bugs
this.warn("emptyNormalizedBugs")
}
}
}
, fixHomepageField: function(data) {
if (!data.homepage && data.repository && data.repository.url) {
var hosted = hostedGitInfo.fromUrl(data.repository.url)
if (hosted && hosted.docs()) data.homepage = hosted.docs()
}
if (!data.homepage) return
if(typeof data.homepage !== "string") {
this.warn("nonUrlHomepage")
return delete data.homepage
}
if(!url.parse(data.homepage).protocol) {
this.warn("missingProtocolHomepage")
data.homepage = "http://" + data.homepage
}
}
, fixLicenseField: function(data) {
if (!data.license) {
return this.warn("missingLicense")
} else{
if (
typeof(data.license) !== 'string' ||
data.license.length < 1
) {
this.warn("invalidLicense")
} else {
if (!validateLicense(data.license).validForNewPackages)
this.warn("invalidLicense")
}
}
}
}
function isValidScopedPackageName(spec) {
if (spec.charAt(0) !== '@') return false
var rest = spec.slice(1).split('/')
if (rest.length !== 2) return false
return rest[0] && rest[1] &&
rest[0] === encodeURIComponent(rest[0]) &&
rest[1] === encodeURIComponent(rest[1])
}
function isCorrectlyEncodedName(spec) {
return !spec.match(/[\/@\s\+%:]/) &&
spec === encodeURIComponent(spec)
}
function ensureValidName (name, strict, allowLegacyCase) {
if (name.charAt(0) === "." ||
!(isValidScopedPackageName(name) || isCorrectlyEncodedName(name)) ||
(strict && (!allowLegacyCase) && name !== name.toLowerCase()) ||
name.toLowerCase() === "node_modules" ||
name.toLowerCase() === "favicon.ico") {
throw new Error("Invalid name: " + JSON.stringify(name))
}
}
function modifyPeople (data, fn) {
if (data.author) data.author = fn(data.author)
;["maintainers", "contributors"].forEach(function (set) {
if (!Array.isArray(data[set])) return;
data[set] = data[set].map(fn)
})
return data
}
function unParsePerson (person) {
if (typeof person === "string") return person
var name = person.name || ""
var u = person.url || person.web
var url = u ? (" ("+u+")") : ""
var e = person.email || person.mail
var email = e ? (" <"+e+">") : ""
return name+email+url
}
function parsePerson (person) {
if (typeof person !== "string") return person
var name = person.match(/^([^\(<]+)/)
var url = person.match(/\(([^\)]+)\)/)
var email = person.match(/<([^>]+)>/)
var obj = {}
if (name && name[0].trim()) obj.name = name[0].trim()
if (email) obj.email = email[1];
if (url) obj.url = url[1];
return obj
}
function addOptionalDepsToDeps (data, warn) {
var o = data.optionalDependencies
if (!o) return;
var d = data.dependencies || {}
Object.keys(o).forEach(function (k) {
d[k] = o[k]
})
data.dependencies = d
}
function depObjectify (deps, type, warn) {
if (!deps) return {}
if (typeof deps === "string") {
deps = deps.trim().split(/[\n\r\s\t ,]+/)
}
if (!Array.isArray(deps)) return deps
warn("deprecatedArrayDependencies", type)
var o = {}
deps.filter(function (d) {
return typeof d === "string"
}).forEach(function(d) {
d = d.trim().split(/(:?[@\s><=])/)
var dn = d.shift()
var dv = d.join("")
dv = dv.trim()
dv = dv.replace(/^@/, "")
o[dn] = dv
})
return o
}
function objectifyDeps (data, warn) {
depTypes.forEach(function (type) {
if (!data[type]) return;
data[type] = depObjectify(data[type], type, warn)
})
}
function bugsTypos(bugs, warn) {
if (!bugs) return
Object.keys(bugs).forEach(function (k) {
if (typos.bugs[k]) {
warn("typo", k, typos.bugs[k], "bugs")
bugs[typos.bugs[k]] = bugs[k]
delete bugs[k]
}
})
}

View File

@@ -0,0 +1,23 @@
var util = require("util")
var messages = require("./warning_messages.json")
module.exports = function() {
var args = Array.prototype.slice.call(arguments, 0)
var warningName = args.shift()
if (warningName == "typo") {
return makeTypoWarning.apply(null,args)
}
else {
var msgTemplate = messages[warningName] ? messages[warningName] : warningName + ": '%s'"
args.unshift(msgTemplate)
return util.format.apply(null, args)
}
}
function makeTypoWarning (providedName, probableName, field) {
if (field) {
providedName = field + "['" + providedName + "']"
probableName = field + "['" + probableName + "']"
}
return util.format(messages.typo, providedName, probableName)
}

View File

@@ -0,0 +1,39 @@
module.exports = normalize
var fixer = require("./fixer")
normalize.fixer = fixer
var makeWarning = require("./make_warning")
var fieldsToFix = ['name','version','description','repository','modules','scripts'
,'files','bin','man','bugs','keywords','readme','homepage','license']
var otherThingsToFix = ['dependencies','people', 'typos']
var thingsToFix = fieldsToFix.map(function(fieldName) {
return ucFirst(fieldName) + "Field"
})
// two ways to do this in CoffeeScript on only one line, sub-70 chars:
// thingsToFix = fieldsToFix.map (name) -> ucFirst(name) + "Field"
// thingsToFix = (ucFirst(name) + "Field" for name in fieldsToFix)
thingsToFix = thingsToFix.concat(otherThingsToFix)
function normalize (data, warn, strict) {
if(warn === true) warn = null, strict = true
if(!strict) strict = false
if(!warn || data.private) warn = function(msg) { /* noop */ }
if (data.scripts &&
data.scripts.install === "node-gyp rebuild" &&
!data.scripts.preinstall) {
data.gypfile = true
}
fixer.warn = function() { warn(makeWarning.apply(null, arguments)) }
thingsToFix.forEach(function(thingName) {
fixer["fix" + ucFirst(thingName)](data, strict)
})
data._id = data.name + "@" + data.version
}
function ucFirst (string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}

View File

@@ -0,0 +1,9 @@
var util = require('util')
module.exports = function() {
var args = Array.prototype.slice.call(arguments, 0)
args.forEach(function(arg) {
if (!arg) throw new TypeError('Bad arguments.')
})
return util.format.apply(null, arguments)
}

View File

@@ -0,0 +1,25 @@
{
"topLevel": {
"dependancies": "dependencies"
,"dependecies": "dependencies"
,"depdenencies": "dependencies"
,"devEependencies": "devDependencies"
,"depends": "dependencies"
,"dev-dependencies": "devDependencies"
,"devDependences": "devDependencies"
,"devDepenencies": "devDependencies"
,"devdependencies": "devDependencies"
,"repostitory": "repository"
,"repo": "repository"
,"prefereGlobal": "preferGlobal"
,"hompage": "homepage"
,"hampage": "homepage"
,"autohr": "author"
,"autor": "author"
,"contributers": "contributors"
,"publicationConfig": "publishConfig"
,"script": "scripts"
},
"bugs": { "web": "url", "name": "url" },
"script": { "server": "start", "tests": "test" }
}

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