init commit

This commit is contained in:
2016-06-09 17:51:55 -04:00
commit 486ed15b61
9915 changed files with 1035994 additions and 0 deletions

23
_site/node_modules/gulp-remote-src/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,23 @@
## Changelog
### v0.1.0 (2014-06-30)
First release.
### v0.2.0 (2014-07-01)
Fix streaming pipe.
Add tests for streaming pipe.
### v0.2.1 (2014-07-18)
Add option `strictSSL` (thank you [@Magomogo](https://github.com/Magomogo))
### v0.3.0 (2014-09-02)
Pass through [request](https://github.com/mikeal/request) options to make it flexible.
### v0.4.0 (2015-08-14)
Put `request` options in a single `requestOptions`.

90
_site/node_modules/gulp-remote-src/Gulpfile.js generated vendored Normal file
View File

@@ -0,0 +1,90 @@
var remoteSrc = require('./');
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var clean = require('gulp-clean');
var FILES = [
"src/node.js",
"lib/_debugger.js",
"lib/_linklist.js",
"lib/_stream_duplex.js",
"lib/_stream_passthrough.js",
"lib/_stream_readable.js",
"lib/_stream_transform.js",
"lib/_stream_writable.js",
"lib/assert.js",
"lib/buffer.js",
"lib/child_process.js",
"lib/cluster.js",
"lib/console.js",
"lib/constants.js",
"lib/crypto.js",
"lib/dgram.js",
"lib/dns.js",
"lib/domain.js",
"lib/events.js",
"lib/freelist.js",
"lib/fs.js",
"lib/http.js",
"lib/https.js",
"lib/module.js",
"lib/net.js",
"lib/os.js",
"lib/path.js",
"lib/punycode.js",
"lib/querystring.js",
"lib/readline.js",
"lib/repl.js",
"lib/stream.js",
"lib/string_decoder.js",
"lib/sys.js",
"lib/timers.js",
"lib/tls.js",
"lib/tty.js",
"lib/url.js",
"lib/util.js",
"lib/vm.js",
"lib/zlib.js"
];
var URL = "https://raw.githubusercontent.com/joyent/node/v0.10.29/"
gulp.task('clean', function() {
return gulp.src('dist', {read: false})
.pipe(clean());
});
gulp.task('nostream', ['clean'], function() {
return remoteSrc(FILES, {
base: URL
})
.pipe(uglify())
.pipe(gulp.dest('dist/nostream'));
});
gulp.task('stream', ['clean'], function() {
return remoteSrc(FILES, {
buffer: false,
base: URL
})
.pipe(gulp.dest('dist/stream'));
});
gulp.task('self-signed-ssl', ['clean'], function() {
return remoteSrc(['index.html'], {
strictSSL: false,
base: 'https://example.com/'
})
.pipe(gulp.dest('dist/strictSSL'));
});
// run this task alone to test timeout
gulp.task('timeout', ['clean'], function() {
return remoteSrc(FILES, {
base: URL,
timeout: 1
})
.pipe(gulp.dest('dist/timeout'));
});
gulp.task('test', ['stream', 'nostream', 'self-signed-ssl']);

23
_site/node_modules/gulp-remote-src/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,23 @@
MIT License
===========
Copyright (c) 2014 Dong <ddliuhb@gmail.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.

75
_site/node_modules/gulp-remote-src/README.md generated vendored Normal file
View File

@@ -0,0 +1,75 @@
# gulp-remote-src
[![Build Status](https://travis-ci.org/ddliu/gulp-remote-src.png)](https://travis-ci.org/ddliu/gulp-remote-src)
Remote `gulp.src`.
## Installation
Install package with NPM and add it to your development dependencies:
npm install --save-dev gulp-remote-src
## Usage
```js
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var remoteSrc = require('gulp-remote-src');
gulp.task('remote', function() {
remoteSrc(['app.js', 'jquery.js'], {
base: 'http://myapps.com/assets/',
})
.pipe(uglify())
.pipe(gulp.dest('./dist/'));
})
```
## Options
- `base`
Url base.
- `buffer` (default is true)
Pipe out files as buffer or as stream. Note that some plugins does not support streaming.
## Request Options
`gulp-remote-src` uses [request](https://github.com/mikeal/request) to make HTTP request, you can specify below
options to customize your request:
* `qs` - object containing querystring values to be appended to the `uri`
* `headers` - http headers (default: `{}`)
* `auth` - A hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). See documentation above.
* `followRedirect` - follow HTTP 3xx responses as redirects (default: `true`). This property can also be implemented as function which gets `response` object as a single argument and should return `true` if redirects should continue or `false` otherwise.
* `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects (default: `false`)
* `maxRedirects` - the maximum number of redirects to follow (default: `10`)
* `timeout` - Integer containing the number of milliseconds to wait for a request to respond before aborting the request
* `proxy` - An HTTP proxy to be used. Supports proxy Auth with Basic Auth, identical to support for the `url` parameter (by embedding the auth info in the `uri`)
* `strictSSL` - If `true`, requires SSL certificates be valid. **Note:** to use your own certificate authority, you need to specify an agent that was created with that CA as an option.
* `aws` - `object` containing AWS signing information. Should have the properties `key`, `secret`. Also requires the property `bucket`, unless youre specifying your `bucket` as part of the path, or the request doesnt use a bucket (i.e. GET Services)
* `gzip` - If `true`, add an `Accept-Encoding` header to request compressed content encodings from the server (if not already present) and decode supported content encodings in the response.
## Changelog
### v0.1.0 (2014-06-30)
First release.
### v0.2.0 (2014-07-01)
Fix streaming pipe.
Add tests for streaming pipe.
### v0.2.1 (2014-07-18)
Add option `strictSSL` (thank you [@Magomogo](https://github.com/Magomogo))
### v0.3.0 (2014-09-02)
Pass through [request](https://github.com/mikeal/request) options to make it flexible.

77
_site/node_modules/gulp-remote-src/index.js generated vendored Normal file
View File

@@ -0,0 +1,77 @@
var util = require('util');
var es = require('event-stream');
var request = require('request');
var File = require('vinyl');
var through2 = require('through2');
var extend = require('node.extend');
module.exports = function(urls, options) {
if (options === undefined) {
options = {};
}
if (typeof options.base !== 'string' ) {
options.base = '/';
}
if (typeof options.buffer !== 'boolean') {
options.buffer = true;
}
if (!util.isArray(urls)) {
urls = [urls];
}
var allowedRequestOptions = ['qs', 'headers', 'auth', 'followRedirect', 'followAllRedirects', 'maxRedirects', 'timeout', 'proxy',
'strictSSL', 'aws', 'gzip']
var requestBaseOptions = {};
for (var i = allowedRequestOptions.length - 1; i >= 0; i--) {
var k = allowedRequestOptions[i];
if (k in options) {
requestBaseOptions[k] = options[k];
}
}
if (options.requestOptions) {
for (var k in options.requestOptions) {
requestBaseOptions[k] = options.requestOptions[k];
}
}
return es.readArray(urls).pipe(es.map(function(data, cb) {
var url = options.base + data, requestOptions = extend({url: url}, requestBaseOptions);
if (!options.buffer) {
var file = new File({
cwd: '/',
base: options.base,
path: url,
// request must be piped out once created, or we'll get this error: "You cannot pipe after data has been emitted from the response."
contents: request(requestOptions).pipe(through2())
});
cb(null, file);
} else {
// set encoding to `null` to return the body as buffer
requestOptions.encoding = null;
request(requestOptions, function(error, response, body) {
if (!error && response.statusCode == 200) {
var file = new File({
cwd: '/',
base: options.base,
path: url,
contents: body
});
cb(null, file);
} else {
if (!error) {
error = new Error("GET " + url + " failed with status code:" + response.statusCode);
}
cb(error);
}
});
}
}));
};

View File

@@ -0,0 +1,22 @@
Copyright (c) 2011 Dominic Tarr
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,25 @@
var inspect = require('util').inspect
if(!module.parent) {
var es = require('..') //load event-stream
es.pipe( //pipe joins streams together
process.openStdin(), //open stdin
es.split(), //split stream to break on newlines
es.map(function (data, callback) {//turn this async function into a stream
var j
try {
j = JSON.parse(data) //try to parse input into json
} catch (err) {
return callback(null, data) //if it fails just pass it anyway
}
callback(null, inspect(j)) //render it nicely
}),
process.stdout // pipe it to stdout !
)
}
// run this
//
// curl -sS registry.npmjs.org/event-stream | node pretty.js
//

View File

@@ -0,0 +1,306 @@
//filter will reemit the data if cb(err,pass) pass is truthy
// reduce is more tricky
// maybe we want to group the reductions or emit progress updates occasionally
// the most basic reduce just emits one 'data' event after it has recieved 'end'
var Stream = require('stream').Stream
, es = exports
, through = require('through')
, from = require('from')
, duplex = require('duplexer')
, map = require('map-stream')
, pause = require('pause-stream')
, split = require('split')
, pipeline = require('stream-combiner')
, immediately = global.setImmediate || process.nextTick;
es.Stream = Stream //re-export Stream from core
es.through = through
es.from = from
es.duplex = duplex
es.map = map
es.pause = pause
es.split = split
es.pipeline = es.connect = es.pipe = pipeline
// merge / concat
//
// combine multiple streams into a single stream.
// will emit end only once
es.concat = //actually this should be called concat
es.merge = function (/*streams...*/) {
var toMerge = [].slice.call(arguments)
var stream = new Stream()
stream.setMaxListeners(0) // allow adding more than 11 streams
var endCount = 0
stream.writable = stream.readable = true
toMerge.forEach(function (e) {
e.pipe(stream, {end: false})
var ended = false
e.on('end', function () {
if(ended) return
ended = true
endCount ++
if(endCount == toMerge.length)
stream.emit('end')
})
})
stream.write = function (data) {
this.emit('data', data)
}
stream.destroy = function () {
toMerge.forEach(function (e) {
if(e.destroy) e.destroy()
})
}
return stream
}
// writable stream, collects all events into an array
// and calls back when 'end' occurs
// mainly I'm using this to test the other functions
es.writeArray = function (done) {
if ('function' !== typeof done)
throw new Error('function writeArray (done): done must be function')
var a = new Stream ()
, array = [], isDone = false
a.write = function (l) {
array.push(l)
}
a.end = function () {
isDone = true
done(null, array)
}
a.writable = true
a.readable = false
a.destroy = function () {
a.writable = a.readable = false
if(isDone) return
done(new Error('destroyed before end'), array)
}
return a
}
//return a Stream that reads the properties of an object
//respecting pause() and resume()
es.readArray = function (array) {
var stream = new Stream()
, i = 0
, paused = false
, ended = false
stream.readable = true
stream.writable = false
if(!Array.isArray(array))
throw new Error('event-stream.read expects an array')
stream.resume = function () {
if(ended) return
paused = false
var l = array.length
while(i < l && !paused && !ended) {
stream.emit('data', array[i++])
}
if(i == l && !ended)
ended = true, stream.readable = false, stream.emit('end')
}
process.nextTick(stream.resume)
stream.pause = function () {
paused = true
}
stream.destroy = function () {
ended = true
stream.emit('close')
}
return stream
}
//
// readable (asyncFunction)
// return a stream that calls an async function while the stream is not paused.
//
// the function must take: (count, callback) {...
//
es.readable =
function (func, continueOnError) {
var stream = new Stream()
, i = 0
, paused = false
, ended = false
, reading = false
stream.readable = true
stream.writable = false
if('function' !== typeof func)
throw new Error('event-stream.readable expects async function')
stream.on('end', function () { ended = true })
function get (err, data) {
if(err) {
stream.emit('error', err)
if(!continueOnError) stream.emit('end')
} else if (arguments.length > 1)
stream.emit('data', data)
immediately(function () {
if(ended || paused || reading) return
try {
reading = true
func.call(stream, i++, function () {
reading = false
get.apply(null, arguments)
})
} catch (err) {
stream.emit('error', err)
}
})
}
stream.resume = function () {
paused = false
get()
}
process.nextTick(get)
stream.pause = function () {
paused = true
}
stream.destroy = function () {
stream.emit('end')
stream.emit('close')
ended = true
}
return stream
}
//
// map sync
//
es.mapSync = function (sync) {
return es.through(function write(data) {
var mappedData = sync(data)
if (typeof mappedData !== 'undefined')
this.emit('data', mappedData)
})
}
//
// log just print out what is coming through the stream, for debugging
//
es.log = function (name) {
return es.through(function (data) {
var args = [].slice.call(arguments)
if(name) console.error(name, data)
else console.error(data)
this.emit('data', data)
})
}
//
// child -- pipe through a child process
//
es.child = function (child) {
return es.duplex(child.stdin, child.stdout)
}
//
// parse
//
// must be used after es.split() to ensure that each chunk represents a line
// source.pipe(es.split()).pipe(es.parse())
es.parse = function () {
return es.through(function (data) {
var obj
try {
if(data) //ignore empty lines
obj = JSON.parse(data.toString())
} catch (err) {
return console.error(err, 'attemping to parse:', data)
}
//ignore lines that where only whitespace.
if(obj !== undefined)
this.emit('data', obj)
})
}
//
// stringify
//
es.stringify = function () {
var Buffer = require('buffer').Buffer
return es.mapSync(function (e){
return JSON.stringify(Buffer.isBuffer(e) ? e.toString() : e) + '\n'
})
}
//
// replace a string within a stream.
//
// warn: just concatenates the string and then does str.split().join().
// probably not optimal.
// for smallish responses, who cares?
// I need this for shadow-npm so it's only relatively small json files.
es.replace = function (from, to) {
return es.pipeline(es.split(from), es.join(to))
}
//
// join chunks with a joiner. just like Array#join
// also accepts a callback that is passed the chunks appended together
// this is still supported for legacy reasons.
//
es.join = function (str) {
//legacy api
if('function' === typeof str)
return es.wait(str)
var first = true
return es.through(function (data) {
if(!first)
this.emit('data', str)
first = false
this.emit('data', data)
return true
})
}
//
// wait. callback when 'end' is emitted, with all chunks appended as string.
//
es.wait = function (callback) {
var arr = []
return es.through(function (data) { arr.push(data) },
function () {
var body = Buffer.isBuffer(arr[0]) ? Buffer.concat(arr)
: arr.join('')
this.emit('data', body)
this.emit('end')
if(callback) callback(null, body)
})
}
es.pipeable = function () {
throw new Error('[EVENT-STREAM] es.pipeable is deprecated')
}

View File

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

View File

@@ -0,0 +1,47 @@
# duplexer
[![build status][1]][2] [![dependency status][3]][4]
[![browser support][5]][6]
Creates a duplex stream
Taken from [event-stream][7]
## duplex (writeStream, readStream)
Takes a writable stream and a readable stream and makes them appear as a readable writable stream.
It is assumed that the two streams are connected to each other in some way.
## Example
```js
var grep = cp.exec('grep Stream')
duplex(grep.stdin, grep.stdout)
```
## Installation
`npm install duplexer`
## Tests
`npm test`
## Contributors
- Dominictarr
- Raynos
- samccone
## MIT Licenced
[1]: https://secure.travis-ci.org/Raynos/duplexer.png
[2]: https://travis-ci.org/Raynos/duplexer
[3]: https://david-dm.org/Raynos/duplexer.png
[4]: https://david-dm.org/Raynos/duplexer
[5]: https://ci.testling.com/Raynos/duplexer.png
[6]: https://ci.testling.com/Raynos/duplexer
[7]: https://github.com/dominictarr/event-stream#duplex-writestream-readstream

View File

@@ -0,0 +1,87 @@
var Stream = require("stream")
var writeMethods = ["write", "end", "destroy"]
var readMethods = ["resume", "pause"]
var readEvents = ["data", "close"]
var slice = Array.prototype.slice
module.exports = duplex
function forEach (arr, fn) {
if (arr.forEach) {
return arr.forEach(fn)
}
for (var i = 0; i < arr.length; i++) {
fn(arr[i], i)
}
}
function duplex(writer, reader) {
var stream = new Stream()
var ended = false
forEach(writeMethods, proxyWriter)
forEach(readMethods, proxyReader)
forEach(readEvents, proxyStream)
reader.on("end", handleEnd)
writer.on("drain", function() {
stream.emit("drain")
})
writer.on("error", reemit)
reader.on("error", reemit)
stream.writable = writer.writable
stream.readable = reader.readable
return stream
function proxyWriter(methodName) {
stream[methodName] = method
function method() {
return writer[methodName].apply(writer, arguments)
}
}
function proxyReader(methodName) {
stream[methodName] = method
function method() {
stream.emit(methodName)
var func = reader[methodName]
if (func) {
return func.apply(reader, arguments)
}
reader.emit(methodName)
}
}
function proxyStream(methodName) {
reader.on(methodName, reemit)
function reemit() {
var args = slice.call(arguments)
args.unshift(methodName)
stream.emit.apply(stream, args)
}
}
function handleEnd() {
if (ended) {
return
}
ended = true
var args = slice.call(arguments)
args.unshift("end")
stream.emit.apply(stream, args)
}
function reemit(err) {
stream.emit("error", err)
}
}

View File

@@ -0,0 +1,79 @@
{
"name": "duplexer",
"version": "0.1.1",
"description": "Creates a duplex stream",
"keywords": [],
"author": {
"name": "Raynos",
"email": "raynos2@gmail.com"
},
"repository": {
"type": "git",
"url": "git://github.com/Raynos/duplexer.git"
},
"main": "index",
"homepage": "https://github.com/Raynos/duplexer",
"contributors": [
{
"name": "Jake Verbaten"
}
],
"bugs": {
"url": "https://github.com/Raynos/duplexer/issues",
"email": "raynos2@gmail.com"
},
"devDependencies": {
"tape": "0.3.3",
"through": "~0.1.4"
},
"licenses": [
{
"type": "MIT",
"url": "http://github.com/Raynos/duplexer/raw/master/LICENSE"
}
],
"scripts": {
"test": "node test"
},
"testling": {
"files": "test/index.js",
"browsers": [
"ie/8..latest",
"firefox/16..latest",
"firefox/nightly",
"chrome/22..latest",
"chrome/canary",
"opera/12..latest",
"opera/next",
"safari/5.1..latest",
"ipad/6.0..latest",
"iphone/6.0..latest"
]
},
"readme": "# duplexer\n\n[![build status][1]][2] [![dependency status][3]][4]\n\n[![browser support][5]][6]\n\nCreates a duplex stream\n\nTaken from [event-stream][7]\n\n## duplex (writeStream, readStream)\n\nTakes a writable stream and a readable stream and makes them appear as a readable writable stream.\n\nIt is assumed that the two streams are connected to each other in some way.\n\n## Example\n\n```js\nvar grep = cp.exec('grep Stream')\n\nduplex(grep.stdin, grep.stdout)\n```\n\n## Installation\n\n`npm install duplexer`\n\n## Tests\n\n`npm test`\n\n## Contributors\n\n - Dominictarr\n - Raynos\n - samccone\n\n## MIT Licenced\n\n [1]: https://secure.travis-ci.org/Raynos/duplexer.png\n [2]: https://travis-ci.org/Raynos/duplexer\n [3]: https://david-dm.org/Raynos/duplexer.png\n [4]: https://david-dm.org/Raynos/duplexer\n [5]: https://ci.testling.com/Raynos/duplexer.png\n [6]: https://ci.testling.com/Raynos/duplexer\n [7]: https://github.com/dominictarr/event-stream#duplex-writestream-readstream\n",
"readmeFilename": "README.md",
"_id": "duplexer@0.1.1",
"dist": {
"shasum": "ace6ff808c1ce66b57d1ebf97977acb02334cfc1",
"tarball": "http://registry.npmjs.org/duplexer/-/duplexer-0.1.1.tgz"
},
"_from": "duplexer@>=0.1.1 <0.2.0",
"_npmVersion": "1.2.18",
"_npmUser": {
"name": "raynos",
"email": "raynos2@gmail.com"
},
"maintainers": [
{
"name": "raynos",
"email": "raynos2@gmail.com"
},
{
"name": "dominictarr",
"email": "dominic.tarr@gmail.com"
}
],
"directories": {},
"_shasum": "ace6ff808c1ce66b57d1ebf97977acb02334cfc1",
"_resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.1.tgz"
}

View File

@@ -0,0 +1,31 @@
var through = require("through")
var test = require("tape")
var duplex = require("../index")
var readable = through()
var writable = through(write)
var written = 0
var data = 0
var stream = duplex(writable, readable)
function write() {
written++
}
stream.on("data", ondata)
function ondata() {
data++
}
test("emit and write", function(t) {
t.plan(2)
stream.write()
readable.emit("data")
t.equal(written, 1, "should have written once")
t.equal(data, 1, "should have recived once")
})

View File

@@ -0,0 +1,15 @@
Apache License, Version 2.0
Copyright (c) 2011 Dominic Tarr
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,24 @@
The MIT License
Copyright (c) 2011 Dominic Tarr
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 @@
'use strict';
var Stream = require('stream')
// from
//
// a stream that reads from an source.
// source may be an array, or a function.
// from handles pause behaviour for you.
module.exports =
function from (source) {
if(Array.isArray(source)) {
source = source.slice()
return from (function (i) {
if(source.length)
this.emit('data', source.shift())
else
this.emit('end')
return true
})
}
var s = new Stream(), i = 0
s.ended = false
s.started = false
s.readable = true
s.writable = false
s.paused = false
s.ended = false
s.pause = function () {
s.started = true
s.paused = true
}
function next () {
s.started = true
if(s.ended) return
while(!s.ended && !s.paused && source.call(s, i++, function () {
if(!s.ended && !s.paused)
next()
}))
;
}
s.resume = function () {
s.started = true
s.paused = false
next()
}
s.on('end', function () {
s.ended = true
s.readable = false
process.nextTick(s.destroy)
})
s.destroy = function () {
s.ended = true
s.emit('close')
}
/*
by default, the stream will start emitting at nextTick
if you want, you can pause it, after pipeing.
you can also resume before next tick, and that will also
work.
*/
process.nextTick(function () {
if(!s.started) s.resume()
})
return s
}

View File

@@ -0,0 +1,56 @@
{
"name": "from",
"version": "0.1.3",
"description": "Easy way to make a Readable Stream",
"main": "index.js",
"scripts": {
"test": "asynct test/*.js"
},
"repository": {
"type": "git",
"url": "git://github.com/dominictarr/from.git"
},
"keywords": [
"stream",
"streams",
"readable",
"easy"
],
"devDependencies": {
"asynct": "1",
"stream-spec": "0",
"assertions": "~2.3.0"
},
"author": {
"name": "Dominic Tarr",
"email": "dominic.tarr@gmail.com",
"url": "dominictarr.com"
},
"license": "MIT",
"readme": "# from\n\nAn easy way to create a `readable Stream`.\n\n## from(function getChunk(count, next))\n\nfrom takes a `getChunk` function and returns a stream. \n\n`getChunk` is called again and again, after each time the user calls `next()`, \nuntil the user emits `'end'`\n\nif `pause()` is called, the `getChunk` won't be called again untill `resume()` is called.\n\n\n```js\nvar from = require('from')\n\nvar stream = \n from(function getChunk(count, next) {\n //do some sort of data\n this.emit('data', whatever)\n \n if(itsOver)\n this.emit('end')\n\n //ready to handle the next chunk\n next()\n //or, if it's sync:\n return true \n })\n```\n\n## from(array)\n\nfrom also takes an `Array` whose elements it emits one after another.\n\n## License\nMIT / Apache2\n",
"readmeFilename": "readme.markdown",
"_id": "from@0.1.3",
"dist": {
"shasum": "ef63ac2062ac32acf7862e0d40b44b896f22f3bc",
"tarball": "http://registry.npmjs.org/from/-/from-0.1.3.tgz"
},
"_from": "from@>=0.0.0 <1.0.0",
"_npmVersion": "1.2.3",
"_npmUser": {
"name": "dominictarr",
"email": "dominic.tarr@gmail.com"
},
"maintainers": [
{
"name": "dominictarr",
"email": "dominic.tarr@gmail.com"
}
],
"directories": {},
"_shasum": "ef63ac2062ac32acf7862e0d40b44b896f22f3bc",
"_resolved": "https://registry.npmjs.org/from/-/from-0.1.3.tgz",
"bugs": {
"url": "https://github.com/dominictarr/from/issues"
},
"homepage": "https://github.com/dominictarr/from#readme"
}

View File

@@ -0,0 +1,38 @@
# from
An easy way to create a `readable Stream`.
## from(function getChunk(count, next))
from takes a `getChunk` function and returns a stream.
`getChunk` is called again and again, after each time the user calls `next()`,
until the user emits `'end'`
if `pause()` is called, the `getChunk` won't be called again untill `resume()` is called.
```js
var from = require('from')
var stream =
from(function getChunk(count, next) {
//do some sort of data
this.emit('data', whatever)
if(itsOver)
this.emit('end')
//ready to handle the next chunk
next()
//or, if it's sync:
return true
})
```
## from(array)
from also takes an `Array` whose elements it emits one after another.
## License
MIT / Apache2

View File

@@ -0,0 +1,141 @@
var from = require('..')
var spec = require('stream-spec')
var a = require('assertions')
function read(stream, callback) {
var actual = []
stream.on('data', function (data) {
actual.push(data)
})
stream.once('end', function () {
callback(null, actual)
})
stream.once('error', function (err) {
callback(err)
})
}
function pause(stream) {
stream.on('data', function () {
if(Math.random() > 0.1) return
stream.pause()
process.nextTick(function () {
stream.resume()
})
})
}
exports['inc'] = function (test) {
var fs = from(function (i) {
this.emit('data', i)
if(i >= 99)
return this.emit('end')
return true
})
spec(fs).readable().validateOnExit()
read(fs, function (err, arr) {
test.equal(arr.length, 100)
test.done()
})
}
exports['simple'] = function (test) {
var l = 1000
, expected = []
while(l--) expected.push(l * Math.random())
var t = from(expected.slice())
spec(t)
.readable()
.pausable({strict: true})
.validateOnExit()
read(t, function (err, actual) {
if(err) test.error(err) //fail
a.deepEqual(actual, expected)
test.done()
})
}
exports['simple pausable'] = function (test) {
var l = 1000
, expected = []
while(l--) expected.push(l * Math.random())
var t = from(expected.slice())
spec(t)
.readable()
.pausable({strict: true})
.validateOnExit()
pause(t)
read(t, function (err, actual) {
if(err) test.error(err) //fail
a.deepEqual(actual, expected)
test.done()
})
}
exports['simple (not strictly pausable) setTimeout'] = function (test) {
var l = 10
, expected = []
while(l--) expected.push(l * Math.random())
var _expected = expected.slice()
var t = from(function (i, n) {
var self = this
setTimeout(function () {
if(_expected.length)
self.emit('data', _expected.shift())
else
self.emit('end')
n()
}, 3)
})
/*
using from in this way will not be strictly pausable.
it could be extended to buffer outputs, but I think a better
way would be to use a PauseStream that implements strict pause.
*/
spec(t)
.readable()
.pausable({strict: false })
.validateOnExit()
//pause(t)
var paused = false
var i = setInterval(function () {
if(!paused) t.pause()
else t.resume()
paused = !paused
}, 2)
t.on('end', function () {
clearInterval(i)
})
read(t, function (err, actual) {
if(err) test.error(err) //fail
a.deepEqual(actual, expected)
test.done()
})
}

View File

@@ -0,0 +1,22 @@
Copyright (c) 2011 Dominic Tarr
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,26 @@
var inspect = require('util').inspect
if(!module.parent) {
var map = require('..') //load map-stream
var es = require('event-stream') //load event-stream
es.pipe( //pipe joins streams together
process.openStdin(), //open stdin
es.split(), //split stream to break on newlines
map(function (data, callback) { //turn this async function into a stream
var j
try {
j = JSON.parse(data) //try to parse input into json
} catch (err) {
return callback(null, data) //if it fails just pass it anyway
}
callback(null, inspect(j)) //render it nicely
}),
process.stdout // pipe it to stdout !
)
}
// run this
//
// curl -sS registry.npmjs.org/event-stream | node pretty.js
//

View File

@@ -0,0 +1,145 @@
//filter will reemit the data if cb(err,pass) pass is truthy
// reduce is more tricky
// maybe we want to group the reductions or emit progress updates occasionally
// the most basic reduce just emits one 'data' event after it has recieved 'end'
var Stream = require('stream').Stream
//create an event stream and apply function to each .write
//emitting each response as data
//unless it's an empty callback
module.exports = function (mapper, opts) {
var stream = new Stream()
, self = this
, inputs = 0
, outputs = 0
, ended = false
, paused = false
, destroyed = false
, lastWritten = 0
, inNext = false
this.opts = opts || {};
var errorEventName = this.opts.failures ? 'failure' : 'error';
// Items that are not ready to be written yet (because they would come out of
// order) get stuck in a queue for later.
var writeQueue = {}
stream.writable = true
stream.readable = true
function queueData (data, number) {
var nextToWrite = lastWritten + 1
if (number === nextToWrite) {
// If it's next, and its not undefined write it
if (data !== undefined) {
stream.emit.apply(stream, ['data', data])
}
lastWritten ++
nextToWrite ++
} else {
// Otherwise queue it for later.
writeQueue[number] = data
}
// If the next value is in the queue, write it
if (writeQueue.hasOwnProperty(nextToWrite)) {
var dataToWrite = writeQueue[nextToWrite]
delete writeQueue[nextToWrite]
return queueData(dataToWrite, nextToWrite)
}
outputs ++
if(inputs === outputs) {
if(paused) paused = false, stream.emit('drain') //written all the incoming events
if(ended) end()
}
}
function next (err, data, number) {
if(destroyed) return
inNext = true
if (!err || self.opts.failures) {
queueData(data, number)
}
if (err) {
stream.emit.apply(stream, [ errorEventName, err ]);
}
inNext = false;
}
// Wrap the mapper function by calling its callback with the order number of
// the item in the stream.
function wrappedMapper (input, number, callback) {
return mapper.call(null, input, function(err, data){
callback(err, data, number)
})
}
stream.write = function (data) {
if(ended) throw new Error('map stream is not writable')
inNext = false
inputs ++
try {
//catch sync errors and handle them like async errors
var written = wrappedMapper(data, inputs, next)
paused = (written === false)
return !paused
} catch (err) {
//if the callback has been called syncronously, and the error
//has occured in an listener, throw it again.
if(inNext)
throw err
next(err)
return !paused
}
}
function end (data) {
//if end was called with args, write it,
ended = true //write will emit 'end' if ended is true
stream.writable = false
if(data !== undefined) {
return queueData(data, inputs)
} else if (inputs == outputs) { //wait for processing
stream.readable = false, stream.emit('end'), stream.destroy()
}
}
stream.end = function (data) {
if(ended) return
end()
}
stream.destroy = function () {
ended = destroyed = true
stream.writable = stream.readable = paused = false
process.nextTick(function () {
stream.emit('close')
})
}
stream.pause = function () {
paused = true
}
stream.resume = function () {
paused = false
}
return stream
}

View File

@@ -0,0 +1,51 @@
{
"name": "map-stream",
"version": "0.1.0",
"description": "construct pipes of streams of events",
"homepage": "http://github.com/dominictarr/map-stream",
"repository": {
"type": "git",
"url": "git://github.com/dominictarr/map-stream.git"
},
"dependencies": {},
"devDependencies": {
"asynct": "*",
"it-is": "1",
"ubelt": "~2.9",
"stream-spec": "~0.2",
"event-stream": "~2.1",
"from": "0.0.2"
},
"scripts": {
"test": "asynct test/"
},
"author": {
"name": "Dominic Tarr",
"email": "dominic.tarr@gmail.com",
"url": "http://dominictarr.com"
},
"bugs": {
"url": "https://github.com/dominictarr/map-stream/issues"
},
"_id": "map-stream@0.1.0",
"dist": {
"shasum": "e56aa94c4c8055a16404a0674b78f215f7c8e194",
"tarball": "http://registry.npmjs.org/map-stream/-/map-stream-0.1.0.tgz"
},
"_from": "map-stream@>=0.1.0 <0.2.0",
"_npmVersion": "1.3.21",
"_npmUser": {
"name": "dominictarr",
"email": "dominic.tarr@gmail.com"
},
"maintainers": [
{
"name": "dominictarr",
"email": "dominic.tarr@gmail.com"
}
],
"directories": {},
"_shasum": "e56aa94c4c8055a16404a0674b78f215f7c8e194",
"_resolved": "https://registry.npmjs.org/map-stream/-/map-stream-0.1.0.tgz",
"readme": "ERROR: No README data found!"
}

View File

@@ -0,0 +1,37 @@
# MapStream
Refactored out of [event-stream](https://github.com/dominictarr/event-stream)
##map (asyncFunction[, options])
Create a through stream from an asyncronous function.
``` js
var map = require('map-stream')
map(function (data, callback) {
//transform data
// ...
callback(null, data)
})
```
Each map MUST call the callback. It may callback with data, with an error or with no arguments,
* `callback()` drop this data.
this makes the map work like `filter`,
note:`callback(null,null)` is not the same, and will emit `null`
* `callback(null, newData)` turn data into newData
* `callback(error)` emit an error for this item.
>Note: if a callback is not called, `map` will think that it is still being processed,
>every call must be answered or the stream will not know when to end.
>
>Also, if the callback is called more than once, every call but the first will be ignored.
##Options
* `failures` - `boolean` continue mapping even if error occured. On error `map-stream` will emit `failure` event. (default: `false`)

View File

@@ -0,0 +1,318 @@
'use strict';
var map = require('../')
, it = require('it-is')
, u = require('ubelt')
, spec = require('stream-spec')
, from = require('from')
, Stream = require('stream')
, es = require('event-stream')
//REFACTOR THIS TEST TO USE es.readArray and es.writeArray
function writeArray(array, stream) {
array.forEach( function (j) {
stream.write(j)
})
stream.end()
}
function readStream(stream, done) {
var array = []
stream.on('data', function (data) {
array.push(data)
})
stream.on('error', done)
stream.on('end', function (data) {
done(null, array)
})
}
//call sink on each write,
//and complete when finished.
function pauseStream (prob, delay) {
var pauseIf = (
'number' == typeof prob
? function () {
return Math.random() < prob
}
: 'function' == typeof prob
? prob
: 0.1
)
var delayer = (
!delay
? process.nextTick
: 'number' == typeof delay
? function (next) { setTimeout(next, delay) }
: delay
)
return es.through(function (data) {
if(!this.paused && pauseIf()) {
console.log('PAUSE STREAM PAUSING')
this.pause()
var self = this
delayer(function () {
console.log('PAUSE STREAM RESUMING')
self.resume()
})
}
console.log("emit ('data', " + data + ')')
this.emit('data', data)
})
}
exports ['simple map applied to a stream'] = function (test) {
var input = [1,2,3,7,5,3,1,9,0,2,4,6]
//create event stream from
var doubler = map(function (data, cb) {
cb(null, data * 2)
})
spec(doubler).through().validateOnExit()
//a map is only a middle man, so it is both readable and writable
it(doubler).has({
readable: true,
writable: true,
})
readStream(doubler, function (err, output) {
it(output).deepEqual(input.map(function (j) {
return j * 2
}))
// process.nextTick(x.validate)
test.done()
})
writeArray(input, doubler)
}
exports ['stream comes back in the correct order'] = function (test) {
var input = [3, 2, 1]
var delayer = map(function(data, cb){
setTimeout(function () {
cb(null, data)
}, 100 * data)
})
readStream(delayer, function (err, output) {
it(output).deepEqual(input)
test.done()
})
writeArray(input, delayer)
}
exports ['continues on error event with failures `true`'] = function (test) {
var input = [1, 2, 3]
var delayer = map(function(data, cb){
cb(new Error('Something gone wrong'), data)
}, { failures: true })
readStream(delayer, function (err, output) {
it(output).deepEqual(input)
test.done()
})
writeArray(input, delayer)
}
exports['pipe two maps together'] = function (test) {
var input = [1,2,3,7,5,3,1,9,0,2,4,6]
//create event stream from
function dd (data, cb) {
cb(null, data * 2)
}
var doubler1 = map(dd), doubler2 = map(dd)
doubler1.pipe(doubler2)
spec(doubler1).through().validateOnExit()
spec(doubler2).through().validateOnExit()
readStream(doubler2, function (err, output) {
it(output).deepEqual(input.map(function (j) {
return j * 4
}))
test.done()
})
writeArray(input, doubler1)
}
//next:
//
// test pause, resume and drian.
//
// then make a pipe joiner:
//
// plumber (evStr1, evStr2, evStr3, evStr4, evStr5)
//
// will return a single stream that write goes to the first
exports ['map will not call end until the callback'] = function (test) {
var ticker = map(function (data, cb) {
process.nextTick(function () {
cb(null, data * 2)
})
})
spec(ticker).through().validateOnExit()
ticker.write('x')
ticker.end()
ticker.on('end', function () {
test.done()
})
}
exports ['emit failures with opts.failures === `ture`'] = function (test) {
var err = new Error('INTENSIONAL ERROR')
, mapper =
map(function () {
throw err
}, { failures: true })
mapper.on('failure', function (_err) {
it(_err).equal(err)
test.done()
})
mapper.write('hello')
}
exports ['emit error thrown'] = function (test) {
var err = new Error('INTENSIONAL ERROR')
, mapper =
map(function () {
throw err
})
mapper.on('error', function (_err) {
it(_err).equal(err)
test.done()
})
mapper.write('hello')
}
exports ['emit error calledback'] = function (test) {
var err = new Error('INTENSIONAL ERROR')
, mapper =
map(function (data, callback) {
callback(err)
})
mapper.on('error', function (_err) {
it(_err).equal(err)
test.done()
})
mapper.write('hello')
}
exports ['do not emit drain if not paused'] = function (test) {
var maps = map(function (data, callback) {
u.delay(callback)(null, 1)
return true
})
spec(maps).through().pausable().validateOnExit()
maps.on('drain', function () {
it(false).ok('should not emit drain unless the stream is paused')
})
it(maps.write('hello')).equal(true)
it(maps.write('hello')).equal(true)
it(maps.write('hello')).equal(true)
setTimeout(function () {maps.end()},10)
maps.on('end', test.done)
}
exports ['emits drain if paused, when all '] = function (test) {
var active = 0
var drained = false
var maps = map(function (data, callback) {
active ++
u.delay(function () {
active --
callback(null, 1)
})()
console.log('WRITE', false)
return false
})
spec(maps).through().validateOnExit()
maps.on('drain', function () {
drained = true
it(active).equal(0, 'should emit drain when all maps are done')
})
it(maps.write('hello')).equal(false)
it(maps.write('hello')).equal(false)
it(maps.write('hello')).equal(false)
process.nextTick(function () {maps.end()},10)
maps.on('end', function () {
console.log('end')
it(drained).ok('shoud have emitted drain before end')
test.done()
})
}
exports ['map applied to a stream with filtering'] = function (test) {
var input = [1,2,3,7,5,3,1,9,0,2,4,6]
var doubler = map(function (data, callback) {
if (data % 2)
callback(null, data * 2)
else
callback()
})
readStream(doubler, function (err, output) {
it(output).deepEqual(input.filter(function (j) {
return j % 2
}).map(function (j) {
return j * 2
}))
test.done()
})
spec(doubler).through().validateOnExit()
writeArray(input, doubler)
}

View File

@@ -0,0 +1,231 @@
Dual Licensed MIT and Apache 2
The MIT License
Copyright (c) 2013 Dominic Tarr
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.
-----------------------------------------------------------------------
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright (c) 2013 Dominic Tarr
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,3 @@
//through@2 handles this by default!
module.exports = require('through')

View File

@@ -0,0 +1,64 @@
{
"name": "pause-stream",
"version": "0.0.11",
"description": "a ThroughStream that strictly buffers all readable events when paused.",
"main": "index.js",
"directories": {
"test": "test"
},
"devDependencies": {
"stream-tester": "0.0.2",
"stream-spec": "~0.2.0"
},
"scripts": {
"test": "node test/index.js && node test/pause-end.js"
},
"repository": {
"type": "git",
"url": "git://github.com/dominictarr/pause-stream.git"
},
"keywords": [
"stream",
"pipe",
"pause",
"drain",
"buffer"
],
"author": {
"name": "Dominic Tarr",
"email": "dominic.tarr@gmail.com",
"url": "dominictarr.com"
},
"license": [
"MIT",
"Apache2"
],
"dependencies": {
"through": "~2.3"
},
"readme": "# PauseStream\n\nThis is a `Stream` that will strictly buffer when paused.\nConnect it to anything you need buffered.\n\n``` js\n var ps = require('pause-stream')();\n\n badlyBehavedStream.pipe(ps.pause())\n\n aLittleLater(function (err, data) {\n ps.pipe(createAnotherStream(data))\n ps.resume()\n })\n```\n\n`PauseStream` will buffer whenever paused.\nit will buffer when yau have called `pause` manually.\nbut also when it's downstream `dest.write()===false`.\nit will attempt to drain the buffer when you call resume\nor the downstream emits `'drain'`\n\n`PauseStream` is tested using [stream-spec](https://github.com/dominictarr/stream-spec)\nand [stream-tester](https://github.com/dominictarr/stream-tester)\n\nThis is now the default case of \n[through](https://github.com/dominictarr/through)\n\nhttps://github.com/dominictarr/pause-stream/commit/4a6fe3dc2c11091b1efbfde912e0473719ed9cc0\n",
"readmeFilename": "readme.markdown",
"bugs": {
"url": "https://github.com/dominictarr/pause-stream/issues"
},
"_id": "pause-stream@0.0.11",
"dist": {
"shasum": "fe5a34b0cbce12b5aa6a2b403ee2e73b602f1445",
"tarball": "http://registry.npmjs.org/pause-stream/-/pause-stream-0.0.11.tgz"
},
"_from": "pause-stream@0.0.11",
"_npmVersion": "1.3.6",
"_npmUser": {
"name": "dominictarr",
"email": "dominic.tarr@gmail.com"
},
"maintainers": [
{
"name": "dominictarr",
"email": "dominic.tarr@gmail.com"
}
],
"_shasum": "fe5a34b0cbce12b5aa6a2b403ee2e73b602f1445",
"_resolved": "https://registry.npmjs.org/pause-stream/-/pause-stream-0.0.11.tgz",
"homepage": "https://github.com/dominictarr/pause-stream#readme"
}

View File

@@ -0,0 +1,29 @@
# PauseStream
This is a `Stream` that will strictly buffer when paused.
Connect it to anything you need buffered.
``` js
var ps = require('pause-stream')();
badlyBehavedStream.pipe(ps.pause())
aLittleLater(function (err, data) {
ps.pipe(createAnotherStream(data))
ps.resume()
})
```
`PauseStream` will buffer whenever paused.
it will buffer when yau have called `pause` manually.
but also when it's downstream `dest.write()===false`.
it will attempt to drain the buffer when you call resume
or the downstream emits `'drain'`
`PauseStream` is tested using [stream-spec](https://github.com/dominictarr/stream-spec)
and [stream-tester](https://github.com/dominictarr/stream-tester)
This is now the default case of
[through](https://github.com/dominictarr/through)
https://github.com/dominictarr/pause-stream/commit/4a6fe3dc2c11091b1efbfde912e0473719ed9cc0

View File

@@ -0,0 +1,17 @@
var spec = require('stream-spec')
var tester = require('stream-tester')
var ps = require('..')()
spec(ps)
.through({strict: false})
.validateOnExit()
var master = tester.createConsistent
tester.createRandomStream(1000) //1k random numbers
.pipe(master = tester.createConsistentStream())
.pipe(tester.createUnpauseStream())
.pipe(ps)
.pipe(tester.createPauseStream())
.pipe(master.createSlave())

View File

@@ -0,0 +1,33 @@
var pause = require('..')
var assert = require('assert')
var ps = pause()
var read = [], ended = false
ps.on('data', function (i) {
read.push(i)
})
ps.on('end', function () {
ended = true
})
assert.deepEqual(read, [])
ps.write(0)
ps.write(1)
ps.write(2)
assert.deepEqual(read, [0, 1, 2])
ps.pause()
assert.deepEqual(read, [0, 1, 2])
ps.end()
assert.equal(ended, false)
ps.resume()
assert.equal(ended, true)

View File

@@ -0,0 +1,22 @@
Copyright (c) 2011 Dominic Tarr
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,26 @@
var inspect = require('util').inspect
var es = require('event-stream') //load event-stream
var split = require('../')
if(!module.parent) {
es.pipe( //pipe joins streams together
process.openStdin(), //open stdin
split(), //split stream to break on newlines
es.map(function (data, callback) {//turn this async function into a stream
var j
try {
j = JSON.parse(data) //try to parse input into json
} catch (err) {
return callback(null, data) //if it fails just pass it anyway
}
callback(null, inspect(j)) //render it nicely
}),
process.stdout // pipe it to stdout !
)
}
// run this
//
// curl -sS registry.npmjs.org/event-stream | node pretty.js
//

View File

@@ -0,0 +1,59 @@
//filter will reemit the data if cb(err,pass) pass is truthy
// reduce is more tricky
// maybe we want to group the reductions or emit progress updates occasionally
// the most basic reduce just emits one 'data' event after it has recieved 'end'
var through = require('through')
var Decoder = require('string_decoder').StringDecoder
module.exports = split
//TODO pass in a function to map across the lines.
function split (matcher, mapper) {
var decoder = new Decoder()
var soFar = ''
if('function' === typeof matcher)
mapper = matcher, matcher = null
if (!matcher)
matcher = /\r?\n/
function emit(stream, piece) {
if(mapper) {
try {
piece = mapper(piece)
}
catch (err) {
return stream.emit('error', err)
}
if('undefined' !== typeof piece)
stream.queue(piece)
}
else
stream.queue(piece)
}
function next (stream, buffer) {
var pieces = (soFar + buffer).split(matcher)
soFar = pieces.pop()
for (var i = 0; i < pieces.length; i++) {
var piece = pieces[i]
emit(stream, piece)
}
}
return through(function (b) {
next(this, decoder.write(b))
},
function () {
if(decoder.end)
next(this, decoder.end())
if(soFar != null)
emit(this, soFar)
this.queue(null)
})
}

View File

@@ -0,0 +1,56 @@
{
"name": "split",
"version": "0.2.10",
"description": "split a Text Stream into a Line Stream",
"homepage": "http://github.com/dominictarr/split",
"repository": {
"type": "git",
"url": "git://github.com/dominictarr/split.git"
},
"dependencies": {
"through": "2"
},
"devDependencies": {
"asynct": "*",
"it-is": "1",
"ubelt": "~2.9",
"stream-spec": "~0.2",
"event-stream": "~3.0.2"
},
"scripts": {
"test": "asynct test/"
},
"author": {
"name": "Dominic Tarr",
"email": "dominic.tarr@gmail.com",
"url": "http://bit.ly/dominictarr"
},
"optionalDependencies": {},
"engines": {
"node": "*"
},
"bugs": {
"url": "https://github.com/dominictarr/split/issues"
},
"_id": "split@0.2.10",
"dist": {
"shasum": "67097c601d697ce1368f418f06cd201cf0521a57",
"tarball": "http://registry.npmjs.org/split/-/split-0.2.10.tgz"
},
"_from": "split@>=0.2.0 <0.3.0",
"_npmVersion": "1.3.6",
"_npmUser": {
"name": "dominictarr",
"email": "dominic.tarr@gmail.com"
},
"maintainers": [
{
"name": "dominictarr",
"email": "dominic.tarr@gmail.com"
}
],
"directories": {},
"_shasum": "67097c601d697ce1368f418f06cd201cf0521a57",
"_resolved": "https://registry.npmjs.org/split/-/split-0.2.10.tgz",
"readme": "ERROR: No README data found!"
}

View File

@@ -0,0 +1,39 @@
# Split (matcher)
[![build status](https://secure.travis-ci.org/dominictarr/split.png)](http://travis-ci.org/dominictarr/split)
Break up a stream and reassemble it so that each line is a chunk. matcher may be a `String`, or a `RegExp`
Example, read every line in a file ...
``` js
fs.createReadStream(file)
.pipe(split())
.on('data', function (line) {
//each chunk now is a seperate line!
})
```
`split` takes the same arguments as `string.split` except it defaults to '/\r?\n/' instead of ',', and the optional `limit` paremeter is ignored.
[String#split](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split)
# NDJ - Newline Delimited Json
`split` accepts a function which transforms each line.
``` js
fs.createReadStream(file)
.pipe(split(JSON.parse))
.on('data', function (obj) {
//each chunk now is a a js object
})
.on('error', function (err) {
//syntax errors will land here
//note, this ends the stream.
})
```
# License
MIT

View File

@@ -0,0 +1,34 @@
var it = require('it-is').style('colour')
, split = require('..')
exports ['split data with partitioned unicode character'] = function (test) {
var s = split(/,/g)
, caughtError = false
, rows = []
s.on('error', function (err) {
caughtError = true
})
s.on('data', function (row) { rows.push(row) })
var x = 'テスト試験今日とても,よい天気で'
unicodeData = new Buffer(x);
// partition of 日
piece1 = unicodeData.slice(0, 20);
piece2 = unicodeData.slice(20, unicodeData.length);
s.write(piece1);
s.write(piece2);
s.end()
it(caughtError).equal(false)
it(rows).deepEqual(['テスト試験今日とても', 'よい天気で']);
it(rows).deepEqual(x.split(','))
test.done()
}

View File

@@ -0,0 +1,85 @@
var es = require('event-stream')
, it = require('it-is').style('colour')
, d = require('ubelt')
, split = require('..')
, join = require('path').join
, fs = require('fs')
, Stream = require('stream').Stream
, spec = require('stream-spec')
exports ['split() works like String#split'] = function (test) {
var readme = join(__filename)
, expected = fs.readFileSync(readme, 'utf-8').split('\n')
, cs = split()
, actual = []
, ended = false
, x = spec(cs).through()
var a = new Stream ()
a.write = function (l) {
actual.push(l.trim())
}
a.end = function () {
ended = true
expected.forEach(function (v,k) {
//String.split will append an empty string ''
//if the string ends in a split pattern.
//es.split doesn't which was breaking this test.
//clearly, appending the empty string is correct.
//tests are passing though. which is the current job.
if(v)
it(actual[k]).like(v)
})
//give the stream time to close
process.nextTick(function () {
test.done()
x.validate()
})
}
a.writable = true
fs.createReadStream(readme, {flags: 'r'}).pipe(cs)
cs.pipe(a)
}
exports ['split() takes mapper function'] = function (test) {
var readme = join(__filename)
, expected = fs.readFileSync(readme, 'utf-8').split('\n')
, cs = split(function (line) { return line.toUpperCase() })
, actual = []
, ended = false
, x = spec(cs).through()
var a = new Stream ()
a.write = function (l) {
actual.push(l.trim())
}
a.end = function () {
ended = true
expected.forEach(function (v,k) {
//String.split will append an empty string ''
//if the string ends in a split pattern.
//es.split doesn't which was breaking this test.
//clearly, appending the empty string is correct.
//tests are passing though. which is the current job.
if(v)
it(actual[k]).equal(v.trim().toUpperCase())
})
//give the stream time to close
process.nextTick(function () {
test.done()
x.validate()
})
}
a.writable = true
fs.createReadStream(readme, {flags: 'r'}).pipe(cs)
cs.pipe(a)
}

View File

@@ -0,0 +1,51 @@
var it = require('it-is').style('colour')
, split = require('..')
exports ['emit mapper exceptions as error events'] = function (test) {
var s = split(JSON.parse)
, caughtError = false
, rows = []
s.on('error', function (err) {
caughtError = true
})
s.on('data', function (row) { rows.push(row) })
s.write('{"a":1}\n{"')
it(caughtError).equal(false)
it(rows).deepEqual([ { a: 1 } ])
s.write('b":2}\n{"c":}\n')
it(caughtError).equal(true)
it(rows).deepEqual([ { a: 1 }, { b: 2 } ])
s.end()
test.done()
}
exports ['mapper error events on trailing chunks'] = function (test) {
var s = split(JSON.parse)
, caughtError = false
, rows = []
s.on('error', function (err) {
caughtError = true
})
s.on('data', function (row) { rows.push(row) })
s.write('{"a":1}\n{"')
it(caughtError).equal(false)
it(rows).deepEqual([ { a: 1 } ])
s.write('b":2}\n{"c":}')
it(caughtError).equal(false)
it(rows).deepEqual([ { a: 1 }, { b: 2 } ])
s.end()
it(caughtError).equal(true)
it(rows).deepEqual([ { a: 1 }, { b: 2 } ])
test.done()
}

View File

@@ -0,0 +1,22 @@
Copyright (c) 2012 'Dominic Tarr'
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,29 @@
# stream-combiner
<img src=https://secure.travis-ci.org/dominictarr/stream-combiner.png?branch=master>
## Combine (stream1,...,streamN)
Turn a pipeline into a single stream. `pipeline` returns a stream that writes to the first stream
and reads from the last stream.
Listening for 'error' will recieve errors from all streams inside the pipe.
``` js
var Combine = require('stream-combiner')
var es = require('event-stream')
Combine( //connect streams together with `pipe`
process.openStdin(), //open stdin
es.split(), //split stream to break on newlines
es.map(function (data, callback) {//turn this async function into a stream
callback(null
, inspect(JSON.parse(data))) //render it nicely
}),
process.stdout // pipe it to stdout !
)
```
## License
MIT

View File

@@ -0,0 +1,39 @@
var duplexer = require('duplexer')
module.exports = function () {
var streams = [].slice.call(arguments)
, first = streams[0]
, last = streams[streams.length - 1]
, thepipe = duplexer(first, last)
if(streams.length == 1)
return streams[0]
else if (!streams.length)
throw new Error('connect called with empty args')
//pipe all the streams together
function recurse (streams) {
if(streams.length < 2)
return
streams[0].pipe(streams[1])
recurse(streams.slice(1))
}
recurse(streams)
function onerror () {
var args = [].slice.call(arguments)
args.unshift('error')
thepipe.emit.apply(thepipe, args)
}
//es.duplex already reemits the error from the first and last stream.
//add a listener for the inner streams in the pipeline.
for(var i = 1; i < streams.length - 1; i ++)
streams[i].on('error', onerror)
return thepipe
}

View File

@@ -0,0 +1,50 @@
{
"name": "stream-combiner",
"version": "0.0.4",
"homepage": "https://github.com/dominictarr/stream-combiner",
"repository": {
"type": "git",
"url": "git://github.com/dominictarr/stream-combiner.git"
},
"dependencies": {
"duplexer": "~0.1.1"
},
"devDependencies": {
"tape": "~2.3.0",
"event-stream": "~3.0.7"
},
"scripts": {
"test": "set -e; for t in test/*.js; do node $t; done"
},
"author": {
"name": "'Dominic Tarr'",
"email": "dominic.tarr@gmail.com",
"url": "http://dominictarr.com"
},
"license": "MIT",
"description": "<img src=https://secure.travis-ci.org/dominictarr/stream-combiner.png?branch=master>",
"bugs": {
"url": "https://github.com/dominictarr/stream-combiner/issues"
},
"_id": "stream-combiner@0.0.4",
"dist": {
"shasum": "4d5e433c185261dde623ca3f44c586bcf5c4ad14",
"tarball": "http://registry.npmjs.org/stream-combiner/-/stream-combiner-0.0.4.tgz"
},
"_from": "stream-combiner@>=0.0.4 <0.1.0",
"_npmVersion": "1.3.11",
"_npmUser": {
"name": "dominictarr",
"email": "dominic.tarr@gmail.com"
},
"maintainers": [
{
"name": "dominictarr",
"email": "dominic.tarr@gmail.com"
}
],
"directories": {},
"_shasum": "4d5e433c185261dde623ca3f44c586bcf5c4ad14",
"_resolved": "https://registry.npmjs.org/stream-combiner/-/stream-combiner-0.0.4.tgz",
"readme": "ERROR: No README data found!"
}

View File

@@ -0,0 +1,52 @@
var es = require('event-stream')
var combine = require('..')
var test = require('tape')
test('do not duplicate errors', function (test) {
var errors = 0;
var pipe = combine(
es.through(function(data) {
return this.emit('data', data);
}),
es.through(function(data) {
return this.emit('error', new Error(data));
})
)
pipe.on('error', function(err) {
errors++
test.ok(errors, 'expected error count')
process.nextTick(function () {
return test.end();
})
})
return pipe.write('meh');
})
test('3 pipe do not duplicate errors', function (test) {
var errors = 0;
var pipe = combine(
es.through(function(data) {
return this.emit('data', data);
}),
es.through(function(data) {
return this.emit('error', new Error(data));
}),
es.through()
)
pipe.on('error', function(err) {
errors++
test.ok(errors, 'expected error count')
process.nextTick(function () {
return test.end();
})
})
return pipe.write('meh');
})

View File

@@ -0,0 +1,15 @@
Apache License, Version 2.0
Copyright (c) 2011 Dominic Tarr
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,24 @@
The MIT License
Copyright (c) 2011 Dominic Tarr
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,108 @@
var Stream = require('stream')
// through
//
// a stream that does nothing but re-emit the input.
// useful for aggregating a series of changing but not ending streams into one stream)
exports = module.exports = through
through.through = through
//create a readable writable stream.
function through (write, end, opts) {
write = write || function (data) { this.queue(data) }
end = end || function () { this.queue(null) }
var ended = false, destroyed = false, buffer = [], _ended = false
var stream = new Stream()
stream.readable = stream.writable = true
stream.paused = false
// stream.autoPause = !(opts && opts.autoPause === false)
stream.autoDestroy = !(opts && opts.autoDestroy === false)
stream.write = function (data) {
write.call(this, data)
return !stream.paused
}
function drain() {
while(buffer.length && !stream.paused) {
var data = buffer.shift()
if(null === data)
return stream.emit('end')
else
stream.emit('data', data)
}
}
stream.queue = stream.push = function (data) {
// console.error(ended)
if(_ended) return stream
if(data === null) _ended = true
buffer.push(data)
drain()
return stream
}
//this will be registered as the first 'end' listener
//must call destroy next tick, to make sure we're after any
//stream piped from here.
//this is only a problem if end is not emitted synchronously.
//a nicer way to do this is to make sure this is the last listener for 'end'
stream.on('end', function () {
stream.readable = false
if(!stream.writable && stream.autoDestroy)
process.nextTick(function () {
stream.destroy()
})
})
function _end () {
stream.writable = false
end.call(stream)
if(!stream.readable && stream.autoDestroy)
stream.destroy()
}
stream.end = function (data) {
if(ended) return
ended = true
if(arguments.length) stream.write(data)
_end() // will emit or queue
return stream
}
stream.destroy = function () {
if(destroyed) return
destroyed = true
ended = true
buffer.length = 0
stream.writable = stream.readable = false
stream.emit('close')
return stream
}
stream.pause = function () {
if(stream.paused) return
stream.paused = true
return stream
}
stream.resume = function () {
if(stream.paused) {
stream.paused = false
stream.emit('resume')
}
drain()
//may have become paused again,
//as drain emits 'data'.
if(!stream.paused)
stream.emit('drain')
return stream
}
return stream
}

View File

@@ -0,0 +1,66 @@
{
"name": "through",
"version": "2.3.8",
"description": "simplified stream construction",
"main": "index.js",
"scripts": {
"test": "set -e; for t in test/*.js; do node $t; done"
},
"devDependencies": {
"stream-spec": "~0.3.5",
"tape": "~2.3.2",
"from": "~0.1.3"
},
"keywords": [
"stream",
"streams",
"user-streams",
"pipe"
],
"author": {
"name": "Dominic Tarr",
"email": "dominic.tarr@gmail.com",
"url": "dominictarr.com"
},
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/dominictarr/through.git"
},
"homepage": "https://github.com/dominictarr/through",
"testling": {
"browsers": [
"ie/8..latest",
"ff/15..latest",
"chrome/20..latest",
"safari/5.1..latest"
],
"files": "test/*.js"
},
"gitHead": "2c5a6f9a0cc54da759b6e10964f2081c358e49dc",
"bugs": {
"url": "https://github.com/dominictarr/through/issues"
},
"_id": "through@2.3.8",
"_shasum": "0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5",
"_from": "through@>=2.3.1 <2.4.0",
"_npmVersion": "2.12.0",
"_nodeVersion": "2.3.1",
"_npmUser": {
"name": "dominictarr",
"email": "dominic.tarr@gmail.com"
},
"maintainers": [
{
"name": "dominictarr",
"email": "dominic.tarr@gmail.com"
}
],
"dist": {
"shasum": "0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5",
"tarball": "http://registry.npmjs.org/through/-/through-2.3.8.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz",
"readme": "ERROR: No README data found!"
}

View File

@@ -0,0 +1,64 @@
#through
[![build status](https://secure.travis-ci.org/dominictarr/through.png)](http://travis-ci.org/dominictarr/through)
[![testling badge](https://ci.testling.com/dominictarr/through.png)](https://ci.testling.com/dominictarr/through)
Easy way to create a `Stream` that is both `readable` and `writable`.
* Pass in optional `write` and `end` methods.
* `through` takes care of pause/resume logic if you use `this.queue(data)` instead of `this.emit('data', data)`.
* Use `this.pause()` and `this.resume()` to manage flow.
* Check `this.paused` to see current flow state. (`write` always returns `!this.paused`).
This function is the basis for most of the synchronous streams in
[event-stream](http://github.com/dominictarr/event-stream).
``` js
var through = require('through')
through(function write(data) {
this.queue(data) //data *must* not be null
},
function end () { //optional
this.queue(null)
})
```
Or, can also be used _without_ buffering on pause, use `this.emit('data', data)`,
and this.emit('end')
``` js
var through = require('through')
through(function write(data) {
this.emit('data', data)
//this.pause()
},
function end () { //optional
this.emit('end')
})
```
## Extended Options
You will probably not need these 99% of the time.
### autoDestroy=false
By default, `through` emits close when the writable
and readable side of the stream has ended.
If that is not desired, set `autoDestroy=false`.
``` js
var through = require('through')
//like this
var ts = through(write, end, {autoDestroy: false})
//or like this
var ts = through(write, end)
ts.autoDestroy = false
```
## License
MIT / Apache2

View File

@@ -0,0 +1,28 @@
var from = require('from')
var through = require('../')
var tape = require('tape')
tape('simple async example', function (t) {
var n = 0, expected = [1,2,3,4,5], actual = []
from(expected)
.pipe(through(function(data) {
this.pause()
n ++
setTimeout(function(){
console.log('pushing data', data)
this.push(data)
this.resume()
}.bind(this), 300)
})).pipe(through(function(data) {
console.log('pushing data second time', data);
this.push(data)
})).on('data', function (d) {
actual.push(d)
}).on('end', function() {
t.deepEqual(actual, expected)
t.end()
})
})

View File

@@ -0,0 +1,30 @@
var test = require('tape')
var through = require('../')
// must emit end before close.
test('end before close', function (assert) {
var ts = through()
ts.autoDestroy = false
var ended = false, closed = false
ts.on('end', function () {
assert.ok(!closed)
ended = true
})
ts.on('close', function () {
assert.ok(ended)
closed = true
})
ts.write(1)
ts.write(2)
ts.write(3)
ts.end()
assert.ok(ended)
assert.notOk(closed)
ts.destroy()
assert.ok(closed)
assert.end()
})

View File

@@ -0,0 +1,71 @@
var test = require('tape')
var through = require('../')
// must emit end before close.
test('buffering', function(assert) {
var ts = through(function (data) {
this.queue(data)
}, function () {
this.queue(null)
})
var ended = false, actual = []
ts.on('data', actual.push.bind(actual))
ts.on('end', function () {
ended = true
})
ts.write(1)
ts.write(2)
ts.write(3)
assert.deepEqual(actual, [1, 2, 3])
ts.pause()
ts.write(4)
ts.write(5)
ts.write(6)
assert.deepEqual(actual, [1, 2, 3])
ts.resume()
assert.deepEqual(actual, [1, 2, 3, 4, 5, 6])
ts.pause()
ts.end()
assert.ok(!ended)
ts.resume()
assert.ok(ended)
assert.end()
})
test('buffering has data in queue, when ends', function (assert) {
/*
* If stream ends while paused with data in the queue,
* stream should still emit end after all data is written
* on resume.
*/
var ts = through(function (data) {
this.queue(data)
}, function () {
this.queue(null)
})
var ended = false, actual = []
ts.on('data', actual.push.bind(actual))
ts.on('end', function () {
ended = true
})
ts.pause()
ts.write(1)
ts.write(2)
ts.write(3)
ts.end()
assert.deepEqual(actual, [], 'no data written yet, still paused')
assert.ok(!ended, 'end not emitted yet, still paused')
ts.resume()
assert.deepEqual(actual, [1, 2, 3], 'resumed, all data should be delivered')
assert.ok(ended, 'end should be emitted once all data was delivered')
assert.end();
})

View File

@@ -0,0 +1,45 @@
var test = require('tape')
var through = require('../')
// must emit end before close.
test('end before close', function (assert) {
var ts = through()
var ended = false, closed = false
ts.on('end', function () {
assert.ok(!closed)
ended = true
})
ts.on('close', function () {
assert.ok(ended)
closed = true
})
ts.write(1)
ts.write(2)
ts.write(3)
ts.end()
assert.ok(ended)
assert.ok(closed)
assert.end()
})
test('end only once', function (t) {
var ts = through()
var ended = false, closed = false
ts.on('end', function () {
t.equal(ended, false)
ended = true
})
ts.queue(null)
ts.queue(null)
ts.queue(null)
ts.resume()
t.end()
})

View File

@@ -0,0 +1,133 @@
var test = require('tape')
var spec = require('stream-spec')
var through = require('../')
/*
I'm using these two functions, and not streams and pipe
so there is less to break. if this test fails it must be
the implementation of _through_
*/
function write(array, stream) {
array = array.slice()
function next() {
while(array.length)
if(stream.write(array.shift()) === false)
return stream.once('drain', next)
stream.end()
}
next()
}
function read(stream, callback) {
var actual = []
stream.on('data', function (data) {
actual.push(data)
})
stream.once('end', function () {
callback(null, actual)
})
stream.once('error', function (err) {
callback(err)
})
}
test('simple defaults', function(assert) {
var l = 1000
, expected = []
while(l--) expected.push(l * Math.random())
var t = through()
var s = spec(t).through().pausable()
read(t, function (err, actual) {
assert.ifError(err)
assert.deepEqual(actual, expected)
assert.end()
})
t.on('close', s.validate)
write(expected, t)
});
test('simple functions', function(assert) {
var l = 1000
, expected = []
while(l--) expected.push(l * Math.random())
var t = through(function (data) {
this.emit('data', data*2)
})
var s = spec(t).through().pausable()
read(t, function (err, actual) {
assert.ifError(err)
assert.deepEqual(actual, expected.map(function (data) {
return data*2
}))
assert.end()
})
t.on('close', s.validate)
write(expected, t)
})
test('pauses', function(assert) {
var l = 1000
, expected = []
while(l--) expected.push(l) //Math.random())
var t = through()
var s = spec(t)
.through()
.pausable()
t.on('data', function () {
if(Math.random() > 0.1) return
t.pause()
process.nextTick(function () {
t.resume()
})
})
read(t, function (err, actual) {
assert.ifError(err)
assert.deepEqual(actual, expected)
})
t.on('close', function () {
s.validate()
assert.end()
})
write(expected, t)
})
test('does not soft-end on `undefined`', function(assert) {
var stream = through()
, count = 0
stream.on('data', function (data) {
count++
})
stream.write(undefined)
stream.write(undefined)
assert.equal(count, 2)
assert.end()
})

View File

@@ -0,0 +1,79 @@
{
"name": "event-stream",
"version": "3.1.7",
"description": "construct pipes of streams of events",
"homepage": "http://github.com/dominictarr/event-stream",
"repository": {
"type": "git",
"url": "git://github.com/dominictarr/event-stream.git"
},
"dependencies": {
"through": "~2.3.1",
"duplexer": "~0.1.1",
"from": "~0",
"map-stream": "~0.1.0",
"pause-stream": "0.0.11",
"split": "0.2",
"stream-combiner": "~0.0.4"
},
"devDependencies": {
"asynct": "*",
"it-is": "1",
"ubelt": "~3.2.2",
"stream-spec": "~0.3.5",
"tape": "~2.3.0"
},
"scripts": {
"test": "asynct test/",
"test_tap": "set -e; for t in test/*.js; do node $t; done"
},
"testling": {
"files": "test/*.js",
"browsers": {
"ie": [
8,
9
],
"firefox": [
13
],
"chrome": [
20
],
"safari": [
5.1
],
"opera": [
12
]
}
},
"author": {
"name": "Dominic Tarr",
"email": "dominic.tarr@gmail.com",
"url": "http://bit.ly/dominictarr"
},
"bugs": {
"url": "https://github.com/dominictarr/event-stream/issues"
},
"_id": "event-stream@3.1.7",
"_shasum": "b4c540012d0fe1498420f3d8946008db6393c37a",
"_from": "event-stream@>=3.1.5 <3.2.0",
"_npmVersion": "1.4.9",
"_npmUser": {
"name": "dominictarr",
"email": "dominic.tarr@gmail.com"
},
"maintainers": [
{
"name": "dominictarr",
"email": "dominic.tarr@gmail.com"
}
],
"dist": {
"shasum": "b4c540012d0fe1498420f3d8946008db6393c37a",
"tarball": "http://registry.npmjs.org/event-stream/-/event-stream-3.1.7.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/event-stream/-/event-stream-3.1.7.tgz"
}

View File

@@ -0,0 +1,298 @@
# EventStream
<img src=https://secure.travis-ci.org/dominictarr/event-stream.png?branch=master>
[![browser status](http://ci.testling.com/dominictarr/event-stream.png)]
(http://ci.testling.com/dominictarr/event-stream)
[Streams](http://nodejs.org/api/stream.html "Stream") are node's best and most misunderstood idea, and
_<em>EventStream</em>_ is a toolkit to make creating and working with streams <em>easy</em>.
Normally, streams are only used for IO,
but in event stream we send all kinds of objects down the pipe.
If your application's <em>input</em> and <em>output</em> are streams,
shouldn't the <em>throughput</em> be a stream too?
The *EventStream* functions resemble the array functions,
because Streams are like Arrays, but laid out in time, rather than in memory.
<em>All the `event-stream` functions return instances of `Stream`</em>.
`event-stream` creates
[0.8 streams](https://github.com/joyent/node/blob/v0.8/doc/api/stream.markdown)
, which are compatible with [0.10 streams](http://nodejs.org/api/stream.html "Stream")
>NOTE: I shall use the term <em>"through stream"</em> to refer to a stream that is writable <em>and</em> readable.
###[simple example](https://github.com/dominictarr/event-stream/blob/master/examples/pretty.js):
``` js
//pretty.js
if(!module.parent) {
var es = require('event-stream')
var inspect = require('util').inspect
process.stdin //connect streams together with `pipe`
.pipe(es.split()) //split stream to break on newlines
.pipe(es.map(function (data, cb) { //turn this async function into a stream
cb(null
, inspect(JSON.parse(data))) //render it nicely
}))
.pipe(process.stdout) // pipe it to stdout !
}
```
run it ...
``` bash
curl -sS registry.npmjs.org/event-stream | node pretty.js
```
[node Stream documentation](http://nodejs.org/api/stream.html)
## through (write?, end?)
Re-emits data synchronously. Easy way to create synchronous through streams.
Pass in optional `write` and `end` methods. They will be called in the
context of the stream. Use `this.pause()` and `this.resume()` to manage flow.
Check `this.paused` to see current flow state. (write always returns `!this.paused`)
this function is the basis for most of the synchronous streams in `event-stream`.
``` js
es.through(function write(data) {
this.emit('data', data)
//this.pause()
},
function end () { //optional
this.emit('end')
})
```
##map (asyncFunction)
Create a through stream from an asynchronous function.
``` js
var es = require('event-stream')
es.map(function (data, callback) {
//transform data
// ...
callback(null, data)
})
```
Each map MUST call the callback. It may callback with data, with an error or with no arguments,
* `callback()` drop this data.
this makes the map work like `filter`,
note:`callback(null,null)` is not the same, and will emit `null`
* `callback(null, newData)` turn data into newData
* `callback(error)` emit an error for this item.
>Note: if a callback is not called, `map` will think that it is still being processed,
>every call must be answered or the stream will not know when to end.
>
>Also, if the callback is called more than once, every call but the first will be ignored.
## mapSync (syncFunction)
Same as `map`, but the callback is called synchronously. Based on `es.through`
## split (matcher)
Break up a stream and reassemble it so that each line is a chunk. matcher may be a `String`, or a `RegExp`
Example, read every line in a file ...
``` js
fs.createReadStream(file, {flags: 'r'})
.pipe(es.split())
.pipe(es.map(function (line, cb) {
//do something with the line
cb(null, line)
}))
```
`split` takes the same arguments as `string.split` except it defaults to '\n' instead of ',', and the optional `limit` parameter is ignored.
[String#split](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split)
## join (separator)
Create a through stream that emits `separator` between each chunk, just like Array#join.
(for legacy reasons, if you pass a callback instead of a string, join is a synonym for `es.wait`)
## merge (stream1,...,streamN)
> concat → merge
Merges streams into one and returns it.
Incoming data will be emitted as soon it comes into - no ordering will be applied (for example: `data1 data1 data2 data1 data2` - where `data1` and `data2` is data from two streams).
Counts how many streams was passed to it and emits end only when all streams emitted end.
```js
es.merge(
process.stdout,
process.stderr
).pipe(fs.createWriteStream('output.log'));
```
## replace (from, to)
Replace all occurrences of `from` with `to`. `from` may be a `String` or a `RegExp`.
Works just like `string.split(from).join(to)`, but streaming.
## parse
Convenience function for parsing JSON chunks. For newline separated JSON,
use with `es.split`
``` js
fs.createReadStream(filename)
.pipe(es.split()) //defaults to lines.
.pipe(es.parse())
```
## stringify
convert javascript objects into lines of text. The text will have whitespace escaped and have a `\n` appended, so it will be compatible with `es.parse`
``` js
objectStream
.pipe(es.stringify())
.pipe(fs.createWriteStream(filename))
```
##readable (asyncFunction)
create a readable stream (that respects pause) from an async function.
while the stream is not paused,
the function will be polled with `(count, callback)`,
and `this` will be the readable stream.
``` js
es.readable(function (count, callback) {
if(streamHasEnded)
return this.emit('end')
//...
this.emit('data', data) //use this way to emit multiple chunks per call.
callback() // you MUST always call the callback eventually.
// the function will not be called again until you do this.
})
```
you can also pass the data and the error to the callback.
you may only call the callback once.
calling the same callback more than once will have no effect.
##readArray (array)
Create a readable stream from an Array.
Just emit each item as a data event, respecting `pause` and `resume`.
``` js
var es = require('event-stream')
, reader = es.readArray([1,2,3])
reader.pipe(...)
```
## writeArray (callback)
create a writeable stream from a callback,
all `data` events are stored in an array, which is passed to the callback when the stream ends.
``` js
var es = require('event-stream')
, reader = es.readArray([1, 2, 3])
, writer = es.writeArray(function (err, array){
//array deepEqual [1, 2, 3]
})
reader.pipe(writer)
```
## pause ()
A stream that buffers all chunks when paused.
``` js
var ps = es.pause()
ps.pause() //buffer the stream, also do not allow 'end'
ps.resume() //allow chunks through
```
## duplex (writeStream, readStream)
Takes a writable stream and a readable stream and makes them appear as a readable writable stream.
It is assumed that the two streams are connected to each other in some way.
(This is used by `pipeline` and `child`.)
``` js
var grep = cp.exec('grep Stream')
es.duplex(grep.stdin, grep.stdout)
```
## child (child_process)
Create a through stream from a child process ...
``` js
var cp = require('child_process')
es.child(cp.exec('grep Stream')) // a through stream
```
## wait (callback)
waits for stream to emit 'end'.
joins chunks of a stream into a single string.
takes an optional callback, which will be passed the
complete string when it receives the 'end' event.
also, emits a single 'data' event.
``` js
readStream.pipe(es.wait(function (err, text) {
// have complete text here.
}))
```
# Other Stream Modules
These modules are not included as a part of *EventStream* but may be
useful when working with streams.
## [reduce (syncFunction, initial)](https://github.com/parshap/node-stream-reduce)
Like `Array.prototype.reduce` but for streams. Given a sync reduce
function and an initial value it will return a through stream that emits
a single data event with the reduced value once the input stream ends.
``` js
var reduce = require("stream-reduce");
process.stdin.pipe(reduce(function(acc, data) {
return acc + data.length;
}, 0)).on("data", function(length) {
console.log("stdin size:", length);
});
```

View File

@@ -0,0 +1,86 @@
var es = require('../')
, it = require('it-is').style('colour')
, d = require('ubelt')
function makeExamplePipe() {
return es.connect(
es.map(function (data, callback) {
callback(null, data * 2)
}),
es.map(function (data, callback) {
d.delay(callback)(null, data)
}),
es.map(function (data, callback) {
callback(null, data + 2)
}))
}
exports['simple pipe'] = function (test) {
var pipe = makeExamplePipe()
pipe.on('data', function (data) {
it(data).equal(18)
test.done()
})
pipe.write(8)
}
exports['read array then map'] = function (test) {
var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100
, first = es.readArray(readThis)
, read = []
, pipe =
es.connect(
first,
es.map(function (data, callback) {
callback(null, {data: data})
}),
es.map(function (data, callback) {
callback(null, {data: data})
}),
es.writeArray(function (err, array) {
it(array).deepEqual(d.map(readThis, function (data) {
return {data: {data: data}}
}))
test.done()
})
)
}
exports ['connect returns a stream'] = function (test) {
var rw =
es.connect(
es.map(function (data, callback) {
callback(null, data * 2)
}),
es.map(function (data, callback) {
callback(null, data * 5)
})
)
it(rw).has({readable: true, writable: true})
var array = [190, 24, 6, 7, 40, 57, 4, 6]
, _array = []
, c =
es.connect(
es.readArray(array),
rw,
es.log('after rw:'),
es.writeArray(function (err, _array) {
it(_array).deepEqual(array.map(function (e) { return e * 10 }))
test.done()
})
)
}
require('./helper')(module)

View File

@@ -0,0 +1,12 @@
var tape = require('tape')
module.exports = function (m) {
if(m.parent) return
for(var name in m.exports) {
tape(name, function (t) {
console.log('start', name)
t.done = t.end
m.exports[name](t)
})
}
}

View File

@@ -0,0 +1,21 @@
var es = require('../')
, it = require('it-is').style('colour')
, d = require('ubelt')
exports.merge = function (t) {
var odd = d.map(1, 3, 100, d.id) //array of multiples of 3 < 100
var even = d.map(2, 4, 100, d.id) //array of multiples of 3 < 100
var r1 = es.readArray(even)
var r2 = es.readArray(odd)
var writer = es.writeArray(function (err, array){
if(err) throw err //unpossible
it(array.sort()).deepEqual(even.concat(odd).sort())
t.done()
})
es.merge(r1, r2).pipe(writer)
}
require('./helper')(module)

View File

@@ -0,0 +1,39 @@
var es = require('../')
, it = require('it-is')
, d = require('ubelt')
exports ['gate buffers when shut'] = function (test) {
var hundy = d.map(1,100, d.id)
, gate = es.pause()
, ten = 10
es.connect(
es.readArray(hundy),
es.log('after readArray'),
gate,
//es.log('after gate'),
es.map(function (num, next) {
//stick a map in here to check that gate never emits when open
it(gate.paused).equal(false)
console.log('data', num)
if(!--ten) {
console.log('PAUSE')
gate.pause()//.resume()
d.delay(gate.resume.bind(gate), 10)()
ten = 10
}
next(null, num)
}),
es.writeArray(function (err, array) { //just realized that I should remove the error param. errors will be emitted
console.log('eonuhoenuoecbulc')
it(array).deepEqual(hundy)
test.done()
})
)
gate.resume()
}
require('./helper')(module)

View File

@@ -0,0 +1,52 @@
var es = require('..')
exports['do not duplicate errors'] = function (test) {
var errors = 0;
var pipe = es.pipeline(
es.through(function(data) {
return this.emit('data', data);
}),
es.through(function(data) {
return this.emit('error', new Error(data));
})
)
pipe.on('error', function(err) {
errors++
console.log('error count', errors)
process.nextTick(function () {
return test.done();
})
})
return pipe.write('meh');
}
exports['3 pipe do not duplicate errors'] = function (test) {
var errors = 0;
var pipe = es.pipeline(
es.through(function(data) {
return this.emit('data', data);
}),
es.through(function(data) {
return this.emit('error', new Error(data));
}),
es.through()
)
pipe.on('error', function(err) {
errors++
console.log('error count', errors)
process.nextTick(function () {
return test.done();
})
})
return pipe.write('meh');
}
require('./helper')(module)

View File

@@ -0,0 +1,89 @@
var es = require('../')
, it = require('it-is').style('colour')
, d = require('ubelt')
function readStream(stream, pauseAt, done) {
if(!done) done = pauseAt, pauseAt = -1
var array = []
stream.on('data', function (data) {
array.push(data)
if(!--pauseAt )
stream.pause(), done(null, array)
})
stream.on('error', done)
stream.on('end', function (data) {
done(null, array)
})
}
exports ['read an array'] = function (test) {
var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100
var reader = es.readArray(readThis)
var writer = es.writeArray(function (err, array){
if(err) throw err //unpossible
it(array).deepEqual(readThis)
test.done()
})
reader.pipe(writer)
}
exports ['read an array and pause it.'] = function (test) {
var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100
var reader = es.readArray(readThis)
readStream(reader, 10, function (err, data) {
if(err) throw err
it(data).deepEqual([3, 6, 9, 12, 15, 18, 21, 24, 27, 30])
readStream(reader, 10, function (err, data) {
it(data).deepEqual([33, 36, 39, 42, 45, 48, 51, 54, 57, 60])
test.done()
})
reader.resume()
})
}
exports ['reader is readable, but not writeable'] = function (test) {
var reader = es.readArray([1])
it(reader).has({
readable: true,
writable: false
})
test.done()
}
exports ['read one item per tick'] = function (test) {
var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100
var drains = 0
var reader = es.readArray(readThis)
var tickMapper = es.map(function (data,callback) {
process.nextTick(function () {
callback(null, data)
})
//since tickMapper is returning false
//pipe should pause the writer until a drain occurs
return false
})
reader.pipe(tickMapper)
readStream(tickMapper, function (err, array) {
it(array).deepEqual(readThis)
it(array.length).deepEqual(readThis.length)
it(drains).equal(readThis.length)
test.done()
})
tickMapper.on('drain', function () {
drains ++
})
}
require('./helper')(module)

View File

@@ -0,0 +1,197 @@
var es = require('../')
, it = require('it-is').style('colour')
, u = require('ubelt')
exports ['read an array'] = function (test) {
console.log('readable')
return test.end()
var readThis = u.map(3, 6, 100, u.id) //array of multiples of 3 < 100
console.log('readable')
var reader =
es.readable(function (i, callback) {
if(i >= readThis.length)
return this.emit('end')
console.log('readable')
callback(null, readThis[i])
})
var writer = es.writeArray(function (err, array){
if(err) throw err
it(array).deepEqual(readThis)
test.done()
})
reader.pipe(writer)
}
exports ['read an array - async'] = function (test) {
var readThis = u.map(3, 6, 100, u.id) //array of multiples of 3 < 100
var reader =
es.readable(function (i, callback) {
if(i >= readThis.length)
return this.emit('end')
u.delay(callback)(null, readThis[i])
})
var writer = es.writeArray(function (err, array){
if(err) throw err
it(array).deepEqual(readThis)
test.done()
})
reader.pipe(writer)
}
exports ['emit data then call next() also works'] = function (test) {
var readThis = u.map(3, 6, 100, u.id) //array of multiples of 3 < 100
var reader =
es.readable(function (i, next) {
if(i >= readThis.length)
return this.emit('end')
this.emit('data', readThis[i])
next()
})
var writer = es.writeArray(function (err, array){
if(err) throw err
it(array).deepEqual(readThis)
test.done()
})
reader.pipe(writer)
}
exports ['callback emits error, then stops'] = function (test) {
var err = new Error('INTENSIONAL ERROR')
, called = 0
var reader =
es.readable(function (i, callback) {
if(called++)
return
callback(err)
})
reader.on('error', function (_err){
it(_err).deepEqual(err)
u.delay(function() {
it(called).equal(1)
test.done()
}, 50)()
})
}
exports['readable does not call read concurrently'] = function (test) {
var current = 0
var source = es.readable(function(count, cb){
current ++
if(count > 100)
return this.emit('end')
u.delay(function(){
current --
it(current).equal(0)
cb(null, {ok: true, n: count});
})();
});
var destination = es.map(function(data, cb){
//console.info(data);
cb();
});
var all = es.connect(source, destination);
destination.on('end', test.done)
}
exports ['does not raise a warning: Recursive process.nextTick detected'] = function (test) {
var readThisDelayed;
u.delay(function () {
readThisDelayed = [1, 3, 5];
})();
es.readable(function (count, callback) {
if (readThisDelayed) {
var that = this;
readThisDelayed.forEach(function (item) {
that.emit('data', item);
});
this.emit('end');
test.done();
}
callback();
});
};
//
// emitting multiple errors is not supported by stream.
//
// I do not think that this is a good idea, at least, there should be an option to pipe to
// continue on error. it makes alot ef sense, if you are using Stream like I am, to be able to emit multiple errors.
// an error might not necessarily mean the end of the stream. it depends on the error, at least.
//
// I will start a thread on the mailing list. I'd rather that than use a custom `pipe` implementation.
//
// basically, I want to be able use pipe to transform objects, and if one object is invalid,
// the next might still be good, so I should get to choose if it's gonna stop.
// re-enstate this test when this issue progresses.
//
// hmm. I could add this to es.connect by deregistering the error listener,
// but I would rather it be an option in core.
/*
exports ['emit multiple errors, with 2nd parameter (continueOnError)'] = function (test) {
var readThis = d.map(1, 100, d.id)
, errors = 0
var reader =
es.readable(function (i, callback) {
console.log(i, readThis.length)
if(i >= readThis.length)
return this.emit('end')
if(!(readThis[i] % 7))
return callback(readThis[i])
callback(null, readThis[i])
}, true)
var writer = es.writeArray(function (err, array) {
if(err) throw err
it(array).every(function (u){
it(u % 7).notEqual(0)
}).property('length', 80)
it(errors).equal(14)
test.done()
})
reader.on('error', function (u) {
errors ++
console.log(u)
if('number' !== typeof u)
throw u
it(u % 7).equal(0)
})
reader.pipe(writer)
}
*/
require('./helper')(module)

View File

@@ -0,0 +1,51 @@
var es = require('../')
, it = require('it-is').style('colour')
, d = require('ubelt')
, spec = require('stream-spec')
var next = process.nextTick
var fizzbuzz = '12F4BF78FB11F1314FB1617F19BF2223FB26F2829FB3132F34BF3738FB41F4344FB4647F49BF5253FB56F5859FB6162F64BF6768FB71F7374FB7677F79BF8283FB86F8889FB9192F94BF9798FB'
, fizz7buzz = '12F4BFseven8FB11F1314FB161sevenF19BF2223FB26F2829FB3132F34BF3seven38FB41F4344FB464sevenF49BF5253FB56F5859FB6162F64BF6seven68FBseven1Fseven3seven4FBseven6sevensevenFseven9BF8283FB86F8889FB9192F94BF9seven98FB'
exports ['fizz buzz'] = function (test) {
var readThis = d.map(1, 100, function (i) {
return (
! (i % 3 || i % 5) ? "FB" :
!(i % 3) ? "F" :
!(i % 5) ? "B" :
''+i
)
}) //array of multiples of 3 < 100
var reader = es.readArray(readThis)
var join = es.wait(function (err, string){
it(string).equal(fizzbuzz)
test.done()
})
reader.pipe(join)
}
exports ['fizz buzz replace'] = function (test) {
var split = es.split(/(1)/)
var replace = es.replace('7', 'seven')
// var x = spec(replace).through()
split
.pipe(replace)
.pipe(es.join(function (err, string) {
it(string).equal(fizz7buzz)
}))
replace.on('close', function () {
// x.validate()
test.done()
})
split.write(fizzbuzz)
split.end()
}
require('./helper')(module)

View File

@@ -0,0 +1,343 @@
'use strict';
var es = require('../')
, it = require('it-is')
, u = require('ubelt')
, spec = require('stream-spec')
, Stream = require('stream')
, from = require('from')
, through = require('through')
//REFACTOR THIS TEST TO USE es.readArray and es.writeArray
function writeArray(array, stream) {
array.forEach( function (j) {
stream.write(j)
})
stream.end()
}
function readStream(stream, done) {
var array = []
stream.on('data', function (data) {
array.push(data)
})
stream.on('error', done)
stream.on('end', function (data) {
done(null, array)
})
}
//call sink on each write,
//and complete when finished.
function pauseStream (prob, delay) {
var pauseIf = (
'number' == typeof prob
? function () {
return Math.random() < prob
}
: 'function' == typeof prob
? prob
: 0.1
)
var delayer = (
!delay
? process.nextTick
: 'number' == typeof delay
? function (next) { setTimeout(next, delay) }
: delay
)
return es.through(function (data) {
if(!this.paused && pauseIf()) {
console.log('PAUSE STREAM PAUSING')
this.pause()
var self = this
delayer(function () {
console.log('PAUSE STREAM RESUMING')
self.resume()
})
}
console.log("emit ('data', " + data + ')')
this.emit('data', data)
})
}
exports ['simple map'] = function (test) {
var input = u.map(1, 1000, function () {
return Math.random()
})
var expected = input.map(function (v) {
return v * 2
})
var pause = pauseStream(0.1)
var fs = from(input)
var ts = es.writeArray(function (err, ar) {
it(ar).deepEqual(expected)
test.done()
})
var map = es.through(function (data) {
this.emit('data', data * 2)
})
spec(map).through().validateOnExit()
spec(pause).through().validateOnExit()
fs.pipe(map).pipe(pause).pipe(ts)
}
exports ['simple map applied to a stream'] = function (test) {
var input = [1,2,3,7,5,3,1,9,0,2,4,6]
//create event stream from
var doubler = es.map(function (data, cb) {
cb(null, data * 2)
})
spec(doubler).through().validateOnExit()
//a map is only a middle man, so it is both readable and writable
it(doubler).has({
readable: true,
writable: true,
})
readStream(doubler, function (err, output) {
it(output).deepEqual(input.map(function (j) {
return j * 2
}))
// process.nextTick(x.validate)
test.done()
})
writeArray(input, doubler)
}
exports['pipe two maps together'] = function (test) {
var input = [1,2,3,7,5,3,1,9,0,2,4,6]
//create event stream from
function dd (data, cb) {
cb(null, data * 2)
}
var doubler1 = es.map(dd), doubler2 = es.map(dd)
doubler1.pipe(doubler2)
spec(doubler1).through().validateOnExit()
spec(doubler2).through().validateOnExit()
readStream(doubler2, function (err, output) {
it(output).deepEqual(input.map(function (j) {
return j * 4
}))
test.done()
})
writeArray(input, doubler1)
}
//next:
//
// test pause, resume and drian.
//
// then make a pipe joiner:
//
// plumber (evStr1, evStr2, evStr3, evStr4, evStr5)
//
// will return a single stream that write goes to the first
exports ['map will not call end until the callback'] = function (test) {
var ticker = es.map(function (data, cb) {
process.nextTick(function () {
cb(null, data * 2)
})
})
spec(ticker).through().validateOnExit()
ticker.write('x')
ticker.end()
ticker.on('end', function () {
test.done()
})
}
exports ['emit error thrown'] = function (test) {
var err = new Error('INTENSIONAL ERROR')
, mapper =
es.map(function () {
throw err
})
mapper.on('error', function (_err) {
it(_err).equal(err)
test.done()
})
// onExit(spec(mapper).basic().validate)
//need spec that says stream may error.
mapper.write('hello')
}
exports ['emit error calledback'] = function (test) {
var err = new Error('INTENSIONAL ERROR')
, mapper =
es.map(function (data, callback) {
callback(err)
})
mapper.on('error', function (_err) {
it(_err).equal(err)
test.done()
})
mapper.write('hello')
}
exports ['do not emit drain if not paused'] = function (test) {
var map = es.map(function (data, callback) {
u.delay(callback)(null, 1)
return true
})
spec(map).through().pausable().validateOnExit()
map.on('drain', function () {
it(false).ok('should not emit drain unless the stream is paused')
})
it(map.write('hello')).equal(true)
it(map.write('hello')).equal(true)
it(map.write('hello')).equal(true)
setTimeout(function () {map.end()},10)
map.on('end', test.done)
}
exports ['emits drain if paused, when all '] = function (test) {
var active = 0
var drained = false
var map = es.map(function (data, callback) {
active ++
u.delay(function () {
active --
callback(null, 1)
})()
console.log('WRITE', false)
return false
})
spec(map).through().validateOnExit()
map.on('drain', function () {
drained = true
it(active).equal(0, 'should emit drain when all maps are done')
})
it(map.write('hello')).equal(false)
it(map.write('hello')).equal(false)
it(map.write('hello')).equal(false)
process.nextTick(function () {map.end()},10)
map.on('end', function () {
console.log('end')
it(drained).ok('shoud have emitted drain before end')
test.done()
})
}
exports ['map applied to a stream with filtering'] = function (test) {
var input = [1,2,3,7,5,3,1,9,0,2,4,6]
var doubler = es.map(function (data, callback) {
if (data % 2)
callback(null, data * 2)
else
callback()
})
readStream(doubler, function (err, output) {
it(output).deepEqual(input.filter(function (j) {
return j % 2
}).map(function (j) {
return j * 2
}))
test.done()
})
spec(doubler).through().validateOnExit()
writeArray(input, doubler)
}
exports ['simple mapSync applied to a stream'] = function (test) {
var input = [1,2,3,7,5,3,1,9,0,2,4,6]
var doubler = es.mapSync(function (data) {
return data * 2
})
readStream(doubler, function (err, output) {
it(output).deepEqual(input.map(function (j) {
return j * 2
}))
test.done()
})
spec(doubler).through().validateOnExit()
writeArray(input, doubler)
}
exports ['mapSync applied to a stream with filtering'] = function (test) {
var input = [1,2,3,7,5,3,1,9,0,2,4,6]
var doubler = es.mapSync(function (data) {
if (data % 2)
return data * 2
})
readStream(doubler, function (err, output) {
it(output).deepEqual(input.filter(function (j) {
return j % 2
}).map(function (j) {
return j * 2
}))
test.done()
})
spec(doubler).through().validateOnExit()
writeArray(input, doubler)
}
require('./helper')(module)

View File

@@ -0,0 +1,86 @@
/*
assert that data is called many times
assert that end is called eventually
assert that when stream enters pause state,
on drain is emitted eventually.
*/
var es = require('..')
var it = require('it-is').style('colour')
var spec = require('stream-spec')
exports['simple stream'] = function (test) {
var stream = es.through()
var x = spec(stream).basic().pausable()
stream.write(1)
stream.write(1)
stream.pause()
stream.write(1)
stream.resume()
stream.write(1)
stream.end(2) //this will call write()
process.nextTick(function (){
x.validate()
test.done()
})
}
exports['throw on write when !writable'] = function (test) {
var stream = es.through()
var x = spec(stream).basic().pausable()
stream.write(1)
stream.write(1)
stream.end(2) //this will call write()
stream.write(1) //this will be throwing..., but the spec will catch it.
process.nextTick(function () {
x.validate()
test.done()
})
}
exports['end fast'] = function (test) {
var stream = es.through()
var x = spec(stream).basic().pausable()
stream.end() //this will call write()
process.nextTick(function () {
x.validate()
test.done()
})
}
/*
okay, that was easy enough, whats next?
say, after you call paused(), write should return false
until resume is called.
simple way to implement this:
write must return !paused
after pause() paused = true
after resume() paused = false
on resume, if !paused drain is emitted again.
after drain, !paused
there are lots of subtle ordering bugs in streams.
example, set !paused before emitting drain.
the stream api is stateful.
*/
require('./helper')(module)

View File

@@ -0,0 +1,47 @@
var es = require('../')
, it = require('it-is').style('colour')
, d = require('ubelt')
, join = require('path').join
, fs = require('fs')
, Stream = require('stream').Stream
, spec = require('stream-spec')
exports ['es.split() works like String#split'] = function (test) {
var readme = join(__filename)
, expected = fs.readFileSync(readme, 'utf-8').split('\n')
, cs = es.split()
, actual = []
, ended = false
, x = spec(cs).through()
var a = new Stream ()
a.write = function (l) {
actual.push(l.trim())
}
a.end = function () {
ended = true
expected.forEach(function (v,k) {
//String.split will append an empty string ''
//if the string ends in a split pattern.
//es.split doesn't which was breaking this test.
//clearly, appending the empty string is correct.
//tests are passing though. which is the current job.
if(v)
it(actual[k]).like(v)
})
//give the stream time to close
process.nextTick(function () {
test.done()
x.validate()
})
}
a.writable = true
fs.createReadStream(readme, {flags: 'r'}).pipe(cs)
cs.pipe(a)
}
require('./helper')(module)

View File

@@ -0,0 +1,15 @@
var es = require('../')
exports['handle buffer'] = function (t) {
es.stringify().on('data', function (d) {
t.equal(d.trim(), JSON.stringify('HELLO'))
t.end()
}).write(new Buffer('HELLO'))
}
require('./helper')(module)

View File

@@ -0,0 +1,31 @@
var es = require('../')
, it = require('it-is').style('colour')
, d = require('ubelt')
exports ['write an array'] = function (test) {
var readThis = d.map(3, 6, 100, d.id) //array of multiples of 3 < 100
var writer = es.writeArray(function (err, array){
if(err) throw err //unpossible
it(array).deepEqual(readThis)
test.done()
})
d.each(readThis, writer.write.bind(writer))
writer.end()
}
exports ['writer is writable, but not readable'] = function (test) {
var reader = es.writeArray(function () {})
it(reader).has({
readable: false,
writable: true
})
test.done()
}
require('./helper')(module)

View File

@@ -0,0 +1,21 @@
## 1.0.1 / 2013-04-02
- Fix tests
## 1.0.0 / 2012-02-28
- Add tests for the stable release
## 0.0.2 / 2012-01-11
- Add repository to package.json
## 0.0.1 / 2012-01-10
- Initial release

View File

@@ -0,0 +1,77 @@
# node.extend
A port of jQuery.extend that **actually works** on node.js
[![Build Status][travis-svg]][travis-url]
[![dependency status][deps-svg]][deps-url]
[![dev dependency status][dev-deps-svg]][dev-deps-url]
[![browser support][testling-png]][testling-url]
## Description
None of the existing ones on npm really work therefore I ported it myself.
## Usage
To install this module in your current working directory (which should already contain a package.json), run
```
npm install node.extend
```
You can additionally just list the module in your [package.json](https://npmjs.org/doc/json.html) and run npm install.
Then, require this package where you need it:
```
var extend = require('node.extend');
```
The syntax for merging two objects is as follows:
```
var destObject = extend({}, sourceObject);
// Where sourceObject is the object whose properties will be copied into another.
// NOTE: In this situation, this is not a deep merge. See below on how to handle a deep merge.
```
For information about how the clone works internally, view source in lib/extend.js or checkout the doc from [jQuery][]
### A Note About Deep Merge (avoiding pass-by-reference cloning)
In order to force a deep merge, when extending an object, you must pass boolean true as the first argument to extend:
```
var destObject = extend(true, {}, sourceObject);
// Where sourceObject is the object whose properties will be copied into another.
```
See [this article](http://www.jon-carlos.com/2013/is-javascript-call-by-value-or-call-by-reference/) for more information about the need for deep merges in JavaScript.
## Credit
- Jordan Harband [@ljharb][]
## License
Copyright 2011, John Resig
Dual licensed under the MIT or GPL Version 2 licenses.
http://jquery.org/license
[testling-png]: https://ci.testling.com/dreamerslab/node.extend.png
[testling-url]: https://ci.testling.com/dreamerslab/node.extend
[travis-svg]: https://travis-ci.org/dreamerslab/node.extend.svg
[travis-url]: https://travis-ci.org/dreamerslab/node.extend
[deps-svg]: https://david-dm.org/dreamerslab/node.extend.svg
[deps-url]: https://david-dm.org/dreamerslab/node.extend
[dev-deps-svg]: https://david-dm.org/dreamerslab/node.extend/dev-status.svg
[dev-deps-url]: https://david-dm.org/dreamerslab/node.extend#info=devDependencies
[jQuery]: http://api.jquery.com/jQuery.extend/
[@ljharb]: https://twitter.com/ljharb

View File

@@ -0,0 +1,2 @@
module.exports = require('./lib/extend');

View File

@@ -0,0 +1,82 @@
/*!
* node.extend
* Copyright 2011, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* @fileoverview
* Port of jQuery.extend that actually works on node.js
*/
var is = require('is');
function extend() {
var target = arguments[0] || {};
var i = 1;
var length = arguments.length;
var deep = false;
var options, name, src, copy, copy_is_array, clone;
// Handle a deep copy situation
if (typeof target === 'boolean') {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== 'object' && !is.fn(target)) {
target = {};
}
for (; i < length; i++) {
// Only deal with non-null/undefined values
options = arguments[i]
if (options != null) {
if (typeof options === 'string') {
options = options.split('');
}
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy) {
continue;
}
// Recurse if we're merging plain objects or arrays
if (deep && copy && (is.hash(copy) || (copy_is_array = is.array(copy)))) {
if (copy_is_array) {
copy_is_array = false;
clone = src && is.array(src) ? src : [];
} else {
clone = src && is.hash(src) ? src : {};
}
// Never move original objects, clone them
target[name] = extend(deep, clone, copy);
// Don't bring in undefined values
} else if (typeof copy !== 'undefined') {
target[name] = copy;
}
}
}
}
// Return the modified object
return target;
};
/**
* @public
*/
extend.version = '1.1.3';
/**
* Exports module.
*/
module.exports = extend;

View File

@@ -0,0 +1,100 @@
3.1.0 / 2015-09-20
==================
* [Enhancement]: `is.array`: Prefer `Array.isArray` when present
* [Fix] Deprecate `is.boolean`/`is.int` (ES3 syntax errors)
* [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG
* [Refactor] Don't use yoda conditions
* [Refactor] `is.equal` can return earlier in some cases (#16)
* [Tests] Quote "throws" (ES3 syntax error)
* [Tests] up to `io.js` `v3.3`, up to `node` `v4.1`
* [Dev Deps] add `npm run eslint`
* [Dev Deps] update `tape`, `covert`, `jscs`
3.0.1 / 2015-02-22
==================
* Version bump to resolve npm bug with v3.0.0
3.0.0 / 2015-02-21
==================
* is.empty should return true for falsy values ([#13](https://github.com/enricomarino/is/issues/13), [#14](https://github.com/enricomarino/is/issues/14))
* All grade A-supported `node`/`iojs` versions now ship with an `npm` that understands `^`.
* Test on `iojs` `v1.2` and `v1.3`, `node` `v0.12`; speed up builds; allow failures on all but two latest minor versions.
* Update `jscs`
2.2.1 / 2015-02-06
==================
* Update `tape`, `jscs`
* `toString` breaks in some browsers; using `toStr` instead.
2.2.0 / 2014-11-29
==================
* Update `tape`, `jscs`
* Add `is.symbol`
2.1.0 / 2014-10-21
==================
* Add `CHANGELOG.md`
* Add `is.hex` and `is.base64` [#12](https://github.com/enricomarino/is/issues/12)
* Update `tape`, `jscs`
* Lock `covert` to v1.0.0 [substack/covert#9](https://github.com/substack/covert/issues/9)
2.0.2 / 2014-10-05
==================
* `undefined` can be redefined in ES3 browsers.
* Update `jscs.json` and make style consistent
* Update `foreach`, `jscs`, `tape`
* Naming URLs in README
2.0.1 / 2014-09-02
==================
* Add the license to package.json
* Add license and downloads badges
* Update `jscs`
2.0.0 / 2014-08-25
==================
* Add `make release`
* Update copyright notice.
* Fix is.empty(new String())
1.1.0 / 2014-08-22
==================
* Removing redundant license
* Add a non-deprecated method for is.null
* Use a more reliable valueOf coercion for is.false/is.true
* Clean up `README.md`
* Running `npm run lint` as part of tests.
* Fixing lint errors.
* Adding `npm run lint`
* Updating `covert`
1.0.0 / 2014-08-07
==================
* Update `tape`, `covert`
* Increase code coverage
* Update `LICENSE.md`, `README.md`
0.3.0 / 2014-03-02
==================
* Update `tape`, `covert`
* Adding `npm run coverage`
* is.arguments -> is.args, because reserved words.
* "undefined" is a reserved word in ES3 browsers.
* Optimizing is.equal to return early if value and other are strictly equal.
* Fixing is.equal for objects.
* Test improvements
0.2.7 / 2013-12-26
==================
* Update `tape`, `foreach`
* is.decimal(Infinity) shouldn't be true [#11](https://github.com/enricomarino/is/issues/11)
0.2.6 / 2013-05-06
==================
* Fix lots of tests [#9](https://github.com/enricomarino/is/issues/9)
* Update tape [#8](https://github.com/enricomarino/is/issues/8)
0.2.5 / 2013-04-24
==================
* Use `tap` instead of `tape` [#7](https://github.com/enricomarino/is/issues/7)

View File

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

View File

@@ -0,0 +1,17 @@
.PHONY: verify-tag release
default: release
verify-tag:
ifndef TAG
$(error TAG is undefined)
endif
release: verify-tag
@ OLD_TAG=`git describe --abbrev=0 --tags` && \
npm run minify && \
replace "$${OLD_TAG/v/}" "$(TAG)" -- *.json README.md && \
git commit -m "v$(TAG)" *.js *.json README.md && \
git tag "v$(TAG)"

View File

@@ -0,0 +1,140 @@
# is <sup>[![Version Badge][npm-version-svg]][npm-url]</sup>
[![Build Status][travis-svg]][travis-url]
[![dependency status][deps-svg]][deps-url]
[![dev dependency status][dev-deps-svg]][dev-deps-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][npm-badge-png]][npm-url]
[![browser support][testling-png]][testling-url]
The definitive JavaScript type testing library
To be or not to be? This is the library!
## Installation
As a node.js module
```shell
$ npm install is
```
As a component
```shell
$ component install enricomarino/is
```
## API
### general
- ``is.a`` (value, type) or ``is.type`` (value, type)
- ``is.defined`` (value)
- ``is.empty`` (value)
- ``is.equal`` (value, other)
- ``is.hosted`` (value, host)
- ``is.instance`` (value, constructor)
- ``is.instanceof`` (value, constructor) - deprecated, because in ES3 browsers, "instanceof" is a reserved word
- ``is.nil`` (value)
- ``is.null`` (value) - deprecated, because in ES3 browsers, "null" is a reserved word
- ``is.undef`` (value)
- ``is.undefined`` (value) - deprecated, because in ES3 browsers, "undefined" is a reserved word
### arguments
- ``is.args`` (value)
- ``is.arguments`` (value) - deprecated, because "arguments" is a reserved word
- ``is.args.empty`` (value)
### array
- ``is.array`` (value)
- ``is.array.empty`` (value)
- ``is.arraylike`` (value)
### boolean
- ``is.bool`` (value)
- ``is.boolean`` (value) - deprecated, because in ES3 browsers, "boolean" is a reserved word
- ``is.false`` (value) - deprecated, because in ES3 browsers, "false" is a reserved word
- ``is.true`` (value) - deprecated, because in ES3 browsers, "true" is a reserved word
### date
- ``is.date`` (value)
### element
- ``is.element`` (value)
### error
- is.error (value)
### function
- ``is.fn`` (value)
- ``is.function`` (value) - deprecated, because in ES3 browsers, "function" is a reserved word
### number
- ``is.number`` (value)
- ``is.infinite`` (value)
- ``is.decimal`` (value)
- ``is.divisibleBy`` (value, n)
- ``is.integer`` (value)
- ``is.int`` (value) - deprecated, because in ES3 browsers, "int" is a reserved word
- ``is.maximum`` (value, others)
- ``is.minimum`` (value, others)
- ``is.nan`` (value)
- ``is.even`` (value)
- ``is.odd`` (value)
- ``is.ge`` (value, other)
- ``is.gt`` (value, other)
- ``is.le`` (value, other)
- ``is.lt`` (value, other)
- ``is.within`` (value, start, finish)
### object
- ``is.object`` (value)
### regexp
- ``is.regexp`` (value)
### string
- ``is.string`` (value)
### encoded binary
- ``is.base64`` (value)
- ``is.hex`` (value)
### ES6 Symbols
- ``is.symbol`` (value)
## Contributors
- [Jordan Harband](https://github.com/ljharb)
[npm-url]: https://npmjs.org/package/is
[npm-version-svg]: http://versionbadg.es/enricomarino/is.svg
[travis-svg]: https://travis-ci.org/enricomarino/is.svg
[travis-url]: https://travis-ci.org/enricomarino/is
[deps-svg]: https://david-dm.org/enricomarino/is.svg
[deps-url]: https://david-dm.org/enricomarino/is
[dev-deps-svg]: https://david-dm.org/enricomarino/is/dev-status.svg
[dev-deps-url]: https://david-dm.org/enricomarino/is#info=devDependencies
[testling-png]: https://ci.testling.com/enricomarino/is.png
[testling-url]: https://ci.testling.com/enricomarino/is
[npm-badge-png]: https://nodei.co/npm/is.png?downloads=true&stars=true
[license-image]: http://img.shields.io/npm/l/is.svg
[license-url]: LICENSE.md
[downloads-image]: http://img.shields.io/npm/dm/is.svg
[downloads-url]: http://npm-stat.com/charts.html?package=is

View File

@@ -0,0 +1,8 @@
{
"name": "is",
"repo": "enricomarino/is",
"description": "The definitive type testing library",
"version": "2.2.0",
"dependencies": {},
"scripts": ["index.js"]
}

View File

@@ -0,0 +1,761 @@
/* globals window, HTMLElement */
/**!
* is
* the definitive JavaScript type testing library
*
* @copyright 2013-2014 Enrico Marino / Jordan Harband
* @license MIT
*/
var objProto = Object.prototype;
var owns = objProto.hasOwnProperty;
var toStr = objProto.toString;
var symbolValueOf;
if (typeof Symbol === 'function') {
symbolValueOf = Symbol.prototype.valueOf;
}
var isActualNaN = function (value) {
return value !== value;
};
var NON_HOST_TYPES = {
'boolean': 1,
number: 1,
string: 1,
undefined: 1
};
var base64Regex = /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/;
var hexRegex = /^[A-Fa-f0-9]+$/;
/**
* Expose `is`
*/
var is = module.exports = {};
/**
* Test general.
*/
/**
* is.type
* Test if `value` is a type of `type`.
*
* @param {Mixed} value value to test
* @param {String} type type
* @return {Boolean} true if `value` is a type of `type`, false otherwise
* @api public
*/
is.a = is.type = function (value, type) {
return typeof value === type;
};
/**
* is.defined
* Test if `value` is defined.
*
* @param {Mixed} value value to test
* @return {Boolean} true if 'value' is defined, false otherwise
* @api public
*/
is.defined = function (value) {
return typeof value !== 'undefined';
};
/**
* is.empty
* Test if `value` is empty.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is empty, false otherwise
* @api public
*/
is.empty = function (value) {
var type = toStr.call(value);
var key;
if (type === '[object Array]' || type === '[object Arguments]' || type === '[object String]') {
return value.length === 0;
}
if (type === '[object Object]') {
for (key in value) {
if (owns.call(value, key)) { return false; }
}
return true;
}
return !value;
};
/**
* is.equal
* Test if `value` is equal to `other`.
*
* @param {Mixed} value value to test
* @param {Mixed} other value to compare with
* @return {Boolean} true if `value` is equal to `other`, false otherwise
*/
is.equal = function equal(value, other) {
if (value === other) {
return true;
}
var type = toStr.call(value);
var key;
if (type !== toStr.call(other)) {
return false;
}
if (type === '[object Object]') {
for (key in value) {
if (!is.equal(value[key], other[key]) || !(key in other)) {
return false;
}
}
for (key in other) {
if (!is.equal(value[key], other[key]) || !(key in value)) {
return false;
}
}
return true;
}
if (type === '[object Array]') {
key = value.length;
if (key !== other.length) {
return false;
}
while (--key) {
if (!is.equal(value[key], other[key])) {
return false;
}
}
return true;
}
if (type === '[object Function]') {
return value.prototype === other.prototype;
}
if (type === '[object Date]') {
return value.getTime() === other.getTime();
}
return false;
};
/**
* is.hosted
* Test if `value` is hosted by `host`.
*
* @param {Mixed} value to test
* @param {Mixed} host host to test with
* @return {Boolean} true if `value` is hosted by `host`, false otherwise
* @api public
*/
is.hosted = function (value, host) {
var type = typeof host[value];
return type === 'object' ? !!host[value] : !NON_HOST_TYPES[type];
};
/**
* is.instance
* Test if `value` is an instance of `constructor`.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is an instance of `constructor`
* @api public
*/
is.instance = is['instanceof'] = function (value, constructor) {
return value instanceof constructor;
};
/**
* is.nil / is.null
* Test if `value` is null.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is null, false otherwise
* @api public
*/
is.nil = is['null'] = function (value) {
return value === null;
};
/**
* is.undef / is.undefined
* Test if `value` is undefined.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is undefined, false otherwise
* @api public
*/
is.undef = is.undefined = function (value) {
return typeof value === 'undefined';
};
/**
* Test arguments.
*/
/**
* is.args
* Test if `value` is an arguments object.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is an arguments object, false otherwise
* @api public
*/
is.args = is.arguments = function (value) {
var isStandardArguments = toStr.call(value) === '[object Arguments]';
var isOldArguments = !is.array(value) && is.arraylike(value) && is.object(value) && is.fn(value.callee);
return isStandardArguments || isOldArguments;
};
/**
* Test array.
*/
/**
* is.array
* Test if 'value' is an array.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is an array, false otherwise
* @api public
*/
is.array = Array.isArray || function (value) {
return toStr.call(value) === '[object Array]';
};
/**
* is.arguments.empty
* Test if `value` is an empty arguments object.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is an empty arguments object, false otherwise
* @api public
*/
is.args.empty = function (value) {
return is.args(value) && value.length === 0;
};
/**
* is.array.empty
* Test if `value` is an empty array.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is an empty array, false otherwise
* @api public
*/
is.array.empty = function (value) {
return is.array(value) && value.length === 0;
};
/**
* is.arraylike
* Test if `value` is an arraylike object.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is an arguments object, false otherwise
* @api public
*/
is.arraylike = function (value) {
return !!value && !is.bool(value)
&& owns.call(value, 'length')
&& isFinite(value.length)
&& is.number(value.length)
&& value.length >= 0;
};
/**
* Test boolean.
*/
/**
* is.bool
* Test if `value` is a boolean.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is a boolean, false otherwise
* @api public
*/
is.bool = is['boolean'] = function (value) {
return toStr.call(value) === '[object Boolean]';
};
/**
* is.false
* Test if `value` is false.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is false, false otherwise
* @api public
*/
is['false'] = function (value) {
return is.bool(value) && Boolean(Number(value)) === false;
};
/**
* is.true
* Test if `value` is true.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is true, false otherwise
* @api public
*/
is['true'] = function (value) {
return is.bool(value) && Boolean(Number(value)) === true;
};
/**
* Test date.
*/
/**
* is.date
* Test if `value` is a date.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is a date, false otherwise
* @api public
*/
is.date = function (value) {
return toStr.call(value) === '[object Date]';
};
/**
* Test element.
*/
/**
* is.element
* Test if `value` is an html element.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is an HTML Element, false otherwise
* @api public
*/
is.element = function (value) {
return value !== undefined
&& typeof HTMLElement !== 'undefined'
&& value instanceof HTMLElement
&& value.nodeType === 1;
};
/**
* Test error.
*/
/**
* is.error
* Test if `value` is an error object.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is an error object, false otherwise
* @api public
*/
is.error = function (value) {
return toStr.call(value) === '[object Error]';
};
/**
* Test function.
*/
/**
* is.fn / is.function (deprecated)
* Test if `value` is a function.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is a function, false otherwise
* @api public
*/
is.fn = is['function'] = function (value) {
var isAlert = typeof window !== 'undefined' && value === window.alert;
return isAlert || toStr.call(value) === '[object Function]';
};
/**
* Test number.
*/
/**
* is.number
* Test if `value` is a number.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is a number, false otherwise
* @api public
*/
is.number = function (value) {
return toStr.call(value) === '[object Number]';
};
/**
* is.infinite
* Test if `value` is positive or negative infinity.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is positive or negative Infinity, false otherwise
* @api public
*/
is.infinite = function (value) {
return value === Infinity || value === -Infinity;
};
/**
* is.decimal
* Test if `value` is a decimal number.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is a decimal number, false otherwise
* @api public
*/
is.decimal = function (value) {
return is.number(value) && !isActualNaN(value) && !is.infinite(value) && value % 1 !== 0;
};
/**
* is.divisibleBy
* Test if `value` is divisible by `n`.
*
* @param {Number} value value to test
* @param {Number} n dividend
* @return {Boolean} true if `value` is divisible by `n`, false otherwise
* @api public
*/
is.divisibleBy = function (value, n) {
var isDividendInfinite = is.infinite(value);
var isDivisorInfinite = is.infinite(n);
var isNonZeroNumber = is.number(value) && !isActualNaN(value) && is.number(n) && !isActualNaN(n) && n !== 0;
return isDividendInfinite || isDivisorInfinite || (isNonZeroNumber && value % n === 0);
};
/**
* is.integer
* Test if `value` is an integer.
*
* @param value to test
* @return {Boolean} true if `value` is an integer, false otherwise
* @api public
*/
is.integer = is['int'] = function (value) {
return is.number(value) && !isActualNaN(value) && value % 1 === 0;
};
/**
* is.maximum
* Test if `value` is greater than 'others' values.
*
* @param {Number} value value to test
* @param {Array} others values to compare with
* @return {Boolean} true if `value` is greater than `others` values
* @api public
*/
is.maximum = function (value, others) {
if (isActualNaN(value)) {
throw new TypeError('NaN is not a valid value');
} else if (!is.arraylike(others)) {
throw new TypeError('second argument must be array-like');
}
var len = others.length;
while (--len >= 0) {
if (value < others[len]) {
return false;
}
}
return true;
};
/**
* is.minimum
* Test if `value` is less than `others` values.
*
* @param {Number} value value to test
* @param {Array} others values to compare with
* @return {Boolean} true if `value` is less than `others` values
* @api public
*/
is.minimum = function (value, others) {
if (isActualNaN(value)) {
throw new TypeError('NaN is not a valid value');
} else if (!is.arraylike(others)) {
throw new TypeError('second argument must be array-like');
}
var len = others.length;
while (--len >= 0) {
if (value > others[len]) {
return false;
}
}
return true;
};
/**
* is.nan
* Test if `value` is not a number.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is not a number, false otherwise
* @api public
*/
is.nan = function (value) {
return !is.number(value) || value !== value;
};
/**
* is.even
* Test if `value` is an even number.
*
* @param {Number} value value to test
* @return {Boolean} true if `value` is an even number, false otherwise
* @api public
*/
is.even = function (value) {
return is.infinite(value) || (is.number(value) && value === value && value % 2 === 0);
};
/**
* is.odd
* Test if `value` is an odd number.
*
* @param {Number} value value to test
* @return {Boolean} true if `value` is an odd number, false otherwise
* @api public
*/
is.odd = function (value) {
return is.infinite(value) || (is.number(value) && value === value && value % 2 !== 0);
};
/**
* is.ge
* Test if `value` is greater than or equal to `other`.
*
* @param {Number} value value to test
* @param {Number} other value to compare with
* @return {Boolean}
* @api public
*/
is.ge = function (value, other) {
if (isActualNaN(value) || isActualNaN(other)) {
throw new TypeError('NaN is not a valid value');
}
return !is.infinite(value) && !is.infinite(other) && value >= other;
};
/**
* is.gt
* Test if `value` is greater than `other`.
*
* @param {Number} value value to test
* @param {Number} other value to compare with
* @return {Boolean}
* @api public
*/
is.gt = function (value, other) {
if (isActualNaN(value) || isActualNaN(other)) {
throw new TypeError('NaN is not a valid value');
}
return !is.infinite(value) && !is.infinite(other) && value > other;
};
/**
* is.le
* Test if `value` is less than or equal to `other`.
*
* @param {Number} value value to test
* @param {Number} other value to compare with
* @return {Boolean} if 'value' is less than or equal to 'other'
* @api public
*/
is.le = function (value, other) {
if (isActualNaN(value) || isActualNaN(other)) {
throw new TypeError('NaN is not a valid value');
}
return !is.infinite(value) && !is.infinite(other) && value <= other;
};
/**
* is.lt
* Test if `value` is less than `other`.
*
* @param {Number} value value to test
* @param {Number} other value to compare with
* @return {Boolean} if `value` is less than `other`
* @api public
*/
is.lt = function (value, other) {
if (isActualNaN(value) || isActualNaN(other)) {
throw new TypeError('NaN is not a valid value');
}
return !is.infinite(value) && !is.infinite(other) && value < other;
};
/**
* is.within
* Test if `value` is within `start` and `finish`.
*
* @param {Number} value value to test
* @param {Number} start lower bound
* @param {Number} finish upper bound
* @return {Boolean} true if 'value' is is within 'start' and 'finish'
* @api public
*/
is.within = function (value, start, finish) {
if (isActualNaN(value) || isActualNaN(start) || isActualNaN(finish)) {
throw new TypeError('NaN is not a valid value');
} else if (!is.number(value) || !is.number(start) || !is.number(finish)) {
throw new TypeError('all arguments must be numbers');
}
var isAnyInfinite = is.infinite(value) || is.infinite(start) || is.infinite(finish);
return isAnyInfinite || (value >= start && value <= finish);
};
/**
* Test object.
*/
/**
* is.object
* Test if `value` is an object.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is an object, false otherwise
* @api public
*/
is.object = function (value) {
return toStr.call(value) === '[object Object]';
};
/**
* is.hash
* Test if `value` is a hash - a plain object literal.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is a hash, false otherwise
* @api public
*/
is.hash = function (value) {
return is.object(value) && value.constructor === Object && !value.nodeType && !value.setInterval;
};
/**
* Test regexp.
*/
/**
* is.regexp
* Test if `value` is a regular expression.
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is a regexp, false otherwise
* @api public
*/
is.regexp = function (value) {
return toStr.call(value) === '[object RegExp]';
};
/**
* Test string.
*/
/**
* is.string
* Test if `value` is a string.
*
* @param {Mixed} value value to test
* @return {Boolean} true if 'value' is a string, false otherwise
* @api public
*/
is.string = function (value) {
return toStr.call(value) === '[object String]';
};
/**
* Test base64 string.
*/
/**
* is.base64
* Test if `value` is a valid base64 encoded string.
*
* @param {Mixed} value value to test
* @return {Boolean} true if 'value' is a base64 encoded string, false otherwise
* @api public
*/
is.base64 = function (value) {
return is.string(value) && (!value.length || base64Regex.test(value));
};
/**
* Test base64 string.
*/
/**
* is.hex
* Test if `value` is a valid hex encoded string.
*
* @param {Mixed} value value to test
* @return {Boolean} true if 'value' is a hex encoded string, false otherwise
* @api public
*/
is.hex = function (value) {
return is.string(value) && (!value.length || hexRegex.test(value));
};
/**
* is.symbol
* Test if `value` is an ES6 Symbol
*
* @param {Mixed} value value to test
* @return {Boolean} true if `value` is a Symbol, false otherise
* @api public
*/
is.symbol = function (value) {
return typeof Symbol === 'function' && toStr.call(value) === '[object Symbol]' && typeof symbolValueOf.call(value) === 'symbol';
};

View File

@@ -0,0 +1,93 @@
{
"name": "is",
"version": "3.1.0",
"main": "index.js",
"scripts": {
"test": "npm run lint && node test/index.js",
"coverage": "covert test/index.js",
"coverage-quiet": "covert test/index.js --quiet",
"lint": "npm run jscs && npm run eslint",
"jscs": "jscs *.js */*.js",
"eslint": "eslint *.js */*.js"
},
"author": {
"name": "Enrico Marino",
"url": "http://onirame.com"
},
"description": "the definitive JavaScript type testing library",
"homepage": "https://github.com/enricomarino/is",
"license": "MIT",
"repository": {
"type": "git",
"url": "git://github.com/enricomarino/is.git"
},
"keywords": [
"util",
"type",
"test"
],
"contributors": [
{
"name": "Jordan Harband",
"url": "https://github.com/ljharb"
}
],
"dependencies": {},
"devDependencies": {
"tape": "^4.2.0",
"foreach": "^2.0.5",
"covert": "^1.1.0",
"jscs": "^2.1.1",
"eslint": "^1.5.0",
"@ljharb/eslint-config": "^1.2.0"
},
"testling": {
"files": "test/index.js",
"browsers": [
"iexplore/6.0..latest",
"firefox/3.0",
"firefox/15.0..latest",
"firefox/nightly",
"chrome/4.0",
"chrome/22.0..latest",
"chrome/canary",
"opera/10.0..latest",
"opera/next",
"safari/5.0.5..latest",
"ipad/6.0..latest",
"iphone/6.0..latest"
]
},
"engines": {
"node": "*"
},
"gitHead": "7b3ba15898119e90c3a8ef3b9d347fa70a4e8255",
"bugs": {
"url": "https://github.com/enricomarino/is/issues"
},
"_id": "is@3.1.0",
"_shasum": "2945d205d691cbfe4833e3f8a11c8ae94673f2a7",
"_from": "is@>=3.0.1 <4.0.0",
"_npmVersion": "2.14.3",
"_nodeVersion": "4.1.0",
"_npmUser": {
"name": "ljharb",
"email": "ljharb@gmail.com"
},
"dist": {
"shasum": "2945d205d691cbfe4833e3f8a11c8ae94673f2a7",
"tarball": "http://registry.npmjs.org/is/-/is-3.1.0.tgz"
},
"maintainers": [
{
"name": "ljharb",
"email": "ljharb@gmail.com"
},
{
"name": "enricomarino",
"email": "enrico.marino@email.com"
}
],
"directories": {},
"_resolved": "https://registry.npmjs.org/is/-/is-3.1.0.tgz"
}

View File

@@ -0,0 +1,636 @@
/* globals window, document */
var test = require('tape');
var is = require('../index.js');
var forEach = require('foreach');
var toStr = Object.prototype.toString;
test('is.type', function (t) {
var booleans = [true, false];
forEach(booleans, function (boolean) {
t.ok(is.type(boolean, 'boolean'), '"' + boolean + '" is a boolean');
});
var numbers = [1, 0 / 1, 0 / -1, NaN, Infinity, -Infinity];
forEach(numbers, function (number) {
t.ok(is.type(number, 'number'), '"' + number + '" is a number');
});
var objects = [{}, null, new Date()];
forEach(objects, function (object) {
t.ok(is.type(object, 'object'), '"' + object + '" is an object');
});
var strings = ['', 'abc'];
forEach(strings, function (string) {
t.ok(is.type(string, 'string'), '"' + string + '" is a string');
});
t.ok(is.type(undefined, 'undefined'), 'undefined is undefined');
t.end();
});
test('is.undef', function (t) {
t.ok(is.undef(), 'absent undefined is undefined');
t.ok(is.undef(undefined), 'literal undefined is undefined');
t.notOk(is.undef(null), 'null is not undefined');
t.notOk(is.undef({}), 'object is not undefined');
t.end();
});
test('is.defined', function (t) {
t.notOk(is.defined(), 'undefined is not defined');
t.ok(is.defined(null), 'null is defined');
t.ok(is.defined({}), 'object is undefined');
t.end();
});
test('is.empty', function (t) {
t.ok(is.empty(''), 'empty string is empty');
t.ok(is.empty(Object('')), 'empty String object is empty');
t.ok(is.empty([]), 'empty array is empty');
t.ok(is.empty({}), 'empty object is empty');
t.ok(is.empty(null), 'null is empty');
t.ok(is.empty(), 'undefined is empty');
t.ok(is.empty(undefined), 'undefined is empty');
t.ok(is.empty(false), 'false is empty');
t.ok(is.empty(0), '0 is empty');
t.ok(is.empty(NaN), 'nan is empty');
(function () { t.ok(is.empty(arguments), 'empty arguments is empty'); }());
t.notOk(is.empty({ a: 1 }), 'nonempty object is not empty');
t.notOk(is.empty(true), 'true is not empty');
t.notOk(is.empty(/a/g), 'regex is not empty');
t.notOk(is.empty(new Date()), 'date is not empty');
t.end();
});
test('is.equal', function (t) {
t.test('primitives', function (pt) {
var primitives = [true, false, undefined, null, '', 'foo', 0, Infinity, -Infinity];
pt.plan(primitives.length);
for (var i = 0; i < primitives.length; ++i) {
pt.ok(is.equal(primitives[i], primitives[i]), 'primitives are equal to themselves: ' + primitives[i]);
}
pt.end();
});
t.test('arrays', function (at) {
at.ok(is.equal([1, 2, 3], [1, 2, 3]), 'arrays are shallowly equal');
at.ok(is.equal([1, 2, [3, 4]], [1, 2, [3, 4]]), 'arrays are deep equal');
at.notOk(is.equal([1, 2], [2, 3]), 'inequal arrays are not equal');
at.notOk(is.equal([1, 2, 3], [2, 3]), 'inequal length arrays are not equal');
var arr = [1, 2];
at.ok(is.equal(arr, arr), 'array is equal to itself');
at.end();
});
t.test('dates', function (dt) {
dt.plan(2);
var now = new Date();
dt.ok(is.equal(now, new Date(now.getTime())), 'two equal date objects are equal');
setTimeout(function () {
dt.notOk(is.equal(now, new Date()), 'two inequal date objects are not equal');
dt.end();
}, 10);
});
t.test('plain objects', function (ot) {
ot.ok(is.equal({ a: 1, b: 2, c: 3 }, { a: 1, b: 2, c: 3 }), 'objects are shallowly equal');
ot.ok(is.equal({ a: { b: 1 } }, { a: { b: 1 } }), 'objects are deep equal');
ot.notOk(is.equal({ a: 1 }, { a: 2 }), 'inequal objects are not equal');
ot.end();
});
t.test('object instances', function (ot) {
var F = function F() {
this.foo = 'bar';
};
F.prototype = {};
var G = function G() {
this.foo = 'bar';
};
var f = new F();
var g = new G();
ot.ok(is.equal(f, f), 'the same object instances are equal');
ot.ok(is.equal(f, new F()), 'two object instances are equal when the prototype and props are the same');
ot.ok(is.equal(f, new G()), 'two object instances are equal when the prototype is not the same, but props are');
g.bar = 'baz';
ot.notOk(is.equal(f, g), 'object instances are not equal when the prototype and props are not the same');
ot.notOk(is.equal(g, f), 'object instances are not equal when the prototype and props are not the same');
ot.end();
});
t.test('functions', function (ft) {
var F = function () {};
F.prototype = {};
var G = function () {};
G.prototype = new Date();
ft.notEqual(F.prototype, G.prototype, 'F and G have different prototypes');
ft.notOk(is.equal(F, G), 'two functions are not equal when the prototype is not the same');
var H = function () {};
H.prototype = F.prototype;
ft.equal(F.prototype, H.prototype, 'F and H have the same prototype');
ft.ok(is.equal(F, H), 'two functions are equal when the prototype is the same');
ft.end();
});
t.end();
});
test('is.hosted', function (t) {
t.ok(is.hosted('a', { a: {} }), 'object is hosted');
t.ok(is.hosted('a', { a: [] }), 'array is hosted');
t.ok(is.hosted('a', { a: function () {} }), 'function is hosted');
t.notOk(is.hosted('a', { a: true }), 'boolean value is not hosted');
t.notOk(is.hosted('a', { a: false }), 'boolean value is not hosted');
t.notOk(is.hosted('a', { a: 3 }), 'number value is not hosted');
t.notOk(is.hosted('a', { a: undefined }), 'undefined value is not hosted');
t.notOk(is.hosted('a', { a: 'abc' }), 'string value is not hosted');
t.notOk(is.hosted('a', { a: null }), 'null value is not hosted');
t.end();
});
test('is.instance', function (t) {
t.ok(is.instance(new Date(), Date), 'new Date is instanceof Date');
var F = function () {};
t.ok(is.instance(new F(), F), 'new constructor is instanceof constructor');
t.end();
});
test('is.nil', function (t) {
var isNull = is.nil;
t.equal(isNull, is['null'], 'is.nil is the same as is.null');
t.ok(isNull(null), 'null is null');
t.notOk(isNull(undefined), 'undefined is not null');
t.notOk(isNull({}), 'object is not null');
t.end();
});
test('is.args', function (t) {
t.notOk(is.args([]), 'array is not arguments');
(function () { t.ok(is.args(arguments), 'arguments is arguments'); }());
(function () { t.notOk(is.args(Array.prototype.slice.call(arguments)), 'sliced arguments is not arguments'); }());
var fakeOldArguments = {
callee: function () {},
length: 3
};
t.ok(is.args(fakeOldArguments), 'old-style arguments object is arguments');
t.end();
});
test('is.args.empty', function (t) {
t.notOk(is.args.empty([]), 'empty array is not empty arguments');
(function () { t.ok(is.args.empty(arguments), 'empty arguments is empty arguments'); }());
(function () { t.notOk(is.args.empty(Array.prototype.slice.call(arguments)), 'empty sliced arguments is not empty arguments'); }());
t.end();
});
test('is.array', function (t) {
t.ok(is.array([]), 'array is array');
(function () { t.ok(is.array(Array.prototype.slice.call(arguments)), 'sliced arguments is array'); }());
t.end();
});
test('is.array.empty', function (t) {
t.ok(is.array.empty([]), 'empty array is empty array');
(function () { t.notOk(is.array.empty(arguments), 'empty arguments is not empty array'); }());
(function () { t.ok(is.array.empty(Array.prototype.slice.call(arguments)), 'empty sliced arguments is empty array'); }());
t.end();
});
test('is.isarraylike', function (t) {
t.notOk(is.arraylike(), 'undefined is not array-like');
t.notOk(is.arraylike(null), 'null is not array-like');
t.notOk(is.arraylike(false), 'false is not array-like');
t.notOk(is.arraylike(true), 'true is not array-like');
t.ok(is.arraylike({ length: 0 }), 'object with zero length is array-like');
t.ok(is.arraylike({ length: 1 }), 'object with positive length is array-like');
t.notOk(is.arraylike({ length: -1 }), 'object with negative length is not array-like');
t.notOk(is.arraylike({ length: NaN }), 'object with NaN length is not array-like');
t.notOk(is.arraylike({ length: 'foo' }), 'object with string length is not array-like');
t.notOk(is.arraylike({ length: '' }), 'object with empty string length is not array-like');
t.ok(is.arraylike([]), 'array is array-like');
(function () { t.ok(is.arraylike(arguments), 'empty arguments is array-like'); }());
(function () { t.ok(is.arraylike(arguments), 'nonempty arguments is array-like'); }(1, 2, 3));
t.end();
});
test('is.bool', function (t) {
t.ok(is.bool(true), 'literal true is a boolean');
t.ok(is.bool(false), 'literal false is a boolean');
t.ok(is.bool(Object(true)), 'object true is a boolean');
t.ok(is.bool(Object(false)), 'object false is a boolean');
t.notOk(is.bool(), 'undefined is not a boolean');
t.notOk(is.bool(null), 'null is not a boolean');
t.end();
});
test('is.false', function (t) {
var isFalse = is['false'];
t.ok(isFalse(false), 'false is false');
t.ok(isFalse(Object(false)), 'object false is false');
t.notOk(isFalse(true), 'true is not false');
t.notOk(isFalse(), 'undefined is not false');
t.notOk(isFalse(null), 'null is not false');
t.notOk(isFalse(''), 'empty string is not false');
t.end();
});
test('is.true', function (t) {
var isTrue = is['true'];
t.ok(isTrue(true), 'true is true');
t.ok(isTrue(Object(true)), 'object true is true');
t.notOk(isTrue(false), 'false is not true');
t.notOk(isTrue(), 'undefined is not true');
t.notOk(isTrue(null), 'null is not true');
t.notOk(isTrue(''), 'empty string is not true');
t.end();
});
test('is.date', function (t) {
t.ok(is.date(new Date()), 'new Date is date');
t.notOk(is.date(), 'undefined is not date');
t.notOk(is.date(null), 'null is not date');
t.notOk(is.date(''), 'empty string is not date');
var nowTS = (new Date()).getTime();
t.notOk(is.date(nowTS), 'timestamp is not date');
var F = function () {};
F.prototype = new Date();
t.notOk(is.date(new F()), 'Date subtype is not date');
t.end();
});
test('is.element', function (t) {
t.notOk(is.element(), 'undefined is not element');
if (typeof HTMLElement !== 'undefined') {
var element = document.createElement('div');
t.ok(is.element(element), 'HTMLElement is element');
t.notOk(is.element({ nodeType: 1 }), 'object with nodeType is not element');
} else {
t.ok(true, 'Skipping is.element test in a non-browser environment');
}
t.end();
});
test('is.error', function (t) {
var err = new Error('foo');
t.ok(is.error(err), 'Error is error');
t.notOk(is.error({}), 'object is not error');
var objWithErrorToString = { toString: function () { return '[object Error]'; } };
t.equal(String(objWithErrorToString), toStr.call(new Error()), 'obj has Error\'s toString');
t.notOk(is.error(objWithErrorToString), 'object with Error\'s toString is not error');
t.end();
});
test('is.fn', function (t) {
t.equal(is['function'], is.fn, 'alias works');
t.ok(is.fn(function () {}), 'function is function');
if (typeof window !== 'undefined') {
// in IE7/8, typeof alert === 'object'
t.ok(is.fn(window.alert), 'window.alert is function');
}
t.notOk(is.fn({}), 'object is not function');
t.notOk(is.fn(null), 'null is not function');
t.end();
});
test('is.number', function (t) {
t.ok(is.number(0), 'positive zero is number');
t.ok(is.number(0 / -1), 'negative zero is number');
t.ok(is.number(3), 'three is number');
t.ok(is.number(NaN), 'NaN is number');
t.ok(is.number(Infinity), 'infinity is number');
t.ok(is.number(-Infinity), 'negative infinity is number');
t.ok(is.number(Object(42)), 'object number is number');
t.notOk(is.number(), 'undefined is not number');
t.notOk(is.number(null), 'null is not number');
t.notOk(is.number(true), 'true is not number');
t.end();
});
test('is.infinite', function (t) {
t.ok(is.infinite(Infinity), 'positive infinity is infinite');
t.ok(is.infinite(-Infinity), 'negative infinity is infinite');
t.notOk(is.infinite(NaN), 'NaN is not infinite');
t.notOk(is.infinite(0), 'a number is not infinite');
t.end();
});
test('is.decimal', function (t) {
t.ok(is.decimal(1.1), 'decimal is decimal');
t.notOk(is.decimal(0), 'zero is not decimal');
t.notOk(is.decimal(1), 'integer is not decimal');
t.notOk(is.decimal(NaN), 'NaN is not decimal');
t.notOk(is.decimal(Infinity), 'Infinity is not decimal');
t.end();
});
test('is.divisibleBy', function (t) {
t.ok(is.divisibleBy(4, 2), '4 is divisible by 2');
t.ok(is.divisibleBy(4, 2), '4 is divisible by 2');
t.ok(is.divisibleBy(0, 1), '0 is divisible by 1');
t.ok(is.divisibleBy(Infinity, 1), 'infinity is divisible by anything');
t.ok(is.divisibleBy(1, Infinity), 'anything is divisible by infinity');
t.ok(is.divisibleBy(Infinity, Infinity), 'infinity is divisible by infinity');
t.notOk(is.divisibleBy(1, 0), '1 is not divisible by 0');
t.notOk(is.divisibleBy(NaN, 1), 'NaN is not divisible by 1');
t.notOk(is.divisibleBy(1, NaN), '1 is not divisible by NaN');
t.notOk(is.divisibleBy(NaN, NaN), 'NaN is not divisible by NaN');
t.notOk(is.divisibleBy(1, 3), '1 is not divisible by 3');
t.end();
});
test('is.integer', function (t) {
t.ok(is.integer(0), '0 is integer');
t.ok(is.integer(3), '3 is integer');
t.notOk(is.integer(1.1), '1.1 is not integer');
t.notOk(is.integer(NaN), 'NaN is not integer');
t.notOk(is.integer(Infinity), 'infinity is not integer');
t.notOk(is.integer(null), 'null is not integer');
t.notOk(is.integer(), 'undefined is not integer');
t.end();
});
test('is.maximum', function (t) {
t.ok(is.maximum(3, [3, 2, 1]), '3 is maximum of [3,2,1]');
t.ok(is.maximum(3, [1, 2, 3]), '3 is maximum of [1,2,3]');
t.ok(is.maximum(4, [1, 2, 3]), '4 is maximum of [1,2,3]');
t.ok(is.maximum('c', ['a', 'b', 'c']), 'c is maximum of [a,b,c]');
t.notOk(is.maximum(2, [1, 2, 3]), '2 is not maximum of [1,2,3]');
var nanError = new TypeError('NaN is not a valid value');
t['throws'](function () { return is.maximum(NaN); }, nanError, 'throws when first value is NaN');
var error = new TypeError('second argument must be array-like');
t['throws'](function () { return is.maximum(2, null); }, error, 'throws when second value is not array-like');
t['throws'](function () { return is.maximum(2, {}); }, error, 'throws when second value is not array-like');
t.end();
});
test('is.minimum', function (t) {
t.ok(is.minimum(1, [1, 2, 3]), '1 is minimum of [1,2,3]');
t.ok(is.minimum(0, [1, 2, 3]), '0 is minimum of [1,2,3]');
t.ok(is.minimum('a', ['a', 'b', 'c']), 'a is minimum of [a,b,c]');
t.notOk(is.minimum(2, [1, 2, 3]), '2 is not minimum of [1,2,3]');
var nanError = new TypeError('NaN is not a valid value');
t['throws'](function () { return is.minimum(NaN); }, nanError, 'throws when first value is NaN');
var error = new TypeError('second argument must be array-like');
t['throws'](function () { return is.minimum(2, null); }, error, 'throws when second value is not array-like');
t['throws'](function () { return is.minimum(2, {}); }, error, 'throws when second value is not array-like');
t.end();
});
test('is.nan', function (t) {
t.ok(is.nan(NaN), 'NaN is not a number');
t.ok(is.nan('abc'), 'string is not a number');
t.ok(is.nan(true), 'boolean is not a number');
t.ok(is.nan({}), 'object is not a number');
t.ok(is.nan([]), 'array is not a number');
t.ok(is.nan(function () {}), 'function is not a number');
t.notOk(is.nan(0), 'zero is a number');
t.notOk(is.nan(3), 'three is a number');
t.notOk(is.nan(1.1), '1.1 is a number');
t.notOk(is.nan(Infinity), 'infinity is a number');
t.end();
});
test('is.even', function (t) {
t.ok(is.even(0), 'zero is even');
t.ok(is.even(2), 'two is even');
t.ok(is.even(Infinity), 'infinity is even');
t.notOk(is.even(1), '1 is not even');
t.notOk(is.even(), 'undefined is not even');
t.notOk(is.even(null), 'null is not even');
t.notOk(is.even(NaN), 'NaN is not even');
t.end();
});
test('is.odd', function (t) {
t.ok(is.odd(1), 'zero is odd');
t.ok(is.odd(3), 'two is odd');
t.ok(is.odd(Infinity), 'infinity is odd');
t.notOk(is.odd(0), '0 is not odd');
t.notOk(is.odd(2), '2 is not odd');
t.notOk(is.odd(), 'undefined is not odd');
t.notOk(is.odd(null), 'null is not odd');
t.notOk(is.odd(NaN), 'NaN is not odd');
t.end();
});
test('is.ge', function (t) {
t.ok(is.ge(3, 2), '3 is greater than 2');
t.notOk(is.ge(2, 3), '2 is not greater than 3');
t.ok(is.ge(3, 3), '3 is greater than or equal to 3');
t.ok(is.ge('abc', 'a'), 'abc is greater than a');
t.ok(is.ge('abc', 'abc'), 'abc is greater than or equal to abc');
t.notOk(is.ge('a', 'abc'), 'a is not greater than abc');
t.notOk(is.ge(Infinity, 0), 'infinity is not greater than anything');
t.notOk(is.ge(0, Infinity), 'anything is not greater than infinity');
var error = new TypeError('NaN is not a valid value');
t['throws'](function () { return is.ge(NaN, 2); }, error, 'throws when first value is NaN');
t['throws'](function () { return is.ge(2, NaN); }, error, 'throws when second value is NaN');
t.end();
});
test('is.gt', function (t) {
t.ok(is.gt(3, 2), '3 is greater than 2');
t.notOk(is.gt(2, 3), '2 is not greater than 3');
t.notOk(is.gt(3, 3), '3 is not greater than 3');
t.ok(is.gt('abc', 'a'), 'abc is greater than a');
t.notOk(is.gt('abc', 'abc'), 'abc is not greater than abc');
t.notOk(is.gt('a', 'abc'), 'a is not greater than abc');
t.notOk(is.gt(Infinity, 0), 'infinity is not greater than anything');
t.notOk(is.gt(0, Infinity), 'anything is not greater than infinity');
var error = new TypeError('NaN is not a valid value');
t['throws'](function () { return is.gt(NaN, 2); }, error, 'throws when first value is NaN');
t['throws'](function () { return is.gt(2, NaN); }, error, 'throws when second value is NaN');
t.end();
});
test('is.le', function (t) {
t.ok(is.le(2, 3), '2 is lesser than or equal to 3');
t.notOk(is.le(3, 2), '3 is not lesser than or equal to 2');
t.ok(is.le(3, 3), '3 is lesser than or equal to 3');
t.ok(is.le('a', 'abc'), 'a is lesser than or equal to abc');
t.ok(is.le('abc', 'abc'), 'abc is lesser than or equal to abc');
t.notOk(is.le('abc', 'a'), 'abc is not lesser than or equal to a');
t.notOk(is.le(Infinity, 0), 'infinity is not lesser than or equal to anything');
t.notOk(is.le(0, Infinity), 'anything is not lesser than or equal to infinity');
var error = new TypeError('NaN is not a valid value');
t['throws'](function () { return is.le(NaN, 2); }, error, 'throws when first value is NaN');
t['throws'](function () { return is.le(2, NaN); }, error, 'throws when second value is NaN');
t.end();
});
test('is.lt', function (t) {
t.ok(is.lt(2, 3), '2 is lesser than 3');
t.notOk(is.lt(3, 2), '3 is not lesser than 2');
t.notOk(is.lt(3, 3), '3 is not lesser than 3');
t.ok(is.lt('a', 'abc'), 'a is lesser than abc');
t.notOk(is.lt('abc', 'abc'), 'abc is not lesser than abc');
t.notOk(is.lt('abc', 'a'), 'abc is not lesser than a');
t.notOk(is.lt(Infinity, 0), 'infinity is not lesser than anything');
t.notOk(is.lt(0, Infinity), 'anything is not lesser than infinity');
var error = new TypeError('NaN is not a valid value');
t['throws'](function () { return is.lt(NaN, 2); }, error, 'throws when first value is NaN');
t['throws'](function () { return is.lt(2, NaN); }, error, 'throws when second value is NaN');
t.end();
});
test('is.within', function (t) {
t.test('throws on NaN', function (st) {
var nanError = new TypeError('NaN is not a valid value');
st['throws'](function () { return is.within(NaN, 0, 0); }, nanError, 'throws when first value is NaN');
st['throws'](function () { return is.within(0, NaN, 0); }, nanError, 'throws when second value is NaN');
st['throws'](function () { return is.within(0, 0, NaN); }, nanError, 'throws when third value is NaN');
st.end();
});
t.test('throws on non-number', function (st) {
var error = new TypeError('all arguments must be numbers');
st['throws'](function () { return is.within('', 0, 0); }, error, 'throws when first value is string');
st['throws'](function () { return is.within(0, '', 0); }, error, 'throws when second value is string');
st['throws'](function () { return is.within(0, 0, ''); }, error, 'throws when third value is string');
st['throws'](function () { return is.within({}, 0, 0); }, error, 'throws when first value is object');
st['throws'](function () { return is.within(0, {}, 0); }, error, 'throws when second value is object');
st['throws'](function () { return is.within(0, 0, {}); }, error, 'throws when third value is object');
st['throws'](function () { return is.within(null, 0, 0); }, error, 'throws when first value is null');
st['throws'](function () { return is.within(0, null, 0); }, error, 'throws when second value is null');
st['throws'](function () { return is.within(0, 0, null); }, error, 'throws when third value is null');
st['throws'](function () { return is.within(undefined, 0, 0); }, error, 'throws when first value is undefined');
st['throws'](function () { return is.within(0, undefined, 0); }, error, 'throws when second value is undefined');
st['throws'](function () { return is.within(0, 0, undefined); }, error, 'throws when third value is undefined');
st.end();
});
t.ok(is.within(2, 1, 3), '2 is between 1 and 3');
t.ok(is.within(0, -1, 1), '0 is between -1 and 1');
t.ok(is.within(2, 0, Infinity), 'infinity always returns true');
t.ok(is.within(2, Infinity, 2), 'infinity always returns true');
t.ok(is.within(Infinity, 0, 1), 'infinity always returns true');
t.notOk(is.within(2, -1, -1), '2 is not between -1 and 1');
t.end();
});
test('is.object', function (t) {
t.ok(is.object({}), 'object literal is object');
t.notOk(is.object(), 'undefined is not an object');
t.notOk(is.object(null), 'null is not an object');
t.notOk(is.object(true), 'true is not an object');
t.notOk(is.object(''), 'string is not an object');
t.notOk(is.object(NaN), 'NaN is not an object');
t.notOk(is.object(Object), 'object constructor is not an object');
t.notOk(is.object(function () {}), 'function is not an object');
t.end();
});
test('is.hash', function (t) {
t.ok(is.hash({}), 'empty object literal is hash');
t.ok(is.hash({ 1: 2, a: 'b' }), 'object literal is hash');
t.notOk(is.hash(), 'undefined is not a hash');
t.notOk(is.hash(null), 'null is not a hash');
t.notOk(is.hash(new Date()), 'date is not a hash');
t.notOk(is.hash(Object('')), 'string object is not a hash');
t.notOk(is.hash(''), 'string literal is not a hash');
t.notOk(is.hash(Object(0)), 'number object is not a hash');
t.notOk(is.hash(1), 'number literal is not a hash');
t.notOk(is.hash(true), 'true is not a hash');
t.notOk(is.hash(false), 'false is not a hash');
t.notOk(is.hash(Object(false)), 'boolean obj is not hash');
t.notOk(is.hash(false), 'literal false is not hash');
t.notOk(is.hash(true), 'literal true is not hash');
t.test('commonJS environment', { skip: typeof module === 'undefined' }, function (st) {
st.ok(is.hash(module.exports), 'module.exports is a hash');
st.end();
});
t.test('browser stuff', { skip: typeof window === 'undefined' }, function (st) {
st.notOk(is.hash(window), 'window is not a hash');
st.notOk(is.hash(document.createElement('div')), 'element is not a hash');
st.end();
});
t.test('node stuff', { skip: typeof process === 'undefined' }, function (st) {
st.notOk(is.hash(global), 'global is not a hash');
st.notOk(is.hash(process), 'process is not a hash');
st.end();
});
t.end();
});
test('is.regexp', function (t) {
t.ok(is.regexp(/a/g), 'regex literal is regex');
t.ok(is.regexp(new RegExp('a', 'g')), 'regex object is regex');
t.notOk(is.regexp(), 'undefined is not regex');
t.notOk(is.regexp(function () {}), 'function is not regex');
t.notOk(is.regexp('/a/g'), 'string regex is not regex');
t.end();
});
test('is.string', function (t) {
t.ok(is.string('foo'), 'string literal is string');
t.ok(is.string(Object('foo')), 'string object is string');
t.notOk(is.string(), 'undefined is not string');
t.notOk(is.string(String), 'string constructor is not string');
var F = function () {};
F.prototype = Object('');
t.notOk(is.string(F), 'string subtype is not string');
t.end();
});
test('is.base64', function (t) {
t.ok(is.base64('wxyzWXYZ/+=='), 'string is base64 encoded');
t.ok(is.base64(''), 'zero length string is base64 encoded');
t.notOk(is.base64('wxyzWXYZ123/+=='), 'string length not a multiple of four is not base64 encoded');
t.notOk(is.base64('wxyzWXYZ1234|]=='), 'string with invalid characters is not base64 encoded');
t.notOk(is.base64('wxyzWXYZ1234==/+'), 'string with = not at end is not base64 encoded');
t.notOk(is.base64('wxyzWXYZ1234/==='), 'string ending with === is not base64 encoded');
t.end();
});
test('is.hex', function (t) {
t.ok(is.hex('abcdABCD1234'), 'string is hex encoded');
t.ok(is.hex(''), 'zero length string is hex encoded');
t.notOk(is.hex('wxyzWXYZ1234/+=='), 'string with invalid characters is not hex encoded');
t.end();
});
test('is.symbol', function (t) {
t.test('not symbols', function (st) {
var notSymbols = [true, false, null, undefined, {}, [], function () {}, 42, NaN, Infinity, /a/g, '', 0, -0, new Error('error')];
forEach(notSymbols, function (notSymbol) {
st.notOk(is.symbol(notSymbol), notSymbol + ' is not symbol');
});
st.end();
});
t.test('symbols', { skip: typeof Symbol !== 'function' }, function (st) {
st.ok(is.symbol(Symbol('foo')), 'Symbol("foo") is symbol');
var notKnownSymbols = ['length', 'name', 'arguments', 'caller', 'prototype', 'for', 'keyFor'];
var symbolKeys = Object.getOwnPropertyNames(Symbol).filter(function (name) {
return notKnownSymbols.indexOf(name) < 0;
});
forEach(symbolKeys, function (symbolKey) {
st.ok(is.symbol(Symbol[symbolKey]), symbolKey + ' is symbol');
});
st.end();
});
t.end();
});

View File

@@ -0,0 +1,92 @@
{
"name": "node.extend",
"version": "1.1.5",
"description": "A port of jQuery.extend that actually works on node.js",
"keywords": [
"extend",
"jQuery",
"jQuery extend",
"clone",
"copy",
"inherit"
],
"author": {
"name": "dreamerslab",
"email": "ben@dreamerslab.com"
},
"dependencies": {
"is": "^3.0.1"
},
"devDependencies": {
"tape": "^4.0.0",
"covert": "^1.1.0",
"jscs": "^1.13.1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/dreamerslab/node.extend.git"
},
"contributors": [
{
"name": "Jordan Harband"
}
],
"main": "index",
"scripts": {
"test": "npm run lint && node test/index.js && npm run coverage-quiet",
"coverage": "covert test/index.js",
"coverage-quiet": "covert test/index.js --quiet",
"lint": "jscs *.js */*.js"
},
"engines": [
"node >= 0.4"
],
"testling": {
"files": "test/index.js",
"browsers": [
"iexplore/6.0..latest",
"firefox/3.0..6.0",
"firefox/15.0..latest",
"firefox/nightly",
"chrome/4.0..10.0",
"chrome/20.0..latest",
"chrome/canary",
"opera/10.0..latest",
"opera/next",
"safari/4.0..latest",
"ipad/6.0..latest",
"iphone/6.0..latest"
]
},
"license": "(MIT OR GPL-2.0)",
"gitHead": "e92f03dc1d62d8d18245a4200720f7e181663c0f",
"bugs": {
"url": "https://github.com/dreamerslab/node.extend/issues"
},
"homepage": "https://github.com/dreamerslab/node.extend#readme",
"_id": "node.extend@1.1.5",
"_shasum": "336bd4d9bf9f8a13028c153e67bf5dc506ac0093",
"_from": "node.extend@>=1.1.2 <1.2.0",
"_npmVersion": "2.10.1",
"_nodeVersion": "2.1.0",
"_npmUser": {
"name": "ljharb",
"email": "ljharb@gmail.com"
},
"dist": {
"shasum": "336bd4d9bf9f8a13028c153e67bf5dc506ac0093",
"tarball": "http://registry.npmjs.org/node.extend/-/node.extend-1.1.5.tgz"
},
"maintainers": [
{
"name": "dreamerslab",
"email": "ben@dreamerslab.com"
},
{
"name": "ljharb",
"email": "ljharb@gmail.com"
}
],
"directories": {},
"_resolved": "https://registry.npmjs.org/node.extend/-/node.extend-1.1.5.tgz"
}

View File

@@ -0,0 +1,499 @@
## Change Log
### v2.58.0 (2015/06/16)
- [#1638](https://github.com/request/request/pull/1638) Use the `extend` module to deep extend in the defaults method (@simov)
- [#1631](https://github.com/request/request/pull/1631) Move tunnel logic into separate module (@simov)
- [#1634](https://github.com/request/request/pull/1634) Fix OAuth query transport_method (@simov)
- [#1603](https://github.com/request/request/pull/1603) Add codecov (@simov)
### v2.57.0 (2015/05/31)
- [#1615](https://github.com/request/request/pull/1615) Replace '.client' with '.socket' as the former was deprecated in 2.2.0. (@ChALkeR)
### v2.56.0 (2015/05/28)
- [#1610](https://github.com/request/request/pull/1610) Bump module dependencies (@simov)
- [#1600](https://github.com/request/request/pull/1600) Extract the querystring logic into separate module (@simov)
- [#1607](https://github.com/request/request/pull/1607) Re-generate certificates (@simov)
- [#1599](https://github.com/request/request/pull/1599) Move getProxyFromURI logic below the check for Invaild URI (#1595) (@simov)
- [#1598](https://github.com/request/request/pull/1598) Fix the way http verbs are defined in order to please intellisense IDEs (@simov, @flannelJesus)
- [#1591](https://github.com/request/request/pull/1591) A few minor fixes: (@simov)
- [#1584](https://github.com/request/request/pull/1584) Refactor test-default tests (according to comments in #1430) (@simov)
- [#1585](https://github.com/request/request/pull/1585) Fixing documentation regarding TLS options (#1583) (@mainakae)
- [#1574](https://github.com/request/request/pull/1574) Refresh the oauth_nonce on redirect (#1573) (@simov)
- [#1570](https://github.com/request/request/pull/1570) Discovered tests that weren't properly running (@seanstrom)
- [#1569](https://github.com/request/request/pull/1569) Fix pause before response arrives (@kevinoid)
- [#1558](https://github.com/request/request/pull/1558) Emit error instead of throw (@simov)
- [#1568](https://github.com/request/request/pull/1568) Fix stall when piping gzipped response (@kevinoid)
- [#1560](https://github.com/request/request/pull/1560) Update combined-stream (@apechimp)
- [#1543](https://github.com/request/request/pull/1543) Initial support for oauth_body_hash on json payloads (@simov, @aesopwolf)
- [#1541](https://github.com/request/request/pull/1541) Fix coveralls (@simov)
- [#1540](https://github.com/request/request/pull/1540) Fix recursive defaults for convenience methods (@simov)
- [#1536](https://github.com/request/request/pull/1536) More eslint style rules (@froatsnook)
- [#1533](https://github.com/request/request/pull/1533) Adding dependency status bar to README.md (@YasharF)
- [#1539](https://github.com/request/request/pull/1539) ensure the latest version of har-validator is included (@ahmadnassri)
- [#1516](https://github.com/request/request/pull/1516) forever+pool test (@devTristan)
### v2.55.0 (2015/04/05)
- [#1520](https://github.com/request/request/pull/1520) Refactor defaults (@simov)
- [#1525](https://github.com/request/request/pull/1525) Delete request headers with undefined value. (@froatsnook)
- [#1521](https://github.com/request/request/pull/1521) Add promise tests (@simov)
- [#1518](https://github.com/request/request/pull/1518) Fix defaults (@simov)
- [#1515](https://github.com/request/request/pull/1515) Allow static invoking of convenience methods (@simov)
- [#1505](https://github.com/request/request/pull/1505) Fix multipart boundary extraction regexp (@simov)
- [#1510](https://github.com/request/request/pull/1510) Fix basic auth form data (@simov)
### v2.54.0 (2015/03/24)
- [#1501](https://github.com/request/request/pull/1501) HTTP Archive 1.2 support (@ahmadnassri)
- [#1486](https://github.com/request/request/pull/1486) Add a test for the forever agent (@akshayp)
- [#1500](https://github.com/request/request/pull/1500) Adding handling for no auth method and null bearer (@philberg)
- [#1498](https://github.com/request/request/pull/1498) Add table of contents in readme (@simov)
- [#1477](https://github.com/request/request/pull/1477) Add support for qs options via qsOptions key (@simov)
- [#1496](https://github.com/request/request/pull/1496) Parameters encoded to base 64 should be decoded as UTF-8, not ASCII. (@albanm)
- [#1494](https://github.com/request/request/pull/1494) Update eslint (@froatsnook)
- [#1474](https://github.com/request/request/pull/1474) Require Colon in Basic Auth (@erykwalder)
- [#1481](https://github.com/request/request/pull/1481) Fix baseUrl and redirections. (@burningtree)
- [#1469](https://github.com/request/request/pull/1469) Feature/base url (@froatsnook)
- [#1459](https://github.com/request/request/pull/1459) Add option to time request/response cycle (including rollup of redirects) (@aaron-em)
- [#1468](https://github.com/request/request/pull/1468) Re-enable io.js/node 0.12 build (@simov, @mikeal, @BBB)
- [#1442](https://github.com/request/request/pull/1442) Fixed the issue with strictSSL tests on 0.12 & io.js by explicitly setting a cipher that matches the cert. (@BBB, @nicolasmccurdy, @simov, @0x4139)
- [#1460](https://github.com/request/request/pull/1460) localAddress or proxy config is lost when redirecting (@simov, @0x4139)
- [#1453](https://github.com/request/request/pull/1453) Test on Node.js 0.12 and io.js with allowed failures (@nicolasmccurdy)
- [#1426](https://github.com/request/request/pull/1426) Fixing tests to pass on io.js and node 0.12 (only test-https.js stiff failing) (@mikeal)
- [#1446](https://github.com/request/request/pull/1446) Missing HTTP referer header with redirects Fixes #1038 (@simov, @guimonz)
- [#1428](https://github.com/request/request/pull/1428) Deprecate Node v0.8.x (@nylen)
- [#1436](https://github.com/request/request/pull/1436) Add ability to set a requester without setting default options (@tikotzky)
- [#1435](https://github.com/request/request/pull/1435) dry up verb methods (@sethpollack)
- [#1423](https://github.com/request/request/pull/1423) Allow fully qualified multipart content-type header (@simov)
- [#1430](https://github.com/request/request/pull/1430) Fix recursive requester (@tikotzky)
- [#1429](https://github.com/request/request/pull/1429) Throw error when making HEAD request with a body (@tikotzky)
- [#1419](https://github.com/request/request/pull/1419) Add note that the project is broken in 0.12.x (@nylen)
- [#1413](https://github.com/request/request/pull/1413) Fix basic auth (@simov)
- [#1397](https://github.com/request/request/pull/1397) Improve pipe-from-file tests (@nylen)
### v2.53.0 (2015/02/02)
- [#1396](https://github.com/request/request/pull/1396) Do not rfc3986 escape JSON bodies (@nylen, @simov)
- [#1392](https://github.com/request/request/pull/1392) Improve `timeout` option description (@watson)
### v2.52.0 (2015/02/02)
- [#1383](https://github.com/request/request/pull/1383) Add missing HTTPS options that were not being passed to tunnel (@brichard19) (@nylen, @brichard19)
- [#1388](https://github.com/request/request/pull/1388) Upgrade mime-types package version (@roderickhsiao)
- [#1389](https://github.com/request/request/pull/1389) Revise Setup Tunnel Function (@seanstrom)
- [#1374](https://github.com/request/request/pull/1374) Allow explicitly disabling tunneling for proxied https destinations (@nylen)
- [#1376](https://github.com/request/request/pull/1376) Use karma-browserify for tests. Add browser test coverage reporter. (@eiriksm)
- [#1366](https://github.com/request/request/pull/1366) Refactor OAuth into separate module (@simov)
- [#1373](https://github.com/request/request/pull/1373) Rewrite tunnel test to be pure Node.js (@nylen)
- [#1371](https://github.com/request/request/pull/1371) Upgrade test reporter (@nylen)
- [#1360](https://github.com/request/request/pull/1360) Refactor basic, bearer, digest auth logic into separate class (@simov)
- [#1354](https://github.com/request/request/pull/1354) Remove circular dependency from debugging code (@nylen)
- [#1351](https://github.com/request/request/pull/1351) Move digest auth into private prototype method (@simov)
- [#1352](https://github.com/request/request/pull/1352) Update hawk dependency to ~2.3.0 (@mridgway)
- [#1353](https://github.com/request/request/pull/1353) Correct travis-ci badge (@dogancelik)
- [#1349](https://github.com/request/request/pull/1349) Make sure we return on errored browser requests. (@eiriksm)
- [#1346](https://github.com/request/request/pull/1346) getProxyFromURI Extraction Refactor (@seanstrom)
- [#1337](https://github.com/request/request/pull/1337) Standardize test ports on 6767 (@nylen)
- [#1341](https://github.com/request/request/pull/1341) Emit FormData error events as Request error events (@nylen, @rwky)
- [#1343](https://github.com/request/request/pull/1343) Clean up readme badges, and add Travis and Coveralls badges (@nylen)
- [#1345](https://github.com/request/request/pull/1345) Update README.md (@Aaron-Hartwig)
- [#1338](https://github.com/request/request/pull/1338) Always wait for server.close() callback in tests (@nylen)
- [#1342](https://github.com/request/request/pull/1342) Add mock https server and redo start of browser tests for this purpose. (@eiriksm)
- [#1339](https://github.com/request/request/pull/1339) Improve auth docs (@nylen)
- [#1335](https://github.com/request/request/pull/1335) Add support for OAuth plaintext signature method (@simov)
- [#1332](https://github.com/request/request/pull/1332) Add clean script to remove test-browser.js after the tests run (@seanstrom)
- [#1327](https://github.com/request/request/pull/1327) Fix errors generating coverage reports. (@nylen)
- [#1330](https://github.com/request/request/pull/1330) Return empty buffer upon empty response body and encoding is set to null (@seanstrom)
- [#1326](https://github.com/request/request/pull/1326) Use faster container-based infrastructure on Travis (@nylen)
- [#1315](https://github.com/request/request/pull/1315) Implement rfc3986 option (@simov, @nylen, @apoco, @DullReferenceException, @mmalecki, @oliamb, @cliffcrosland, @LewisJEllis, @eiriksm, @poislagarde)
- [#1314](https://github.com/request/request/pull/1314) Detect urlencoded form data header via regex (@simov)
- [#1317](https://github.com/request/request/pull/1317) Improve OAuth1.0 server side flow example (@simov)
### v2.51.0 (2014/12/10)
- [#1310](https://github.com/request/request/pull/1310) Revert changes introduced in https://github.com/request/request/pull/1282 (@simov)
### v2.50.0 (2014/12/09)
- [#1308](https://github.com/request/request/pull/1308) Add browser test to keep track of browserify compability. (@eiriksm)
- [#1299](https://github.com/request/request/pull/1299) Add optional support for jsonReviver (@poislagarde)
- [#1277](https://github.com/request/request/pull/1277) Add Coveralls configuration (@simov)
- [#1307](https://github.com/request/request/pull/1307) Upgrade form-data, add back browserify compability. Fixes #455. (@eiriksm)
- [#1305](https://github.com/request/request/pull/1305) Fix typo in README.md (@LewisJEllis)
- [#1288](https://github.com/request/request/pull/1288) Update README.md to explain custom file use case (@cliffcrosland)
### v2.49.0 (2014/11/28)
- [#1295](https://github.com/request/request/pull/1295) fix(proxy): no-proxy false positive (@oliamb)
- [#1292](https://github.com/request/request/pull/1292) Upgrade `caseless` to 0.8.1 (@mmalecki)
- [#1276](https://github.com/request/request/pull/1276) Set transfer encoding for multipart/related to chunked by default (@simov)
- [#1275](https://github.com/request/request/pull/1275) Fix multipart content-type headers detection (@simov)
- [#1269](https://github.com/request/request/pull/1269) adds streams example for review (@tbuchok)
- [#1238](https://github.com/request/request/pull/1238) Add examples README.md (@simov)
### v2.48.0 (2014/11/12)
- [#1263](https://github.com/request/request/pull/1263) Fixed a syntax error / typo in README.md (@xna2)
- [#1253](https://github.com/request/request/pull/1253) Add multipart chunked flag (@simov, @nylen)
- [#1251](https://github.com/request/request/pull/1251) Clarify that defaults() does not modify global defaults (@nylen)
- [#1250](https://github.com/request/request/pull/1250) Improve documentation for pool and maxSockets options (@nylen)
- [#1237](https://github.com/request/request/pull/1237) Documenting error handling when using streams (@vmattos)
- [#1244](https://github.com/request/request/pull/1244) Finalize changelog command (@nylen)
- [#1241](https://github.com/request/request/pull/1241) Fix typo (@alexanderGugel)
- [#1223](https://github.com/request/request/pull/1223) Show latest version number instead of "upcoming" in changelog (@nylen)
- [#1236](https://github.com/request/request/pull/1236) Document how to use custom CA in README (#1229) (@hypesystem)
- [#1228](https://github.com/request/request/pull/1228) Support for oauth with RSA-SHA1 signing (@nylen)
- [#1216](https://github.com/request/request/pull/1216) Made json and multipart options coexist (@nylen, @simov)
- [#1225](https://github.com/request/request/pull/1225) Allow header white/exclusive lists in any case. (@RReverser)
### v2.47.0 (2014/10/26)
- [#1222](https://github.com/request/request/pull/1222) Move from mikeal/request to request/request (@nylen)
- [#1220](https://github.com/request/request/pull/1220) update qs dependency to 2.3.1 (@FredKSchott)
- [#1212](https://github.com/request/request/pull/1212) Improve tests/test-timeout.js (@nylen)
- [#1219](https://github.com/request/request/pull/1219) remove old globalAgent workaround for node 0.4 (@request)
- [#1214](https://github.com/request/request/pull/1214) Remove cruft left over from optional dependencies (@nylen)
- [#1215](https://github.com/request/request/pull/1215) Add proxyHeaderExclusiveList option for proxy-only headers. (@RReverser)
- [#1211](https://github.com/request/request/pull/1211) Allow 'Host' header instead of 'host' and remember case across redirects (@nylen)
- [#1208](https://github.com/request/request/pull/1208) Improve release script (@nylen)
- [#1213](https://github.com/request/request/pull/1213) Support for custom cookie store (@nylen, @mitsuru)
- [#1197](https://github.com/request/request/pull/1197) Clean up some code around setting the agent (@FredKSchott)
- [#1209](https://github.com/request/request/pull/1209) Improve multipart form append test (@simov)
- [#1207](https://github.com/request/request/pull/1207) Update changelog (@nylen)
- [#1185](https://github.com/request/request/pull/1185) Stream multipart/related bodies (@simov)
### v2.46.0 (2014/10/23)
- [#1198](https://github.com/request/request/pull/1198) doc for TLS/SSL protocol options (@shawnzhu)
- [#1200](https://github.com/request/request/pull/1200) Add a Gitter chat badge to README.md (@gitter-badger)
- [#1196](https://github.com/request/request/pull/1196) Upgrade taper test reporter to v0.3.0 (@nylen)
- [#1199](https://github.com/request/request/pull/1199) Fix lint error: undeclared var i (@nylen)
- [#1191](https://github.com/request/request/pull/1191) Move self.proxy decision logic out of init and into a helper (@FredKSchott)
- [#1190](https://github.com/request/request/pull/1190) Move _buildRequest() logic back into init (@FredKSchott)
- [#1186](https://github.com/request/request/pull/1186) Support Smarter Unix URL Scheme (@FredKSchott)
- [#1178](https://github.com/request/request/pull/1178) update form documentation for new usage (@FredKSchott)
- [#1180](https://github.com/request/request/pull/1180) Enable no-mixed-requires linting rule (@nylen)
- [#1184](https://github.com/request/request/pull/1184) Don't forward authorization header across redirects to different hosts (@nylen)
- [#1183](https://github.com/request/request/pull/1183) Correct README about pre and postamble CRLF using multipart and not mult... (@netpoetica)
- [#1179](https://github.com/request/request/pull/1179) Lint tests directory (@nylen)
- [#1169](https://github.com/request/request/pull/1169) add metadata for form-data file field (@dotcypress)
- [#1173](https://github.com/request/request/pull/1173) remove optional dependencies (@seanstrom)
- [#1165](https://github.com/request/request/pull/1165) Cleanup event listeners and remove function creation from init (@FredKSchott)
- [#1174](https://github.com/request/request/pull/1174) update the request.cookie docs to have a valid cookie example (@seanstrom)
- [#1168](https://github.com/request/request/pull/1168) create a detach helper and use detach helper in replace of nextTick (@seanstrom)
- [#1171](https://github.com/request/request/pull/1171) in post can send form data and use callback (@MiroRadenovic)
- [#1159](https://github.com/request/request/pull/1159) accept charset for x-www-form-urlencoded content-type (@seanstrom)
- [#1157](https://github.com/request/request/pull/1157) Update README.md: body with json=true (@Rob--W)
- [#1164](https://github.com/request/request/pull/1164) Disable tests/test-timeout.js on Travis (@nylen)
- [#1153](https://github.com/request/request/pull/1153) Document how to run a single test (@nylen)
- [#1144](https://github.com/request/request/pull/1144) adds documentation for the "response" event within the streaming section (@tbuchok)
- [#1162](https://github.com/request/request/pull/1162) Update eslintrc file to no longer allow past errors (@FredKSchott)
- [#1155](https://github.com/request/request/pull/1155) Support/use self everywhere (@seanstrom)
- [#1161](https://github.com/request/request/pull/1161) fix no-use-before-define lint warnings (@emkay)
- [#1156](https://github.com/request/request/pull/1156) adding curly brackets to get rid of lint errors (@emkay)
- [#1151](https://github.com/request/request/pull/1151) Fix localAddress test on OS X (@nylen)
- [#1145](https://github.com/request/request/pull/1145) documentation: fix outdated reference to setCookieSync old name in README (@FredKSchott)
- [#1131](https://github.com/request/request/pull/1131) Update pool documentation (@FredKSchott)
- [#1143](https://github.com/request/request/pull/1143) Rewrite all tests to use tape (@nylen)
- [#1137](https://github.com/request/request/pull/1137) Add ability to specifiy querystring lib in options. (@jgrund)
- [#1138](https://github.com/request/request/pull/1138) allow hostname and port in place of host on uri (@cappslock)
- [#1134](https://github.com/request/request/pull/1134) Fix multiple redirects and `self.followRedirect` (@blakeembrey)
- [#1130](https://github.com/request/request/pull/1130) documentation fix: add note about npm test for contributing (@FredKSchott)
- [#1120](https://github.com/request/request/pull/1120) Support/refactor request setup tunnel (@seanstrom)
- [#1129](https://github.com/request/request/pull/1129) linting fix: convert double quote strings to use single quotes (@FredKSchott)
- [#1124](https://github.com/request/request/pull/1124) linting fix: remove unneccesary semi-colons (@FredKSchott)
### v2.45.0 (2014/10/06)
- [#1128](https://github.com/request/request/pull/1128) Add test for setCookie regression (@nylen)
- [#1127](https://github.com/request/request/pull/1127) added tests around using objects as values in a query string (@bcoe)
- [#1103](https://github.com/request/request/pull/1103) Support/refactor request constructor (@nylen, @seanstrom)
- [#1119](https://github.com/request/request/pull/1119) add basic linting to request library (@FredKSchott)
- [#1121](https://github.com/request/request/pull/1121) Revert "Explicitly use sync versions of cookie functions" (@nylen)
- [#1118](https://github.com/request/request/pull/1118) linting fix: Restructure bad empty if statement (@FredKSchott)
- [#1117](https://github.com/request/request/pull/1117) Fix a bad check for valid URIs (@FredKSchott)
- [#1113](https://github.com/request/request/pull/1113) linting fix: space out operators (@FredKSchott)
- [#1116](https://github.com/request/request/pull/1116) Fix typo in `noProxyHost` definition (@FredKSchott)
- [#1114](https://github.com/request/request/pull/1114) linting fix: Added a `new` operator that was missing when creating and throwing a new error (@FredKSchott)
- [#1096](https://github.com/request/request/pull/1096) No_proxy support (@samcday)
- [#1107](https://github.com/request/request/pull/1107) linting-fix: remove unused variables (@FredKSchott)
- [#1112](https://github.com/request/request/pull/1112) linting fix: Make return values consistent and more straitforward (@FredKSchott)
- [#1111](https://github.com/request/request/pull/1111) linting fix: authPieces was getting redeclared (@FredKSchott)
- [#1105](https://github.com/request/request/pull/1105) Use strict mode in request (@FredKSchott)
- [#1110](https://github.com/request/request/pull/1110) linting fix: replace lazy '==' with more strict '===' (@FredKSchott)
- [#1109](https://github.com/request/request/pull/1109) linting fix: remove function call from if-else conditional statement (@FredKSchott)
- [#1102](https://github.com/request/request/pull/1102) Fix to allow setting a `requester` on recursive calls to `request.defaults` (@tikotzky)
- [#1095](https://github.com/request/request/pull/1095) Tweaking engines in package.json (@pdehaan)
- [#1082](https://github.com/request/request/pull/1082) Forward the socket event from the httpModule request (@seanstrom)
- [#972](https://github.com/request/request/pull/972) Clarify gzip handling in the README (@kevinoid)
- [#1089](https://github.com/request/request/pull/1089) Mention that encoding defaults to utf8, not Buffer (@stuartpb)
- [#1088](https://github.com/request/request/pull/1088) Fix cookie example in README.md and make it more clear (@pipi32167)
- [#1027](https://github.com/request/request/pull/1027) Add support for multipart form data in request options. (@crocket)
- [#1076](https://github.com/request/request/pull/1076) use Request.abort() to abort the request when the request has timed-out (@seanstrom)
- [#1068](https://github.com/request/request/pull/1068) add optional postamble required by .NET multipart requests (@netpoetica)
### v2.43.0 (2014/09/18)
- [#1057](https://github.com/request/request/pull/1057) Defaults should not overwrite defined options (@davidwood)
- [#1046](https://github.com/request/request/pull/1046) Propagate datastream errors, useful in case gzip fails. (@ZJONSSON, @Janpot)
- [#1063](https://github.com/request/request/pull/1063) copy the input headers object #1060 (@finnp)
- [#1031](https://github.com/request/request/pull/1031) Explicitly use sync versions of cookie functions (@ZJONSSON)
- [#1056](https://github.com/request/request/pull/1056) Fix redirects when passing url.parse(x) as URL to convenience method (@nylen)
### v2.42.0 (2014/09/04)
- [#1053](https://github.com/request/request/pull/1053) Fix #1051 Parse auth properly when using non-tunneling proxy (@isaacs)
### v2.41.0 (2014/09/04)
- [#1050](https://github.com/request/request/pull/1050) Pass whitelisted headers to tunneling proxy. Organize all tunneling logic. (@isaacs, @Feldhacker)
- [#1035](https://github.com/request/request/pull/1035) souped up nodei.co badge (@rvagg)
- [#1048](https://github.com/request/request/pull/1048) Aws is now possible over a proxy (@steven-aerts)
- [#1039](https://github.com/request/request/pull/1039) extract out helper functions to a helper file (@seanstrom)
- [#1021](https://github.com/request/request/pull/1021) Support/refactor indexjs (@seanstrom)
- [#1033](https://github.com/request/request/pull/1033) Improve and document debug options (@nylen)
- [#1034](https://github.com/request/request/pull/1034) Fix readme headings (@nylen)
- [#1030](https://github.com/request/request/pull/1030) Allow recursive request.defaults (@tikotzky)
- [#1029](https://github.com/request/request/pull/1029) Fix a couple of typos (@nylen)
- [#675](https://github.com/request/request/pull/675) Checking for SSL fault on connection before reading SSL properties (@VRMink)
- [#989](https://github.com/request/request/pull/989) Added allowRedirect function. Should return true if redirect is allowed or false otherwise (@doronin)
- [#1025](https://github.com/request/request/pull/1025) [fixes #1023] Set self._ended to true once response has ended (@mridgway)
- [#1020](https://github.com/request/request/pull/1020) Add back removed debug metadata (@FredKSchott)
- [#1008](https://github.com/request/request/pull/1008) Moving to module instead of cutomer buffer concatenation. (@mikeal)
- [#770](https://github.com/request/request/pull/770) Added dependency badge for README file; (@timgluz, @mafintosh, @lalitkapoor, @stash, @bobyrizov)
- [#1016](https://github.com/request/request/pull/1016) toJSON no longer results in an infinite loop, returns simple objects (@FredKSchott)
- [#1018](https://github.com/request/request/pull/1018) Remove pre-0.4.4 HTTPS fix (@mmalecki)
- [#1006](https://github.com/request/request/pull/1006) Migrate to caseless, fixes #1001 (@mikeal)
- [#995](https://github.com/request/request/pull/995) Fix parsing array of objects (@sjonnet19)
- [#999](https://github.com/request/request/pull/999) Fix fallback for browserify for optional modules. (@eiriksm)
- [#996](https://github.com/request/request/pull/996) Wrong oauth signature when multiple same param keys exist [updated] (@bengl, @hyjin)
### v2.40.0 (2014/08/06)
- [#992](https://github.com/request/request/pull/992) Fix security vulnerability. Update qs (@poeticninja)
- [#988](https://github.com/request/request/pull/988) “--” -> “—” (@upisfree)
- [#987](https://github.com/request/request/pull/987) Show optional modules as being loaded by the module that reqeusted them (@iarna)
### v2.39.0 (2014/07/24)
- [#976](https://github.com/request/request/pull/976) Update README.md (@pvoznenko)
### v2.38.0 (2014/07/22)
- [#952](https://github.com/request/request/pull/952) Adding support to client certificate with proxy use case (@ofirshaked)
- [#884](https://github.com/request/request/pull/884) Documented tough-cookie installation. (@wbyoung)
- [#935](https://github.com/request/request/pull/935) Correct repository url (@fritx)
- [#963](https://github.com/request/request/pull/963) Update changelog (@nylen)
- [#960](https://github.com/request/request/pull/960) Support gzip with encoding on node pre-v0.9.4 (@kevinoid)
- [#953](https://github.com/request/request/pull/953) Add async Content-Length computation when using form-data (@LoicMahieu)
- [#844](https://github.com/request/request/pull/844) Add support for HTTP[S]_PROXY environment variables. Fixes #595. (@jvmccarthy)
- [#946](https://github.com/request/request/pull/946) defaults: merge headers (@aj0strow)
### v2.37.0 (2014/07/07)
- [#957](https://github.com/request/request/pull/957) Silence EventEmitter memory leak warning #311 (@watson)
- [#955](https://github.com/request/request/pull/955) check for content-length header before setting it in nextTick (@camilleanne)
- [#951](https://github.com/request/request/pull/951) Add support for gzip content decoding (@kevinoid)
- [#949](https://github.com/request/request/pull/949) Manually enter querystring in form option (@charlespwd)
- [#944](https://github.com/request/request/pull/944) Make request work with browserify (@eiriksm)
- [#943](https://github.com/request/request/pull/943) New mime module (@eiriksm)
- [#927](https://github.com/request/request/pull/927) Bump version of hawk dep. (@samccone)
- [#907](https://github.com/request/request/pull/907) append secureOptions to poolKey (@medovob)
### v2.35.0 (2014/05/17)
- [#901](https://github.com/request/request/pull/901) Fixes #555 (@pigulla)
- [#897](https://github.com/request/request/pull/897) merge with default options (@vohof)
- [#891](https://github.com/request/request/pull/891) fixes 857 - options object is mutated by calling request (@lalitkapoor)
- [#869](https://github.com/request/request/pull/869) Pipefilter test (@tgohn)
- [#866](https://github.com/request/request/pull/866) Fix typo (@dandv)
- [#861](https://github.com/request/request/pull/861) Add support for RFC 6750 Bearer Tokens (@phedny)
- [#809](https://github.com/request/request/pull/809) upgrade tunnel-proxy to 0.4.0 (@ksato9700)
- [#850](https://github.com/request/request/pull/850) Fix word consistency in readme (@0xNobody)
- [#810](https://github.com/request/request/pull/810) add some exposition to mpu example in README.md (@mikermcneil)
- [#840](https://github.com/request/request/pull/840) improve error reporting for invalid protocols (@FND)
- [#821](https://github.com/request/request/pull/821) added secureOptions back (@nw)
- [#815](https://github.com/request/request/pull/815) Create changelog based on pull requests (@lalitkapoor)
### v2.34.0 (2014/02/18)
- [#516](https://github.com/request/request/pull/516) UNIX Socket URL Support (@lyuzashi)
- [#801](https://github.com/request/request/pull/801) 794 ignore cookie parsing and domain errors (@lalitkapoor)
- [#802](https://github.com/request/request/pull/802) Added the Apache license to the package.json. (@keskival)
- [#793](https://github.com/request/request/pull/793) Adds content-length calculation when submitting forms using form-data li... (@Juul)
- [#785](https://github.com/request/request/pull/785) Provide ability to override content-type when `json` option used (@vvo)
- [#781](https://github.com/request/request/pull/781) simpler isReadStream function (@joaojeronimo)
### v2.32.0 (2014/01/16)
- [#767](https://github.com/request/request/pull/767) Use tough-cookie CookieJar sync API (@stash)
- [#764](https://github.com/request/request/pull/764) Case-insensitive authentication scheme (@bobyrizov)
- [#763](https://github.com/request/request/pull/763) Upgrade tough-cookie to 0.10.0 (@stash)
- [#744](https://github.com/request/request/pull/744) Use Cookie.parse (@lalitkapoor)
- [#757](https://github.com/request/request/pull/757) require aws-sign2 (@mafintosh)
### v2.31.0 (2014/01/08)
- [#645](https://github.com/request/request/pull/645) update twitter api url to v1.1 (@mick)
- [#746](https://github.com/request/request/pull/746) README: Markdown code highlight (@weakish)
- [#745](https://github.com/request/request/pull/745) updating setCookie example to make it clear that the callback is required (@emkay)
- [#742](https://github.com/request/request/pull/742) Add note about JSON output body type (@iansltx)
- [#741](https://github.com/request/request/pull/741) README example is using old cookie jar api (@emkay)
- [#736](https://github.com/request/request/pull/736) Fix callback arguments documentation (@mmalecki)
### v2.30.0 (2013/12/13)
- [#732](https://github.com/request/request/pull/732) JSHINT: Creating global 'for' variable. Should be 'for (var ...'. (@Fritz-Lium)
- [#730](https://github.com/request/request/pull/730) better HTTP DIGEST support (@dai-shi)
- [#728](https://github.com/request/request/pull/728) Fix TypeError when calling request.cookie (@scarletmeow)
### v2.29.0 (2013/12/06)
- [#727](https://github.com/request/request/pull/727) fix requester bug (@jchris)
### v2.28.0 (2013/12/04)
- [#724](https://github.com/request/request/pull/724) README.md: add custom HTTP Headers example. (@tcort)
- [#719](https://github.com/request/request/pull/719) Made a comment gender neutral. (@unsetbit)
- [#715](https://github.com/request/request/pull/715) Request.multipart no longer crashes when header 'Content-type' present (@pastaclub)
- [#710](https://github.com/request/request/pull/710) Fixing listing in callback part of docs. (@lukasz-zak)
- [#696](https://github.com/request/request/pull/696) Edited README.md for formatting and clarity of phrasing (@Zearin)
- [#694](https://github.com/request/request/pull/694) Typo in README (@VRMink)
- [#690](https://github.com/request/request/pull/690) Handle blank password in basic auth. (@diversario)
- [#682](https://github.com/request/request/pull/682) Optional dependencies (@Turbo87)
- [#683](https://github.com/request/request/pull/683) Travis CI support (@Turbo87)
- [#674](https://github.com/request/request/pull/674) change cookie module,to tough-cookie.please check it . (@sxyizhiren)
- [#666](https://github.com/request/request/pull/666) make `ciphers` and `secureProtocol` to work in https request (@richarddong)
- [#656](https://github.com/request/request/pull/656) Test case for #304. (@diversario)
- [#662](https://github.com/request/request/pull/662) option.tunnel to explicitly disable tunneling (@seanmonstar)
- [#659](https://github.com/request/request/pull/659) fix failure when running with NODE_DEBUG=request, and a test for that (@jrgm)
- [#630](https://github.com/request/request/pull/630) Send random cnonce for HTTP Digest requests (@wprl)
### v2.27.0 (2013/08/15)
- [#619](https://github.com/request/request/pull/619) decouple things a bit (@joaojeronimo)
### v2.26.0 (2013/08/07)
- [#613](https://github.com/request/request/pull/613) Fixes #583, moved initialization of self.uri.pathname (@lexander)
- [#605](https://github.com/request/request/pull/605) Only include ":" + pass in Basic Auth if it's defined (fixes #602) (@bendrucker)
### v2.24.0 (2013/07/23)
- [#596](https://github.com/request/request/pull/596) Global agent is being used when pool is specified (@Cauldrath)
- [#594](https://github.com/request/request/pull/594) Emit complete event when there is no callback (@RomainLK)
- [#601](https://github.com/request/request/pull/601) Fixed a small typo (@michalstanko)
### v2.23.0 (2013/07/23)
- [#589](https://github.com/request/request/pull/589) Prevent setting headers after they are sent (@geek)
- [#587](https://github.com/request/request/pull/587) Global cookie jar disabled by default (@threepointone)
### v2.22.0 (2013/07/05)
- [#544](https://github.com/request/request/pull/544) Update http-signature version. (@davidlehn)
- [#581](https://github.com/request/request/pull/581) Fix spelling of "ignoring." (@bigeasy)
- [#568](https://github.com/request/request/pull/568) use agentOptions to create agent when specified in request (@SamPlacette)
- [#564](https://github.com/request/request/pull/564) Fix redirections (@criloz)
- [#541](https://github.com/request/request/pull/541) The exported request function doesn't have an auth method (@tschaub)
- [#542](https://github.com/request/request/pull/542) Expose Request class (@regality)
### v2.21.0 (2013/04/30)
- [#536](https://github.com/request/request/pull/536) Allow explicitly empty user field for basic authentication. (@mikeando)
- [#532](https://github.com/request/request/pull/532) fix typo (@fredericosilva)
- [#497](https://github.com/request/request/pull/497) Added redirect event (@Cauldrath)
- [#503](https://github.com/request/request/pull/503) Fix basic auth for passwords that contain colons (@tonistiigi)
- [#521](https://github.com/request/request/pull/521) Improving test-localAddress.js (@noway421)
- [#529](https://github.com/request/request/pull/529) dependencies versions bump (@jodaka)
### v2.17.0 (2013/04/22)
- [#523](https://github.com/request/request/pull/523) Updating dependencies (@noway421)
- [#520](https://github.com/request/request/pull/520) Fixing test-tunnel.js (@noway421)
- [#519](https://github.com/request/request/pull/519) Update internal path state on post-creation QS changes (@jblebrun)
- [#510](https://github.com/request/request/pull/510) Add HTTP Signature support. (@davidlehn)
- [#502](https://github.com/request/request/pull/502) Fix POST (and probably other) requests that are retried after 401 Unauthorized (@nylen)
- [#508](https://github.com/request/request/pull/508) Honor the .strictSSL option when using proxies (tunnel-agent) (@jhs)
- [#512](https://github.com/request/request/pull/512) Make password optional to support the format: http://username@hostname/ (@pajato1)
- [#513](https://github.com/request/request/pull/513) add 'localAddress' support (@yyfrankyy)
- [#498](https://github.com/request/request/pull/498) Moving response emit above setHeaders on destination streams (@kenperkins)
- [#490](https://github.com/request/request/pull/490) Empty response body (3-rd argument) must be passed to callback as an empty string (@Olegas)
- [#479](https://github.com/request/request/pull/479) Changing so if Accept header is explicitly set, sending json does not ov... (@RoryH)
- [#475](https://github.com/request/request/pull/475) Use `unescape` from `querystring` (@shimaore)
- [#473](https://github.com/request/request/pull/473) V0.10 compat (@isaacs)
- [#471](https://github.com/request/request/pull/471) Using querystring library from visionmedia (@kbackowski)
- [#461](https://github.com/request/request/pull/461) Strip the UTF8 BOM from a UTF encoded response (@kppullin)
- [#460](https://github.com/request/request/pull/460) hawk 0.10.0 (@hueniverse)
- [#462](https://github.com/request/request/pull/462) if query params are empty, then request path shouldn't end with a '?' (merges cleanly now) (@jaipandya)
- [#456](https://github.com/request/request/pull/456) hawk 0.9.0 (@hueniverse)
- [#429](https://github.com/request/request/pull/429) Copy options before adding callback. (@nrn, @nfriedly, @youurayy, @jplock, @kapetan, @landeiro, @othiym23, @mmalecki)
- [#454](https://github.com/request/request/pull/454) Destroy the response if present when destroying the request (clean merge) (@mafintosh)
- [#310](https://github.com/request/request/pull/310) Twitter Oauth Stuff Out of Date; Now Updated (@joemccann, @isaacs, @mscdex)
- [#413](https://github.com/request/request/pull/413) rename googledoodle.png to .jpg (@nfriedly, @youurayy, @jplock, @kapetan, @landeiro, @othiym23, @mmalecki)
- [#448](https://github.com/request/request/pull/448) Convenience method for PATCH (@mloar)
- [#444](https://github.com/request/request/pull/444) protect against double callbacks on error path (@spollack)
- [#433](https://github.com/request/request/pull/433) Added support for HTTPS cert & key (@mmalecki)
- [#430](https://github.com/request/request/pull/430) Respect specified {Host,host} headers, not just {host} (@andrewschaaf)
- [#415](https://github.com/request/request/pull/415) Fixed a typo. (@jerem)
- [#338](https://github.com/request/request/pull/338) Add more auth options, including digest support (@nylen)
- [#403](https://github.com/request/request/pull/403) Optimize environment lookup to happen once only (@mmalecki)
- [#398](https://github.com/request/request/pull/398) Add more reporting to tests (@mmalecki)
- [#388](https://github.com/request/request/pull/388) Ensure "safe" toJSON doesn't break EventEmitters (@othiym23)
- [#381](https://github.com/request/request/pull/381) Resolving "Invalid signature. Expected signature base string: " (@landeiro)
- [#380](https://github.com/request/request/pull/380) Fixes missing host header on retried request when using forever agent (@mac-)
- [#376](https://github.com/request/request/pull/376) Headers lost on redirect (@kapetan)
- [#375](https://github.com/request/request/pull/375) Fix for missing oauth_timestamp parameter (@jplock)
- [#374](https://github.com/request/request/pull/374) Correct Host header for proxy tunnel CONNECT (@youurayy)
- [#370](https://github.com/request/request/pull/370) Twitter reverse auth uses x_auth_mode not x_auth_type (@drudge)
- [#369](https://github.com/request/request/pull/369) Don't remove x_auth_mode for Twitter reverse auth (@drudge)
- [#344](https://github.com/request/request/pull/344) Make AWS auth signing find headers correctly (@nlf)
- [#363](https://github.com/request/request/pull/363) rfc3986 on base_uri, now passes tests (@jeffmarshall)
- [#362](https://github.com/request/request/pull/362) Running `rfc3986` on `base_uri` in `oauth.hmacsign` instead of just `encodeURIComponent` (@jeffmarshall)
- [#361](https://github.com/request/request/pull/361) Don't create a Content-Length header if we already have it set (@danjenkins)
- [#360](https://github.com/request/request/pull/360) Delete self._form along with everything else on redirect (@jgautier)
- [#355](https://github.com/request/request/pull/355) stop sending erroneous headers on redirected requests (@azylman)
- [#332](https://github.com/request/request/pull/332) Fix #296 - Only set Content-Type if body exists (@Marsup)
- [#343](https://github.com/request/request/pull/343) Allow AWS to work in more situations, added a note in the README on its usage (@nlf)
- [#320](https://github.com/request/request/pull/320) request.defaults() doesn't need to wrap jar() (@StuartHarris)
- [#322](https://github.com/request/request/pull/322) Fix + test for piped into request bumped into redirect. #321 (@alexindigo)
- [#326](https://github.com/request/request/pull/326) Do not try to remove listener from an undefined connection (@strk)
- [#318](https://github.com/request/request/pull/318) Pass servername to tunneling secure socket creation (@isaacs)
- [#317](https://github.com/request/request/pull/317) Workaround for #313 (@isaacs)
- [#293](https://github.com/request/request/pull/293) Allow parser errors to bubble up to request (@mscdex)
- [#290](https://github.com/request/request/pull/290) A test for #289 (@isaacs)
- [#280](https://github.com/request/request/pull/280) Like in node.js print options if NODE_DEBUG contains the word request (@Filirom1)
- [#207](https://github.com/request/request/pull/207) Fix #206 Change HTTP/HTTPS agent when redirecting between protocols (@isaacs)
- [#214](https://github.com/request/request/pull/214) documenting additional behavior of json option (@jphaas)
- [#272](https://github.com/request/request/pull/272) Boundary begins with CRLF? (@elspoono, @timshadel, @naholyr, @nanodocumet, @TehShrike)
- [#284](https://github.com/request/request/pull/284) Remove stray `console.log()` call in multipart generator. (@bcherry)
- [#241](https://github.com/request/request/pull/241) Composability updates suggested by issue #239 (@polotek)
- [#282](https://github.com/request/request/pull/282) OAuth Authorization header contains non-"oauth_" parameters (@jplock)
- [#279](https://github.com/request/request/pull/279) fix tests with boundary by injecting boundry from header (@benatkin)
- [#273](https://github.com/request/request/pull/273) Pipe back pressure issue (@mafintosh)
- [#268](https://github.com/request/request/pull/268) I'm not OCD seriously (@TehShrike)
- [#263](https://github.com/request/request/pull/263) Bug in OAuth key generation for sha1 (@nanodocumet)
- [#265](https://github.com/request/request/pull/265) uncaughtException when redirected to invalid URI (@naholyr)
- [#262](https://github.com/request/request/pull/262) JSON test should check for equality (@timshadel)
- [#261](https://github.com/request/request/pull/261) Setting 'pool' to 'false' does NOT disable Agent pooling (@timshadel)
- [#249](https://github.com/request/request/pull/249) Fix for the fix of your (closed) issue #89 where self.headers[content-length] is set to 0 for all methods (@sethbridges, @polotek, @zephrax, @jeromegn)
- [#255](https://github.com/request/request/pull/255) multipart allow body === '' ( the empty string ) (@Filirom1)
- [#260](https://github.com/request/request/pull/260) fixed just another leak of 'i' (@sreuter)
- [#246](https://github.com/request/request/pull/246) Fixing the set-cookie header (@jeromegn)
- [#243](https://github.com/request/request/pull/243) Dynamic boundary (@zephrax)
- [#240](https://github.com/request/request/pull/240) don't error when null is passed for options (@polotek)
- [#211](https://github.com/request/request/pull/211) Replace all occurrences of special chars in RFC3986 (@chriso)
- [#224](https://github.com/request/request/pull/224) Multipart content-type change (@janjongboom)
- [#217](https://github.com/request/request/pull/217) need to use Authorization (titlecase) header with Tumblr OAuth (@visnup)
- [#203](https://github.com/request/request/pull/203) Fix cookie and redirect bugs and add auth support for HTTPS tunnel (@milewise)
- [#199](https://github.com/request/request/pull/199) Tunnel (@isaacs)
- [#198](https://github.com/request/request/pull/198) Bugfix on forever usage of util.inherits (@isaacs)
- [#197](https://github.com/request/request/pull/197) Make ForeverAgent work with HTTPS (@isaacs)
- [#193](https://github.com/request/request/pull/193) Fixes GH-119 (@goatslacker)
- [#188](https://github.com/request/request/pull/188) Add abort support to the returned request (@itay)
- [#176](https://github.com/request/request/pull/176) Querystring option (@csainty)
- [#182](https://github.com/request/request/pull/182) Fix request.defaults to support (uri, options, callback) api (@twilson63)
- [#180](https://github.com/request/request/pull/180) Modified the post, put, head and del shortcuts to support uri optional param (@twilson63)
- [#179](https://github.com/request/request/pull/179) fix to add opts in .pipe(stream, opts) (@substack)
- [#177](https://github.com/request/request/pull/177) Issue #173 Support uri as first and optional config as second argument (@twilson63)
- [#170](https://github.com/request/request/pull/170) can't create a cookie in a wrapped request (defaults) (@fabianonunes)
- [#168](https://github.com/request/request/pull/168) Picking off an EasyFix by adding some missing mimetypes. (@serby)
- [#161](https://github.com/request/request/pull/161) Fix cookie jar/headers.cookie collision (#125) (@papandreou)
- [#162](https://github.com/request/request/pull/162) Fix issue #159 (@dpetukhov)
- [#90](https://github.com/request/request/pull/90) add option followAllRedirects to follow post/put redirects (@jroes)
- [#148](https://github.com/request/request/pull/148) Retry Agent (@thejh)
- [#146](https://github.com/request/request/pull/146) Multipart should respect content-type if previously set (@apeace)
- [#144](https://github.com/request/request/pull/144) added "form" option to readme (@petejkim)
- [#133](https://github.com/request/request/pull/133) Fixed cookies parsing (@afanasy)
- [#135](https://github.com/request/request/pull/135) host vs hostname (@iangreenleaf)
- [#132](https://github.com/request/request/pull/132) return the body as a Buffer when encoding is set to null (@jahewson)
- [#112](https://github.com/request/request/pull/112) Support using a custom http-like module (@jhs)
- [#104](https://github.com/request/request/pull/104) Cookie handling contains bugs (@janjongboom)
- [#121](https://github.com/request/request/pull/121) Another patch for cookie handling regression (@jhurliman)
- [#117](https://github.com/request/request/pull/117) Remove the global `i` (@3rd-Eden)
- [#110](https://github.com/request/request/pull/110) Update to Iris Couch URL (@jhs)
- [#86](https://github.com/request/request/pull/86) Can't post binary to multipart requests (@developmentseed)
- [#105](https://github.com/request/request/pull/105) added test for proxy option. (@dominictarr)
- [#102](https://github.com/request/request/pull/102) Implemented cookies - closes issue 82: https://github.com/mikeal/request/issues/82 (@alessioalex)
- [#97](https://github.com/request/request/pull/97) Typo in previous pull causes TypeError in non-0.5.11 versions (@isaacs)
- [#96](https://github.com/request/request/pull/96) Authless parsed url host support (@isaacs)
- [#81](https://github.com/request/request/pull/81) Enhance redirect handling (@danmactough)
- [#78](https://github.com/request/request/pull/78) Don't try to do strictSSL for non-ssl connections (@isaacs)
- [#76](https://github.com/request/request/pull/76) Bug when a request fails and a timeout is set (@Marsup)
- [#70](https://github.com/request/request/pull/70) add test script to package.json (@isaacs, @aheckmann)
- [#73](https://github.com/request/request/pull/73) Fix #71 Respect the strictSSL flag (@isaacs)
- [#69](https://github.com/request/request/pull/69) Flatten chunked requests properly (@isaacs)
- [#67](https://github.com/request/request/pull/67) fixed global variable leaks (@aheckmann)
- [#66](https://github.com/request/request/pull/66) Do not overwrite established content-type headers for read stream deliver (@voodootikigod)
- [#53](https://github.com/request/request/pull/53) Parse json: Issue #51 (@benatkin)
- [#45](https://github.com/request/request/pull/45) Added timeout option (@mbrevoort)
- [#35](https://github.com/request/request/pull/35) The "end" event isn't emitted for some responses (@voxpelli)
- [#31](https://github.com/request/request/pull/31) Error on piping a request to a destination (@tobowers)

View File

@@ -0,0 +1,44 @@
# This is an OPEN Open Source Project
-----------------------------------------
## What?
Individuals making significant and valuable contributions are given
commit-access to the project to contribute as they see fit. This project is
more like an open wiki than a standard guarded open source project.
## Rules
There are a few basic ground-rules for contributors:
1. **No `--force` pushes** or modifying the Git history in any way.
1. **Non-master branches** ought to be used for ongoing work.
1. **External API changes and significant modifications** ought to be subject
to an **internal pull-request** to solicit feedback from other contributors.
1. Internal pull-requests to solicit feedback are *encouraged* for any other
non-trivial contribution but left to the discretion of the contributor.
1. For significant changes wait a full 24 hours before merging so that active
contributors who are distributed throughout the world have a chance to weigh
in.
1. Contributors should attempt to adhere to the prevailing code-style.
1. Run `npm test` locally before submitting your PR, to catch any easy to miss
style & testing issues. To diagnose test failures, there are two ways to
run a single test file:
- `node_modules/.bin/taper tests/test-file.js` - run using the default
[`taper`](https://github.com/nylen/taper) test reporter.
- `node tests/test-file.js` - view the raw
[tap](https://testanything.org/) output.
## Releases
Declaring formal releases remains the prerogative of the project maintainer.
## Changes to this arrangement
This is an experiment and feedback is welcome! This document may also be
subject to pull-requests or changes by contributors where you believe you have
something valuable to add or change.
-----------------------------------------

View File

@@ -0,0 +1,55 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,36 @@
# http://www.appveyor.com/docs/appveyor-yml
# Fix line endings in Windows. (runs before repo cloning)
init:
- git config --global core.autocrlf input
# Test against these versions of Node.js.
environment:
matrix:
- nodejs_version: "0.10"
- nodejs_version: "0.8"
- nodejs_version: "0.11"
# Allow failing jobs for bleeding-edge Node.js versions.
matrix:
allow_failures:
- nodejs_version: "0.11"
# Install scripts. (runs after repo cloning)
install:
# Get the latest stable version of Node 0.STABLE.latest
- ps: Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version)
# Typical npm stuff.
- npm install
# Post-install test scripts.
test_script:
# Output useful info for debugging.
- ps: "npm test # PowerShell" # Pass comment to PS for easier debugging
- cmd: npm test
# Don't actually build.
build: off
# Set build version format here instead of in the admin panel.
version: "{build}"

View File

@@ -0,0 +1,115 @@
# Authentication
## OAuth
### OAuth1.0 Refresh Token
- http://oauth.googlecode.com/svn/spec/ext/session/1.0/drafts/1/spec.html#anchor4
- https://developer.yahoo.com/oauth/guide/oauth-refreshaccesstoken.html
```js
request.post('https://api.login.yahoo.com/oauth/v2/get_token', {
oauth: {
consumer_key: '...',
consumer_secret: '...',
token: '...',
token_secret: '...',
session_handle: '...'
}
}, function (err, res, body) {
var result = require('querystring').parse(body)
// assert.equal(typeof result, 'object')
})
```
### OAuth2 Refresh Token
- https://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-6
```js
request.post('https://accounts.google.com/o/oauth2/token', {
form: {
grant_type: 'refresh_token',
client_id: '...',
client_secret: '...',
refresh_token: '...'
},
json: true
}, function (err, res, body) {
// assert.equal(typeof body, 'object')
})
```
# Multipart
## multipart/form-data
### Flickr Image Upload
- https://www.flickr.com/services/api/upload.api.html
```js
request.post('https://up.flickr.com/services/upload', {
oauth: {
consumer_key: '...',
consumer_secret: '...',
token: '...',
token_secret: '...'
},
// all meta data should be included here for proper signing
qs: {
title: 'My cat is awesome',
description: 'Sent on ' + new Date(),
is_public: 1
},
// again the same meta data + the actual photo
formData: {
title: 'My cat is awesome',
description: 'Sent on ' + new Date(),
is_public: 1,
photo:fs.createReadStream('cat.png')
},
json: true
}, function (err, res, body) {
// assert.equal(typeof body, 'object')
})
```
# Streams
## `POST` data
Use Request as a Writable stream to easily `POST` Readable streams (like files, other HTTP requests, or otherwise).
TL;DR: Pipe a Readable Stream onto Request via:
```
READABLE.pipe(request.post(URL));
```
A more detailed example:
```js
var fs = require('fs')
, path = require('path')
, http = require('http')
, request = require('request')
, TMP_FILE_PATH = path.join(path.sep, 'tmp', 'foo')
;
// write a temporary file:
fs.writeFileSync(TMP_FILE_PATH, 'foo bar baz quk\n');
http.createServer(function(req, res) {
console.log('the server is receiving data!\n');
req
.on('end', res.end.bind(res))
.pipe(process.stdout)
;
}).listen(3000).unref();
fs.createReadStream(TMP_FILE_PATH)
.pipe(request.post('http://127.0.0.1:3000'))
;
```

View File

@@ -0,0 +1,152 @@
// Copyright 2010-2012 Mikeal Rogers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict'
var extend = require('extend')
, cookies = require('./lib/cookies')
, helpers = require('./lib/helpers')
var isFunction = helpers.isFunction
, paramsHaveRequestBody = helpers.paramsHaveRequestBody
// organize params for patch, post, put, head, del
function initParams(uri, options, callback) {
if (typeof options === 'function') {
callback = options
}
var params = {}
if (typeof options === 'object') {
extend(params, options, {uri: uri})
} else if (typeof uri === 'string') {
extend(params, {uri: uri})
} else {
extend(params, uri)
}
params.callback = callback
return params
}
function request (uri, options, callback) {
if (typeof uri === 'undefined') {
throw new Error('undefined is not a valid uri or options object.')
}
var params = initParams(uri, options, callback)
if (params.method === 'HEAD' && paramsHaveRequestBody(params)) {
throw new Error('HTTP HEAD requests MUST NOT include a request body.')
}
return new request.Request(params)
}
function verbFunc (verb) {
var method = verb === 'del' ? 'DELETE' : verb.toUpperCase()
return function (uri, options, callback) {
var params = initParams(uri, options, callback)
params.method = method
return request(params, params.callback)
}
}
// define like this to please codeintel/intellisense IDEs
request.get = verbFunc('get')
request.head = verbFunc('head')
request.post = verbFunc('post')
request.put = verbFunc('put')
request.patch = verbFunc('patch')
request.del = verbFunc('del')
request.jar = function (store) {
return cookies.jar(store)
}
request.cookie = function (str) {
return cookies.parse(str)
}
function wrapRequestMethod (method, options, requester, verb) {
return function (uri, opts, callback) {
var params = initParams(uri, opts, callback)
var target = {}
extend(true, target, options, params)
if (verb) {
target.method = (verb === 'del' ? 'DELETE' : verb.toUpperCase())
}
if (isFunction(requester)) {
method = requester
}
return method(target, target.callback)
}
}
request.defaults = function (options, requester) {
var self = this
if (typeof options === 'function') {
requester = options
options = {}
}
var defaults = wrapRequestMethod(self, options, requester)
var verbs = ['get', 'head', 'post', 'put', 'patch', 'del']
verbs.forEach(function(verb) {
defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb)
})
defaults.cookie = wrapRequestMethod(self.cookie, options, requester)
defaults.jar = self.jar
defaults.defaults = self.defaults
return defaults
}
request.forever = function (agentOptions, optionsArg) {
var options = {}
if (optionsArg) {
extend(options, optionsArg)
}
if (agentOptions) {
options.agentOptions = agentOptions
}
options.forever = true
return request.defaults(options)
}
// Exports
module.exports = request
request.Request = require('./request')
request.initParams = initParams
// Backwards compatibility for request.debug
Object.defineProperty(request, 'debug', {
enumerable : true,
get : function() {
return request.Request.debug
},
set : function(debug) {
request.Request.debug = debug
}
})

View File

@@ -0,0 +1,153 @@
'use strict'
var caseless = require('caseless')
, uuid = require('node-uuid')
, helpers = require('./helpers')
var md5 = helpers.md5
, toBase64 = helpers.toBase64
function Auth (request) {
// define all public properties here
this.request = request
this.hasAuth = false
this.sentAuth = false
this.bearerToken = null
this.user = null
this.pass = null
}
Auth.prototype.basic = function (user, pass, sendImmediately) {
var self = this
if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) {
self.request.emit('error', new Error('auth() received invalid user or password'))
}
self.user = user
self.pass = pass
self.hasAuth = true
var header = user + ':' + (pass || '')
if (sendImmediately || typeof sendImmediately === 'undefined') {
var authHeader = 'Basic ' + toBase64(header)
self.sentAuth = true
return authHeader
}
}
Auth.prototype.bearer = function (bearer, sendImmediately) {
var self = this
self.bearerToken = bearer
self.hasAuth = true
if (sendImmediately || typeof sendImmediately === 'undefined') {
if (typeof bearer === 'function') {
bearer = bearer()
}
var authHeader = 'Bearer ' + (bearer || '')
self.sentAuth = true
return authHeader
}
}
Auth.prototype.digest = function (method, path, authHeader) {
// TODO: More complete implementation of RFC 2617.
// - check challenge.algorithm
// - support algorithm="MD5-sess"
// - handle challenge.domain
// - support qop="auth-int" only
// - handle Authentication-Info (not necessarily?)
// - check challenge.stale (not necessarily?)
// - increase nc (not necessarily?)
// For reference:
// http://tools.ietf.org/html/rfc2617#section-3
// https://github.com/bagder/curl/blob/master/lib/http_digest.c
var self = this
var challenge = {}
var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi
for (;;) {
var match = re.exec(authHeader)
if (!match) {
break
}
challenge[match[1]] = match[2] || match[3]
}
var ha1 = md5(self.user + ':' + challenge.realm + ':' + self.pass)
var ha2 = md5(method + ':' + path)
var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth'
var nc = qop && '00000001'
var cnonce = qop && uuid().replace(/-/g, '')
var digestResponse = qop
? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2)
: md5(ha1 + ':' + challenge.nonce + ':' + ha2)
var authValues = {
username: self.user,
realm: challenge.realm,
nonce: challenge.nonce,
uri: path,
qop: qop,
response: digestResponse,
nc: nc,
cnonce: cnonce,
algorithm: challenge.algorithm,
opaque: challenge.opaque
}
authHeader = []
for (var k in authValues) {
if (authValues[k]) {
if (k === 'qop' || k === 'nc' || k === 'algorithm') {
authHeader.push(k + '=' + authValues[k])
} else {
authHeader.push(k + '="' + authValues[k] + '"')
}
}
}
authHeader = 'Digest ' + authHeader.join(', ')
self.sentAuth = true
return authHeader
}
Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) {
var self = this
, request = self.request
var authHeader
if (bearer === undefined && user === undefined) {
self.request.emit('error', new Error('no auth mechanism defined'))
} else if (bearer !== undefined) {
authHeader = self.bearer(bearer, sendImmediately)
} else {
authHeader = self.basic(user, pass, sendImmediately)
}
if (authHeader) {
request.setHeader('authorization', authHeader)
}
}
Auth.prototype.onResponse = function (response) {
var self = this
, request = self.request
if (!self.hasAuth || self.sentAuth) { return null }
var c = caseless(response.headers)
var authHeader = c.get('www-authenticate')
var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase()
request.debug('reauth', authVerb)
switch (authVerb) {
case 'basic':
return self.basic(self.user, self.pass, true)
case 'bearer':
return self.bearer(self.bearerToken, true)
case 'digest':
return self.digest(request.method, request.path, authHeader)
}
}
exports.Auth = Auth

View File

@@ -0,0 +1,39 @@
'use strict'
var tough = require('tough-cookie')
var Cookie = tough.Cookie
, CookieJar = tough.CookieJar
exports.parse = function(str) {
if (str && str.uri) {
str = str.uri
}
if (typeof str !== 'string') {
throw new Error('The cookie function only accepts STRING as param')
}
return Cookie.parse(str)
}
// Adapt the sometimes-Async api of tough.CookieJar to our requirements
function RequestJar(store) {
var self = this
self._jar = new CookieJar(store)
}
RequestJar.prototype.setCookie = function(cookieOrStr, uri, options) {
var self = this
return self._jar.setCookieSync(cookieOrStr, uri, options || {})
}
RequestJar.prototype.getCookieString = function(uri) {
var self = this
return self._jar.getCookieStringSync(uri)
}
RequestJar.prototype.getCookies = function(uri) {
var self = this
return self._jar.getCookiesSync(uri)
}
exports.jar = function(store) {
return new RequestJar(store)
}

View File

@@ -0,0 +1,79 @@
'use strict'
function formatHostname(hostname) {
// canonicalize the hostname, so that 'oogle.com' won't match 'google.com'
return hostname.replace(/^\.*/, '.').toLowerCase()
}
function parseNoProxyZone(zone) {
zone = zone.trim().toLowerCase()
var zoneParts = zone.split(':', 2)
, zoneHost = formatHostname(zoneParts[0])
, zonePort = zoneParts[1]
, hasPort = zone.indexOf(':') > -1
return {hostname: zoneHost, port: zonePort, hasPort: hasPort}
}
function uriInNoProxy(uri, noProxy) {
var port = uri.port || (uri.protocol === 'https:' ? '443' : '80')
, hostname = formatHostname(uri.hostname)
, noProxyList = noProxy.split(',')
// iterate through the noProxyList until it finds a match.
return noProxyList.map(parseNoProxyZone).some(function(noProxyZone) {
var isMatchedAt = hostname.indexOf(noProxyZone.hostname)
, hostnameMatched = (
isMatchedAt > -1 &&
(isMatchedAt === hostname.length - noProxyZone.hostname.length)
)
if (noProxyZone.hasPort) {
return (port === noProxyZone.port) && hostnameMatched
}
return hostnameMatched
})
}
function getProxyFromURI(uri) {
// Decide the proper request proxy to use based on the request URI object and the
// environmental variables (NO_PROXY, HTTP_PROXY, etc.)
// respect NO_PROXY environment variables (see: http://lynx.isc.org/current/breakout/lynx_help/keystrokes/environments.html)
var noProxy = process.env.NO_PROXY || process.env.no_proxy || ''
// if the noProxy is a wildcard then return null
if (noProxy === '*') {
return null
}
// if the noProxy is not empty and the uri is found return null
if (noProxy !== '' && uriInNoProxy(uri, noProxy)) {
return null
}
// Check for HTTP or HTTPS Proxy in environment Else default to null
if (uri.protocol === 'http:') {
return process.env.HTTP_PROXY ||
process.env.http_proxy || null
}
if (uri.protocol === 'https:') {
return process.env.HTTPS_PROXY ||
process.env.https_proxy ||
process.env.HTTP_PROXY ||
process.env.http_proxy || null
}
// if none of that works, return null
// (What uri protocol are you using then?)
return null
}
module.exports = getProxyFromURI

View File

@@ -0,0 +1,205 @@
'use strict'
var fs = require('fs')
var qs = require('querystring')
var validate = require('har-validator')
var util = require('util')
function Har (request) {
this.request = request
}
Har.prototype.reducer = function (obj, pair) {
// new property ?
if (obj[pair.name] === undefined) {
obj[pair.name] = pair.value
return obj
}
// existing? convert to array
var arr = [
obj[pair.name],
pair.value
]
obj[pair.name] = arr
return obj
}
Har.prototype.prep = function (data) {
// construct utility properties
data.queryObj = {}
data.headersObj = {}
data.postData.jsonObj = false
data.postData.paramsObj = false
// construct query objects
if (data.queryString && data.queryString.length) {
data.queryObj = data.queryString.reduce(this.reducer, {})
}
// construct headers objects
if (data.headers && data.headers.length) {
// loweCase header keys
data.headersObj = data.headers.reduceRight(function (headers, header) {
headers[header.name] = header.value
return headers
}, {})
}
// construct Cookie header
if (data.cookies && data.cookies.length) {
var cookies = data.cookies.map(function (cookie) {
return cookie.name + '=' + cookie.value
})
if (cookies.length) {
data.headersObj.cookie = cookies.join('; ')
}
}
// prep body
switch (data.postData.mimeType) {
case 'multipart/mixed':
case 'multipart/related':
case 'multipart/form-data':
case 'multipart/alternative':
// reset values
data.postData.mimeType = 'multipart/form-data'
break
case 'application/x-www-form-urlencoded':
if (!data.postData.params) {
data.postData.text = ''
} else {
data.postData.paramsObj = data.postData.params.reduce(this.reducer, {})
// always overwrite
data.postData.text = qs.stringify(data.postData.paramsObj)
}
break
case 'text/json':
case 'text/x-json':
case 'application/json':
case 'application/x-json':
data.postData.mimeType = 'application/json'
if (data.postData.text) {
try {
data.postData.jsonObj = JSON.parse(data.postData.text)
} catch (e) {
this.request.debug(e)
// force back to text/plain
data.postData.mimeType = 'text/plain'
}
}
break
}
return data
}
Har.prototype.options = function (options) {
// skip if no har property defined
if (!options.har) {
return options
}
var har = util._extend({}, options.har)
// only process the first entry
if (har.log && har.log.entries) {
har = har.log.entries[0]
}
// add optional properties to make validation successful
har.url = har.url || options.url || options.uri || options.baseUrl || '/'
har.httpVersion = har.httpVersion || 'HTTP/1.1'
har.queryString = har.queryString || []
har.headers = har.headers || []
har.cookies = har.cookies || []
har.postData = har.postData || {}
har.postData.mimeType = har.postData.mimeType || 'application/octet-stream'
har.bodySize = 0
har.headersSize = 0
har.postData.size = 0
if (!validate.request(har)) {
return options
}
// clean up and get some utility properties
var req = this.prep(har)
// construct new options
if (req.url) {
options.url = req.url
}
if (req.method) {
options.method = req.method
}
if (Object.keys(req.queryObj).length) {
options.qs = req.queryObj
}
if (Object.keys(req.headersObj).length) {
options.headers = req.headersObj
}
switch (req.postData.mimeType) {
case 'application/x-www-form-urlencoded':
options.form = req.postData.paramsObj
break
case 'application/json':
if (req.postData.jsonObj) {
options.body = req.postData.jsonObj
options.json = true
}
break
case 'multipart/form-data':
options.formData = {}
req.postData.params.forEach(function (param) {
var attachment = {}
if (!param.fileName && !param.fileName && !param.contentType) {
options.formData[param.name] = param.value
return
}
// attempt to read from disk!
if (param.fileName && !param.value) {
attachment.value = fs.createReadStream(param.fileName)
} else if (param.value) {
attachment.value = param.value
}
if (param.fileName) {
attachment.options = {
filename: param.fileName,
contentType: param.contentType ? param.contentType : null
}
}
options.formData[param.name] = attachment
})
break
default:
if (req.postData.text) {
options.body = req.postData.text
}
}
return options
}
exports.Har = Har

View File

@@ -0,0 +1,64 @@
'use strict'
var jsonSafeStringify = require('json-stringify-safe')
, crypto = require('crypto')
function deferMethod() {
if (typeof setImmediate === 'undefined') {
return process.nextTick
}
return setImmediate
}
function isFunction(value) {
return typeof value === 'function'
}
function paramsHaveRequestBody(params) {
return (
params.body ||
params.requestBodyStream ||
(params.json && typeof params.json !== 'boolean') ||
params.multipart
)
}
function safeStringify (obj) {
var ret
try {
ret = JSON.stringify(obj)
} catch (e) {
ret = jsonSafeStringify(obj)
}
return ret
}
function md5 (str) {
return crypto.createHash('md5').update(str).digest('hex')
}
function isReadStream (rs) {
return rs.readable && rs.path && rs.mode
}
function toBase64 (str) {
return (new Buffer(str || '', 'utf8')).toString('base64')
}
function copy (obj) {
var o = {}
Object.keys(obj).forEach(function (i) {
o[i] = obj[i]
})
return o
}
exports.isFunction = isFunction
exports.paramsHaveRequestBody = paramsHaveRequestBody
exports.safeStringify = safeStringify
exports.md5 = md5
exports.isReadStream = isReadStream
exports.toBase64 = toBase64
exports.copy = copy
exports.defer = deferMethod()

View File

@@ -0,0 +1,109 @@
'use strict'
var uuid = require('node-uuid')
, CombinedStream = require('combined-stream')
, isstream = require('isstream')
function Multipart (request) {
this.request = request
this.boundary = uuid()
this.chunked = false
this.body = null
}
Multipart.prototype.isChunked = function (options) {
var self = this
, chunked = false
, parts = options.data || options
if (!parts.forEach) {
self.request.emit('error', new Error('Argument error, options.multipart.'))
}
if (options.chunked !== undefined) {
chunked = options.chunked
}
if (self.request.getHeader('transfer-encoding') === 'chunked') {
chunked = true
}
if (!chunked) {
parts.forEach(function (part) {
if (typeof part.body === 'undefined') {
self.request.emit('error', new Error('Body attribute missing in multipart.'))
}
if (isstream(part.body)) {
chunked = true
}
})
}
return chunked
}
Multipart.prototype.setHeaders = function (chunked) {
var self = this
if (chunked && !self.request.hasHeader('transfer-encoding')) {
self.request.setHeader('transfer-encoding', 'chunked')
}
var header = self.request.getHeader('content-type')
if (!header || header.indexOf('multipart') === -1) {
self.request.setHeader('content-type', 'multipart/related; boundary=' + self.boundary)
} else {
if (header.indexOf('boundary') !== -1) {
self.boundary = header.replace(/.*boundary=([^\s;]+).*/, '$1')
} else {
self.request.setHeader('content-type', header + '; boundary=' + self.boundary)
}
}
}
Multipart.prototype.build = function (parts, chunked) {
var self = this
var body = chunked ? new CombinedStream() : []
function add (part) {
return chunked ? body.append(part) : body.push(new Buffer(part))
}
if (self.request.preambleCRLF) {
add('\r\n')
}
parts.forEach(function (part) {
var preamble = '--' + self.boundary + '\r\n'
Object.keys(part).forEach(function (key) {
if (key === 'body') { return }
preamble += key + ': ' + part[key] + '\r\n'
})
preamble += '\r\n'
add(preamble)
add(part.body)
add('\r\n')
})
add('--' + self.boundary + '--')
if (self.request.postambleCRLF) {
add('\r\n')
}
return body
}
Multipart.prototype.onRequest = function (options) {
var self = this
var chunked = self.isChunked(options)
, parts = options.data || options
self.setHeaders(chunked)
self.chunked = chunked
self.body = self.build(parts, chunked)
}
exports.Multipart = Multipart

View File

@@ -0,0 +1,147 @@
'use strict'
var url = require('url')
, qs = require('qs')
, caseless = require('caseless')
, uuid = require('node-uuid')
, oauth = require('oauth-sign')
, crypto = require('crypto')
function OAuth (request) {
this.request = request
this.params = null
}
OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib) {
var oa = {}
for (var i in _oauth) {
oa['oauth_' + i] = _oauth[i]
}
if (!oa.oauth_version) {
oa.oauth_version = '1.0'
}
if (!oa.oauth_timestamp) {
oa.oauth_timestamp = Math.floor( Date.now() / 1000 ).toString()
}
if (!oa.oauth_nonce) {
oa.oauth_nonce = uuid().replace(/-/g, '')
}
if (!oa.oauth_signature_method) {
oa.oauth_signature_method = 'HMAC-SHA1'
}
var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key
delete oa.oauth_consumer_secret
delete oa.oauth_private_key
var token_secret = oa.oauth_token_secret
delete oa.oauth_token_secret
var realm = oa.oauth_realm
delete oa.oauth_realm
delete oa.oauth_transport_method
var baseurl = uri.protocol + '//' + uri.host + uri.pathname
var params = qsLib.parse([].concat(query, form, qsLib.stringify(oa)).join('&'))
oa.oauth_signature = oauth.sign(
oa.oauth_signature_method,
method,
baseurl,
params,
consumer_secret_or_private_key,
token_secret)
if (realm) {
oa.realm = realm
}
return oa
}
OAuth.prototype.buildBodyHash = function(_oauth, body) {
if (['HMAC-SHA1', 'RSA-SHA1'].indexOf(_oauth.signature_method || 'HMAC-SHA1') < 0) {
this.request.emit('error', new Error('oauth: ' + _oauth.signature_method +
' signature_method not supported with body_hash signing.'))
}
var shasum = crypto.createHash('sha1')
shasum.update(body || '')
var sha1 = shasum.digest('hex')
return new Buffer(sha1).toString('base64')
}
OAuth.prototype.concatParams = function (oa, sep, wrap) {
wrap = wrap || ''
var params = Object.keys(oa).filter(function (i) {
return i !== 'realm' && i !== 'oauth_signature'
}).sort()
if (oa.realm) {
params.splice(0, 1, 'realm')
}
params.push('oauth_signature')
return params.map(function (i) {
return i + '=' + wrap + oauth.rfc3986(oa[i]) + wrap
}).join(sep)
}
OAuth.prototype.onRequest = function (_oauth) {
var self = this
self.params = _oauth
var uri = self.request.uri || {}
, method = self.request.method || ''
, headers = caseless(self.request.headers)
, body = self.request.body || ''
, qsLib = self.request.qsLib || qs
var form
, query
, contentType = headers.get('content-type') || ''
, formContentType = 'application/x-www-form-urlencoded'
, transport = _oauth.transport_method || 'header'
if (contentType.slice(0, formContentType.length) === formContentType) {
contentType = formContentType
form = body
}
if (uri.query) {
query = uri.query
}
if (transport === 'body' && (method !== 'POST' || contentType !== formContentType)) {
self.request.emit('error', new Error('oauth: transport_method of body requires POST ' +
'and content-type ' + formContentType))
}
if (!form && typeof _oauth.body_hash === 'boolean') {
_oauth.body_hash = self.buildBodyHash(_oauth, self.request.body.toString())
}
var oa = self.buildParams(_oauth, uri, method, query, form, qsLib)
switch (transport) {
case 'header':
self.request.setHeader('Authorization', 'OAuth ' + self.concatParams(oa, ',', '"'))
break
case 'query':
var href = self.request.uri.href += (query ? '&' : '?') + self.concatParams(oa, '&')
self.request.uri = url.parse(href)
self.request.path = self.request.uri.path
break
case 'body':
self.request.body = (form ? form + '&' : '') + self.concatParams(oa, '&')
break
default:
self.request.emit('error', new Error('oauth: transport_method invalid'))
}
}
exports.OAuth = OAuth

View File

@@ -0,0 +1,51 @@
'use strict'
var qs = require('qs')
, querystring = require('querystring')
function Querystring (request) {
this.request = request
this.lib = null
this.useQuerystring = null
this.parseOptions = null
this.stringifyOptions = null
}
Querystring.prototype.init = function (options) {
if (this.lib) {return}
this.useQuerystring = options.useQuerystring
this.lib = (this.useQuerystring ? querystring : qs)
this.parseOptions = options.qsParseOptions || {}
this.stringifyOptions = options.qsStringifyOptions || {}
}
Querystring.prototype.stringify = function (obj) {
return (this.useQuerystring)
? this.rfc3986(this.lib.stringify(obj,
this.stringifyOptions.sep || null,
this.stringifyOptions.eq || null,
this.stringifyOptions))
: this.lib.stringify(obj, this.stringifyOptions)
}
Querystring.prototype.parse = function (str) {
return (this.useQuerystring)
? this.lib.parse(str,
this.parseOptions.sep || null,
this.parseOptions.eq || null,
this.parseOptions)
: this.lib.parse(str, this.parseOptions)
}
Querystring.prototype.rfc3986 = function (str) {
return str.replace(/[!'()*]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
Querystring.prototype.unescape = querystring.unescape
exports.Querystring = Querystring

View File

@@ -0,0 +1,153 @@
'use strict'
var url = require('url')
var isUrl = /^https?:/
function Redirect (request) {
this.request = request
this.followRedirect = true
this.followRedirects = true
this.followAllRedirects = false
this.allowRedirect = function () {return true}
this.maxRedirects = 10
this.redirects = []
this.redirectsFollowed = 0
this.removeRefererHeader = false
}
Redirect.prototype.onRequest = function (options) {
var self = this
if (options.maxRedirects !== undefined) {
self.maxRedirects = options.maxRedirects
}
if (typeof options.followRedirect === 'function') {
self.allowRedirect = options.followRedirect
}
if (options.followRedirect !== undefined) {
self.followRedirects = !!options.followRedirect
}
if (options.followAllRedirects !== undefined) {
self.followAllRedirects = options.followAllRedirects
}
if (self.followRedirects || self.followAllRedirects) {
self.redirects = self.redirects || []
}
if (options.removeRefererHeader !== undefined) {
self.removeRefererHeader = options.removeRefererHeader
}
}
Redirect.prototype.redirectTo = function (response) {
var self = this
, request = self.request
var redirectTo = null
if (response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location')) {
var location = response.caseless.get('location')
request.debug('redirect', location)
if (self.followAllRedirects) {
redirectTo = location
} else if (self.followRedirects) {
switch (request.method) {
case 'PATCH':
case 'PUT':
case 'POST':
case 'DELETE':
// Do not follow redirects
break
default:
redirectTo = location
break
}
}
} else if (response.statusCode === 401) {
var authHeader = request._auth.onResponse(response)
if (authHeader) {
request.setHeader('authorization', authHeader)
redirectTo = request.uri
}
}
return redirectTo
}
Redirect.prototype.onResponse = function (response) {
var self = this
, request = self.request
var redirectTo = self.redirectTo(response)
if (!redirectTo || !self.allowRedirect.call(request, response)) {
return false
}
request.debug('redirect to', redirectTo)
// ignore any potential response body. it cannot possibly be useful
// to us at this point.
// response.resume should be defined, but check anyway before calling. Workaround for browserify.
if (response.resume) {
response.resume()
}
if (self.redirectsFollowed >= self.maxRedirects) {
request.emit('error', new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + request.uri.href))
return false
}
self.redirectsFollowed += 1
if (!isUrl.test(redirectTo)) {
redirectTo = url.resolve(request.uri.href, redirectTo)
}
var uriPrev = request.uri
request.uri = url.parse(redirectTo)
// handle the case where we change protocol from https to http or vice versa
if (request.uri.protocol !== uriPrev.protocol) {
request._updateProtocol()
}
self.redirects.push(
{ statusCode : response.statusCode
, redirectUri: redirectTo
}
)
if (self.followAllRedirects && response.statusCode !== 401 && response.statusCode !== 307) {
request.method = 'GET'
}
// request.method = 'GET' // Force all redirects to use GET || commented out fixes #215
delete request.src
delete request.req
delete request.agent
delete request._started
if (response.statusCode !== 401 && response.statusCode !== 307) {
// Remove parameters from the previous response, unless this is the second request
// for a server that requires digest authentication.
delete request.body
delete request._form
if (request.headers) {
request.removeHeader('host')
request.removeHeader('content-type')
request.removeHeader('content-length')
if (request.uri.hostname !== request.originalHost.split(':')[0]) {
// Remove authorization if changing hostnames (but not if just
// changing ports or protocols). This matches the behavior of curl:
// https://github.com/bagder/curl/blob/6beb0eee/lib/http.c#L710
request.removeHeader('authorization')
}
}
}
if (!self.removeRefererHeader) {
request.setHeader('referer', request.uri.href)
}
request.emit('redirect')
request.init()
return true
}
exports.Redirect = Redirect

View File

@@ -0,0 +1,183 @@
'use strict'
var url = require('url')
, tunnel = require('tunnel-agent')
var defaultProxyHeaderWhiteList = [
'accept',
'accept-charset',
'accept-encoding',
'accept-language',
'accept-ranges',
'cache-control',
'content-encoding',
'content-language',
'content-length',
'content-location',
'content-md5',
'content-range',
'content-type',
'connection',
'date',
'expect',
'max-forwards',
'pragma',
'referer',
'te',
'transfer-encoding',
'user-agent',
'via'
]
var defaultProxyHeaderExclusiveList = [
'proxy-authorization'
]
function constructProxyHost(uriObject) {
var port = uriObject.portA
, protocol = uriObject.protocol
, proxyHost = uriObject.hostname + ':'
if (port) {
proxyHost += port
} else if (protocol === 'https:') {
proxyHost += '443'
} else {
proxyHost += '80'
}
return proxyHost
}
function constructProxyHeaderWhiteList(headers, proxyHeaderWhiteList) {
var whiteList = proxyHeaderWhiteList
.reduce(function (set, header) {
set[header.toLowerCase()] = true
return set
}, {})
return Object.keys(headers)
.filter(function (header) {
return whiteList[header.toLowerCase()]
})
.reduce(function (set, header) {
set[header] = headers[header]
return set
}, {})
}
function constructTunnelOptions (request, proxyHeaders) {
var proxy = request.proxy
var tunnelOptions = {
proxy : {
host : proxy.hostname,
port : +proxy.port,
proxyAuth : proxy.auth,
headers : proxyHeaders
},
headers : request.headers,
ca : request.ca,
cert : request.cert,
key : request.key,
passphrase : request.passphrase,
pfx : request.pfx,
ciphers : request.ciphers,
rejectUnauthorized : request.rejectUnauthorized,
secureOptions : request.secureOptions,
secureProtocol : request.secureProtocol
}
return tunnelOptions
}
function constructTunnelFnName(uri, proxy) {
var uriProtocol = (uri.protocol === 'https:' ? 'https' : 'http')
var proxyProtocol = (proxy.protocol === 'https:' ? 'Https' : 'Http')
return [uriProtocol, proxyProtocol].join('Over')
}
function getTunnelFn(request) {
var uri = request.uri
var proxy = request.proxy
var tunnelFnName = constructTunnelFnName(uri, proxy)
return tunnel[tunnelFnName]
}
function Tunnel (request) {
this.request = request
this.proxyHeaderWhiteList = defaultProxyHeaderWhiteList
this.proxyHeaderExclusiveList = []
}
Tunnel.prototype.isEnabled = function (options) {
var request = this.request
// Tunnel HTTPS by default, or if a previous request in the redirect chain
// was tunneled. Allow the user to override this setting.
// If self.tunnel is already set (because this is a redirect), use the
// existing value.
if (typeof request.tunnel !== 'undefined') {
return request.tunnel
}
// If options.tunnel is set (the user specified a value), use it.
if (typeof options.tunnel !== 'undefined') {
return options.tunnel
}
// If the destination is HTTPS, tunnel.
if (request.uri.protocol === 'https:') {
return true
}
// Otherwise, leave tunnel unset, because if a later request in the redirect
// chain is HTTPS then that request (and any subsequent ones) should be
// tunneled.
return undefined
}
Tunnel.prototype.setup = function (options) {
var self = this
, request = self.request
options = options || {}
if (typeof request.proxy === 'string') {
request.proxy = url.parse(request.proxy)
}
if (!request.proxy || !request.tunnel) {
return false
}
// Setup Proxy Header Exclusive List and White List
if (options.proxyHeaderWhiteList) {
self.proxyHeaderWhiteList = options.proxyHeaderWhiteList
}
if (options.proxyHeaderExclusiveList) {
self.proxyHeaderExclusiveList = options.proxyHeaderExclusiveList
}
var proxyHeaderExclusiveList = self.proxyHeaderExclusiveList.concat(defaultProxyHeaderExclusiveList)
var proxyHeaderWhiteList = self.proxyHeaderWhiteList.concat(proxyHeaderExclusiveList)
// Setup Proxy Headers and Proxy Headers Host
// Only send the Proxy White Listed Header names
var proxyHeaders = constructProxyHeaderWhiteList(request.headers, proxyHeaderWhiteList)
proxyHeaders.host = constructProxyHost(request.uri)
proxyHeaderExclusiveList.forEach(request.removeHeader, request)
// Set Agent from Tunnel Data
var tunnelFn = getTunnelFn(request)
var tunnelOptions = constructTunnelOptions(request, proxyHeaders)
request.agent = tunnelFn(tunnelOptions)
return true
}
Tunnel.defaultProxyHeaderWhiteList = defaultProxyHeaderWhiteList
Tunnel.defaultProxyHeaderExclusiveList = defaultProxyHeaderExclusiveList
exports.Tunnel = Tunnel

View File

@@ -0,0 +1,55 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

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