remove node_modules óÒ
This commit is contained in:
+1
-1
@@ -193,7 +193,7 @@ ClientBin/
|
||||
*.jfm
|
||||
*.pfx
|
||||
*.publishsettings
|
||||
node_modules/
|
||||
**/node_modules/
|
||||
orleans.codegen.cs
|
||||
|
||||
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||
|
||||
@@ -9,4 +9,8 @@
|
||||
<ProjectReference Include="..\zero.Web\zero.Web.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="wwwroot\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
# async-each
|
||||
|
||||
No-bullshit, ultra-simple, 35-lines-of-code async parallel forEach function for JavaScript.
|
||||
|
||||
We don't need junky 30K async libs. Really.
|
||||
|
||||
For browsers and node.js.
|
||||
|
||||
## Installation
|
||||
* Just include async-each before your scripts.
|
||||
* `npm install async-each` if you’re using node.js.
|
||||
|
||||
## Usage
|
||||
|
||||
* `each(array, iterator, callback);` — `Array`, `Function`, `(optional) Function`
|
||||
* `iterator(item, next)` receives current item and a callback that will mark the item as done. `next` callback receives optional `error, transformedItem` arguments.
|
||||
* `callback(error, transformedArray)` optionally receives first error and transformed result `Array`.
|
||||
|
||||
```javascript
|
||||
var each = require('async-each');
|
||||
each(['a.js', 'b.js', 'c.js'], fs.readFile, function(error, contents) {
|
||||
if (error) console.error(error);
|
||||
console.log('Contents for a, b and c:', contents);
|
||||
});
|
||||
|
||||
// Alternatively in browser:
|
||||
asyncEach(list, fn, callback);
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016 Paul Miller [(paulmillr.com)](http://paulmillr.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.
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
// async-each MIT license (by Paul Miller from https://paulmillr.com).
|
||||
(function(globals) {
|
||||
'use strict';
|
||||
var each = function(items, next, callback) {
|
||||
if (!Array.isArray(items)) throw new TypeError('each() expects array as first argument');
|
||||
if (typeof next !== 'function') throw new TypeError('each() expects function as second argument');
|
||||
if (typeof callback !== 'function') callback = Function.prototype; // no-op
|
||||
|
||||
if (items.length === 0) return callback(undefined, items);
|
||||
|
||||
var transformed = new Array(items.length);
|
||||
var count = 0;
|
||||
var returned = false;
|
||||
|
||||
items.forEach(function(item, index) {
|
||||
next(item, function(error, transformedItem) {
|
||||
if (returned) return;
|
||||
if (error) {
|
||||
returned = true;
|
||||
return callback(error);
|
||||
}
|
||||
transformed[index] = transformedItem;
|
||||
count += 1;
|
||||
if (count === items.length) return callback(undefined, transformed);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
if (typeof define !== 'undefined' && define.amd) {
|
||||
define([], function() {
|
||||
return each;
|
||||
}); // RequireJS
|
||||
} else if (typeof module !== 'undefined' && module.exports) {
|
||||
module.exports = each; // CommonJS
|
||||
} else {
|
||||
globals.asyncEach = each; // <script>
|
||||
}
|
||||
})(this);
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
{
|
||||
"_from": "async-each@^1.0.1",
|
||||
"_id": "async-each@1.0.3",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-z/WhQ5FPySLdvREByI2vZiTWwCnF0moMJ1hK9YQwDTHKh6I7/uSckMetoRGb5UBZPC1z0jlw+n/XCgjeH7y1AQ==",
|
||||
"_location": "/async-each",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "async-each@^1.0.1",
|
||||
"name": "async-each",
|
||||
"escapedName": "async-each",
|
||||
"rawSpec": "^1.0.1",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^1.0.1"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/chokidar"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/async-each/-/async-each-1.0.3.tgz",
|
||||
"_shasum": "b727dbf87d7651602f06f4d4ac387f47d91b0cbf",
|
||||
"_spec": "async-each@^1.0.1",
|
||||
"_where": "O:\\zero\\zero.Web\\node_modules\\chokidar",
|
||||
"author": {
|
||||
"name": "Paul Miller",
|
||||
"url": "https://paulmillr.com/"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/paulmillr/async-each/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {},
|
||||
"deprecated": false,
|
||||
"description": "No-bullshit, ultra-simple, 35-lines-of-code async parallel forEach / map function for JavaScript.",
|
||||
"files": [
|
||||
"index.js"
|
||||
],
|
||||
"homepage": "https://github.com/paulmillr/async-each/",
|
||||
"keywords": [
|
||||
"async",
|
||||
"forEach",
|
||||
"each",
|
||||
"map",
|
||||
"asynchronous",
|
||||
"iteration",
|
||||
"iterate",
|
||||
"loop",
|
||||
"parallel",
|
||||
"concurrent",
|
||||
"array",
|
||||
"flow",
|
||||
"control flow"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "index.js",
|
||||
"name": "async-each",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/paulmillr/async-each.git"
|
||||
},
|
||||
"version": "1.0.3"
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
Copyright (c) 2011 "Cowboy" Ben Alman
|
||||
|
||||
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.
|
||||
-195
@@ -1,195 +0,0 @@
|
||||
# JavaScript Sync/Async forEach
|
||||
|
||||
An optionally-asynchronous forEach with an interesting interface.
|
||||
|
||||
## Getting Started
|
||||
|
||||
This code should work just fine in Node.js:
|
||||
|
||||
First, install the module with: `npm install async-foreach`
|
||||
|
||||
```javascript
|
||||
var forEach = require('async-foreach').forEach;
|
||||
forEach(["a", "b", "c"], function(item, index, arr) {
|
||||
console.log("each", item, index, arr);
|
||||
});
|
||||
// logs:
|
||||
// each a 0 ["a", "b", "c"]
|
||||
// each b 1 ["a", "b", "c"]
|
||||
// each c 2 ["a", "b", "c"]
|
||||
```
|
||||
|
||||
Or in the browser:
|
||||
|
||||
```html
|
||||
<script src="dist/ba-foreach.min.js"></script>
|
||||
<script>
|
||||
forEach(["a", "b", "c"], function(item, index, arr) {
|
||||
console.log("each", item, index, arr);
|
||||
});
|
||||
// logs:
|
||||
// each a 0 ["a", "b", "c"]
|
||||
// each b 1 ["a", "b", "c"]
|
||||
// each c 2 ["a", "b", "c"]
|
||||
</script>
|
||||
```
|
||||
|
||||
In the browser, you can attach the forEach method to any object.
|
||||
|
||||
```html
|
||||
<script>
|
||||
this.exports = Bocoup.utils;
|
||||
</script>
|
||||
<script src="dist/ba-foreach.min.js"></script>
|
||||
<script>
|
||||
Bocoup.utils.forEach(["a", "b", "c"], function(item, index, arr) {
|
||||
console.log("each", item, index, arr);
|
||||
});
|
||||
// logs:
|
||||
// each a 0 ["a", "b", "c"]
|
||||
// each b 1 ["a", "b", "c"]
|
||||
// each c 2 ["a", "b", "c"]
|
||||
</script>
|
||||
```
|
||||
|
||||
## The General Idea (Why I thought this was worth sharing)
|
||||
|
||||
The idea is to allow the callback to decide _at runtime_ whether the loop will be synchronous or asynchronous. By using `this` in a creative way (in situations where that value isn't already spoken for), an entire control API can be offered without over-complicating function signatures.
|
||||
|
||||
```javascript
|
||||
forEach(arr, function(item, index) {
|
||||
// Synchronous.
|
||||
});
|
||||
|
||||
forEach(arr, function(item, index) {
|
||||
// Only when `this.async` is called does iteration becomes asynchronous. The
|
||||
// loop won't be continued until the `done` function is executed.
|
||||
var done = this.async();
|
||||
// Continue in one second.
|
||||
setTimeout(done, 1000);
|
||||
});
|
||||
|
||||
forEach(arr, function(item, index) {
|
||||
// Break out of synchronous iteration early by returning false.
|
||||
return index !== 1;
|
||||
});
|
||||
|
||||
forEach(arr, function(item, index) {
|
||||
// Break out of asynchronous iteration early...
|
||||
var done = this.async();
|
||||
// ...by passing false to the done function.
|
||||
setTimeout(function() {
|
||||
done(index !== 1);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Examples
|
||||
See the unit tests for more examples.
|
||||
|
||||
```javascript
|
||||
// Generic "done" callback.
|
||||
function allDone(notAborted, arr) {
|
||||
console.log("done", notAborted, arr);
|
||||
}
|
||||
|
||||
// Synchronous.
|
||||
forEach(["a", "b", "c"], function(item, index, arr) {
|
||||
console.log("each", item, index, arr);
|
||||
}, allDone);
|
||||
// logs:
|
||||
// each a 0 ["a", "b", "c"]
|
||||
// each b 1 ["a", "b", "c"]
|
||||
// each c 2 ["a", "b", "c"]
|
||||
// done true ["a", "b", "c"]
|
||||
|
||||
// Synchronous with early abort.
|
||||
forEach(["a", "b", "c"], function(item, index, arr) {
|
||||
console.log("each", item, index, arr);
|
||||
if (item === "b") { return false; }
|
||||
}, allDone);
|
||||
// logs:
|
||||
// each a 0 ["a", "b", "c"]
|
||||
// each b 1 ["a", "b", "c"]
|
||||
// done false ["a", "b", "c"]
|
||||
|
||||
// Asynchronous.
|
||||
forEach(["a", "b", "c"], function(item, index, arr) {
|
||||
console.log("each", item, index, arr);
|
||||
var done = this.async();
|
||||
setTimeout(function() {
|
||||
done();
|
||||
}, 500);
|
||||
}, allDone);
|
||||
// logs:
|
||||
// each a 0 ["a", "b", "c"]
|
||||
// each b 1 ["a", "b", "c"]
|
||||
// each c 2 ["a", "b", "c"]
|
||||
// done true ["a", "b", "c"]
|
||||
|
||||
// Asynchronous with early abort.
|
||||
forEach(["a", "b", "c"], function(item, index, arr) {
|
||||
console.log("each", item, index, arr);
|
||||
var done = this.async();
|
||||
setTimeout(function() {
|
||||
done(item !== "b");
|
||||
}, 500);
|
||||
}, allDone);
|
||||
// logs:
|
||||
// each a 0 ["a", "b", "c"]
|
||||
// each b 1 ["a", "b", "c"]
|
||||
// done false ["a", "b", "c"]
|
||||
|
||||
// Not actually asynchronous.
|
||||
forEach(["a", "b", "c"], function(item, index, arr) {
|
||||
console.log("each", item, index, arr);
|
||||
var done = this.async()
|
||||
done();
|
||||
}, allDone);
|
||||
// logs:
|
||||
// each a 0 ["a", "b", "c"]
|
||||
// each b 1 ["a", "b", "c"]
|
||||
// each c 2 ["a", "b", "c"]
|
||||
// done true ["a", "b", "c"]
|
||||
|
||||
// Not actually asynchronous with early abort.
|
||||
forEach(["a", "b", "c"], function(item, index, arr) {
|
||||
console.log("each", item, index, arr);
|
||||
var done = this.async();
|
||||
done(item !== "b");
|
||||
}, allDone);
|
||||
// logs:
|
||||
// each a 0 ["a", "b", "c"]
|
||||
// each b 1 ["a", "b", "c"]
|
||||
// done false ["a", "b", "c"]
|
||||
```
|
||||
|
||||
## Contributing
|
||||
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [grunt](https://github.com/cowboy/grunt).
|
||||
|
||||
_Also, please don't edit files in the "dist" subdirectory as they are generated via grunt. You'll find source code in the "lib" subdirectory!_
|
||||
|
||||
## Release History
|
||||
|
||||
04/29/2013
|
||||
v0.1.3
|
||||
Removed hard Node.js version dependency.
|
||||
|
||||
11/17/2011
|
||||
v0.1.2
|
||||
Adding sparse array support.
|
||||
Invalid length properties are now sanitized.
|
||||
This closes issue #1 (like a boss).
|
||||
|
||||
11/11/2011
|
||||
v0.1.1
|
||||
Refactored code to be much simpler. Yay for unit tests!
|
||||
|
||||
11/11/2011
|
||||
v0.1.0
|
||||
Initial Release.
|
||||
|
||||
## License
|
||||
Copyright (c) 2012 "Cowboy" Ben Alman
|
||||
Licensed under the MIT license.
|
||||
<http://benalman.com/about/license/>
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
/* JavaScript Sync/Async forEach - v0.1.2 - 1/10/2012
|
||||
* http://github.com/cowboy/javascript-sync-async-foreach
|
||||
* Copyright (c) 2012 "Cowboy" Ben Alman; Licensed MIT */
|
||||
|
||||
(function(exports) {
|
||||
|
||||
// Iterate synchronously or asynchronously.
|
||||
exports.forEach = function(arr, eachFn, doneFn) {
|
||||
var i = -1;
|
||||
// Resolve array length to a valid (ToUint32) number.
|
||||
var len = arr.length >>> 0;
|
||||
|
||||
// This IIFE is called once now, and then again, by name, for each loop
|
||||
// iteration.
|
||||
(function next(result) {
|
||||
// This flag will be set to true if `this.async` is called inside the
|
||||
// eachFn` callback.
|
||||
var async;
|
||||
// Was false returned from the `eachFn` callback or passed to the
|
||||
// `this.async` done function?
|
||||
var abort = result === false;
|
||||
|
||||
// Increment counter variable and skip any indices that don't exist. This
|
||||
// allows sparse arrays to be iterated.
|
||||
do { ++i; } while (!(i in arr) && i !== len);
|
||||
|
||||
// Exit if result passed to `this.async` done function or returned from
|
||||
// the `eachFn` callback was false, or when done iterating.
|
||||
if (abort || i === len) {
|
||||
// If a `doneFn` callback was specified, invoke that now. Pass in a
|
||||
// boolean value representing "not aborted" state along with the array.
|
||||
if (doneFn) {
|
||||
doneFn(!abort, arr);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Invoke the `eachFn` callback, setting `this` inside the callback to a
|
||||
// custom object that contains one method, and passing in the array item,
|
||||
// index, and the array.
|
||||
result = eachFn.call({
|
||||
// If `this.async` is called inside the `eachFn` callback, set the async
|
||||
// flag and return a function that can be used to continue iterating.
|
||||
async: function() {
|
||||
async = true;
|
||||
return next;
|
||||
}
|
||||
}, arr[i], i, arr);
|
||||
|
||||
// If the async flag wasn't set, continue by calling `next` synchronously,
|
||||
// passing in the result of the `eachFn` callback.
|
||||
if (!async) {
|
||||
next(result);
|
||||
}
|
||||
}());
|
||||
};
|
||||
|
||||
}(typeof exports === "object" && exports || this));
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
/* JavaScript Sync/Async forEach - v0.1.2 - 1/10/2012
|
||||
* http://github.com/cowboy/javascript-sync-async-foreach
|
||||
* Copyright (c) 2012 "Cowboy" Ben Alman; Licensed MIT */
|
||||
(function(a){a.forEach=function(a,b,c){var d=-1,e=a.length>>>0;(function f(g){var h,j=g===!1;do++d;while(!(d in a)&&d!==e);if(j||d===e){c&&c(!j,a);return}g=b.call({async:function(){return h=!0,f}},a[d],d,a),h||f(g)})()}})(typeof exports=="object"&&exports||this)
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
/*global config:true, task:true*/
|
||||
config.init({
|
||||
pkg: '<json:package.json>',
|
||||
meta: {
|
||||
title: 'JavaScript Sync/Async forEach',
|
||||
license: ['MIT'],
|
||||
copyright: 'Copyright (c) 2012 "Cowboy" Ben Alman',
|
||||
banner: '/* {{meta.title}} - v{{pkg.version}} - {{today "m/d/yyyy"}}\n' +
|
||||
' * {{pkg.homepage}}\n' +
|
||||
' * {{{meta.copyright}}}; Licensed {{join meta.license}} */'
|
||||
},
|
||||
concat: {
|
||||
'dist/ba-foreach.js': ['<banner>', '<file_strip_banner:lib/foreach.js>']
|
||||
},
|
||||
min: {
|
||||
'dist/ba-foreach.min.js': ['<banner>', 'dist/ba-foreach.js']
|
||||
},
|
||||
test: {
|
||||
files: ['test/**/*.js']
|
||||
},
|
||||
lint: {
|
||||
files: ['grunt.js', 'lib/**/*.js', 'test/**/*.js']
|
||||
},
|
||||
watch: {
|
||||
files: '<config:lint.files>',
|
||||
tasks: 'lint:files test:files'
|
||||
},
|
||||
jshint: {
|
||||
options: {
|
||||
curly: true,
|
||||
eqeqeq: true,
|
||||
immed: true,
|
||||
latedef: true,
|
||||
newcap: true,
|
||||
noarg: true,
|
||||
sub: true,
|
||||
undef: true,
|
||||
eqnull: true
|
||||
},
|
||||
globals: {
|
||||
exports: true
|
||||
}
|
||||
},
|
||||
uglify: {}
|
||||
});
|
||||
|
||||
// Default task.
|
||||
task.registerTask('default', 'lint:files test:files concat min');
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
/*!
|
||||
* Sync/Async forEach
|
||||
* https://github.com/cowboy/javascript-sync-async-foreach
|
||||
*
|
||||
* Copyright (c) 2012 "Cowboy" Ben Alman
|
||||
* Licensed under the MIT license.
|
||||
* http://benalman.com/about/license/
|
||||
*/
|
||||
|
||||
(function(exports) {
|
||||
|
||||
// Iterate synchronously or asynchronously.
|
||||
exports.forEach = function(arr, eachFn, doneFn) {
|
||||
var i = -1;
|
||||
// Resolve array length to a valid (ToUint32) number.
|
||||
var len = arr.length >>> 0;
|
||||
|
||||
// This IIFE is called once now, and then again, by name, for each loop
|
||||
// iteration.
|
||||
(function next(result) {
|
||||
// This flag will be set to true if `this.async` is called inside the
|
||||
// eachFn` callback.
|
||||
var async;
|
||||
// Was false returned from the `eachFn` callback or passed to the
|
||||
// `this.async` done function?
|
||||
var abort = result === false;
|
||||
|
||||
// Increment counter variable and skip any indices that don't exist. This
|
||||
// allows sparse arrays to be iterated.
|
||||
do { ++i; } while (!(i in arr) && i !== len);
|
||||
|
||||
// Exit if result passed to `this.async` done function or returned from
|
||||
// the `eachFn` callback was false, or when done iterating.
|
||||
if (abort || i === len) {
|
||||
// If a `doneFn` callback was specified, invoke that now. Pass in a
|
||||
// boolean value representing "not aborted" state along with the array.
|
||||
if (doneFn) {
|
||||
doneFn(!abort, arr);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Invoke the `eachFn` callback, setting `this` inside the callback to a
|
||||
// custom object that contains one method, and passing in the array item,
|
||||
// index, and the array.
|
||||
result = eachFn.call({
|
||||
// If `this.async` is called inside the `eachFn` callback, set the async
|
||||
// flag and return a function that can be used to continue iterating.
|
||||
async: function() {
|
||||
async = true;
|
||||
return next;
|
||||
}
|
||||
}, arr[i], i, arr);
|
||||
|
||||
// If the async flag wasn't set, continue by calling `next` synchronously,
|
||||
// passing in the result of the `eachFn` callback.
|
||||
if (!async) {
|
||||
next(result);
|
||||
}
|
||||
}());
|
||||
};
|
||||
|
||||
}(typeof exports === "object" && exports || this));
|
||||
-55
@@ -1,55 +0,0 @@
|
||||
{
|
||||
"_from": "async-foreach@^0.1.3",
|
||||
"_id": "async-foreach@0.1.3",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha1-NhIfhFwFeBct5Bmpfb6x0W7DRUI=",
|
||||
"_location": "/async-foreach",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "async-foreach@^0.1.3",
|
||||
"name": "async-foreach",
|
||||
"escapedName": "async-foreach",
|
||||
"rawSpec": "^0.1.3",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^0.1.3"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/node-sass"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/async-foreach/-/async-foreach-0.1.3.tgz",
|
||||
"_shasum": "36121f845c0578172de419a97dbeb1d16ec34542",
|
||||
"_spec": "async-foreach@^0.1.3",
|
||||
"_where": "O:\\zero\\zero.Web\\node_modules\\node-sass",
|
||||
"author": {
|
||||
"name": "\"Cowboy\" Ben Alman",
|
||||
"url": "http://benalman.com/"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/cowboy/javascript-sync-async-foreach/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {},
|
||||
"deprecated": false,
|
||||
"description": "An optionally-asynchronous forEach with an interesting interface.",
|
||||
"devDependencies": {},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
},
|
||||
"homepage": "http://github.com/cowboy/javascript-sync-async-foreach",
|
||||
"keywords": [
|
||||
"array",
|
||||
"loop",
|
||||
"sync",
|
||||
"async",
|
||||
"foreach"
|
||||
],
|
||||
"main": "lib/foreach",
|
||||
"name": "async-foreach",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/cowboy/javascript-sync-async-foreach.git"
|
||||
},
|
||||
"version": "0.1.3"
|
||||
}
|
||||
-200
@@ -1,200 +0,0 @@
|
||||
/*global require:true, setTimeout:true */
|
||||
var forEach = require('../lib/foreach').forEach;
|
||||
|
||||
exports['foreach'] = {
|
||||
setUp: function(done) {
|
||||
this.order = [];
|
||||
this.track = function() {
|
||||
[].push.apply(this.order, arguments);
|
||||
};
|
||||
done();
|
||||
},
|
||||
'Synchronous': function(test) {
|
||||
test.expect(1);
|
||||
var that = this;
|
||||
|
||||
var arr = ["a", "b", "c"];
|
||||
forEach(arr, function(item, index, arr) {
|
||||
that.track("each", item, index, arr);
|
||||
});
|
||||
|
||||
test.deepEqual(that.order, [
|
||||
"each", "a", 0, arr,
|
||||
"each", "b", 1, arr,
|
||||
"each", "c", 2, arr
|
||||
], "should call eachFn for each array item, in order.");
|
||||
test.done();
|
||||
},
|
||||
'Synchronous, done': function(test) {
|
||||
test.expect(1);
|
||||
var that = this;
|
||||
|
||||
var arr = ["a", "b", "c"];
|
||||
forEach(arr, function(item, index, arr) {
|
||||
that.track("each", item, index, arr);
|
||||
}, function(notAborted, arr) {
|
||||
that.track("done", notAborted, arr);
|
||||
});
|
||||
|
||||
test.deepEqual(that.order, [
|
||||
"each", "a", 0, arr,
|
||||
"each", "b", 1, arr,
|
||||
"each", "c", 2, arr,
|
||||
"done", true, arr
|
||||
], "should call eachFn for each array item, in order, followed by doneFn.");
|
||||
test.done();
|
||||
},
|
||||
'Synchronous, early abort': function(test) {
|
||||
test.expect(1);
|
||||
var that = this;
|
||||
|
||||
var arr = ["a", "b", "c"];
|
||||
forEach(arr, function(item, index, arr) {
|
||||
that.track("each", item, index, arr);
|
||||
if (item === "b") { return false; }
|
||||
}, function(notAborted, arr) {
|
||||
that.track("done", notAborted, arr);
|
||||
});
|
||||
|
||||
test.deepEqual(that.order, [
|
||||
"each", "a", 0, arr,
|
||||
"each", "b", 1, arr,
|
||||
"done", false, arr
|
||||
], "should call eachFn for each array item, in order, followed by doneFn.");
|
||||
test.done();
|
||||
},
|
||||
'Asynchronous': function(test) {
|
||||
test.expect(1);
|
||||
var that = this;
|
||||
|
||||
var arr = ["a", "b", "c"];
|
||||
forEach(arr, function(item, index, arr) {
|
||||
that.track("each", item, index, arr);
|
||||
var done = this.async();
|
||||
setTimeout(done, 10);
|
||||
});
|
||||
|
||||
setTimeout(function() {
|
||||
test.deepEqual(that.order, [
|
||||
"each", "a", 0, arr,
|
||||
"each", "b", 1, arr,
|
||||
"each", "c", 2, arr
|
||||
], "should call eachFn for each array item, in order.");
|
||||
test.done();
|
||||
}, 100);
|
||||
},
|
||||
'Asynchronous, done': function(test) {
|
||||
test.expect(1);
|
||||
var that = this;
|
||||
|
||||
var arr = ["a", "b", "c"];
|
||||
forEach(arr, function(item, index, arr) {
|
||||
that.track("each", item, index, arr);
|
||||
var done = this.async();
|
||||
setTimeout(done, 10);
|
||||
}, function(notAborted, arr) {
|
||||
that.track("done", notAborted, arr);
|
||||
test.deepEqual(that.order, [
|
||||
"each", "a", 0, arr,
|
||||
"each", "b", 1, arr,
|
||||
"each", "c", 2, arr,
|
||||
"done", true, arr
|
||||
], "should call eachFn for each array item, in order, followed by doneFn.");
|
||||
test.done();
|
||||
});
|
||||
},
|
||||
'Asynchronous, early abort': function(test) {
|
||||
test.expect(1);
|
||||
var that = this;
|
||||
|
||||
var arr = ["a", "b", "c"];
|
||||
forEach(arr, function(item, index, arr) {
|
||||
that.track("each", item, index, arr);
|
||||
var done = this.async();
|
||||
setTimeout(function() {
|
||||
done(item !== "b");
|
||||
}, 10);
|
||||
}, function(notAborted, arr) {
|
||||
that.track("done", notAborted, arr);
|
||||
test.deepEqual(that.order, [
|
||||
"each", "a", 0, arr,
|
||||
"each", "b", 1, arr,
|
||||
"done", false, arr
|
||||
], "should call eachFn for each array item, in order, followed by doneFn.");
|
||||
test.done();
|
||||
});
|
||||
},
|
||||
'Not actually asynchronous': function(test) {
|
||||
test.expect(1);
|
||||
var that = this;
|
||||
|
||||
var arr = ["a", "b", "c"];
|
||||
forEach(arr, function(item, index, arr) {
|
||||
that.track("each", item, index, arr);
|
||||
var done = this.async();
|
||||
done();
|
||||
}, function(notAborted, arr) {
|
||||
that.track("done", notAborted, arr);
|
||||
test.deepEqual(that.order, [
|
||||
"each", "a", 0, arr,
|
||||
"each", "b", 1, arr,
|
||||
"each", "c", 2, arr,
|
||||
"done", true, arr
|
||||
], "should call eachFn for each array item, in order, followed by doneFn.");
|
||||
test.done();
|
||||
});
|
||||
},
|
||||
'Not actually asynchronous, early abort': function(test) {
|
||||
test.expect(1);
|
||||
var that = this;
|
||||
|
||||
var arr = ["a", "b", "c"];
|
||||
forEach(arr, function(item, index, arr) {
|
||||
that.track("each", item, index, arr);
|
||||
var done = this.async();
|
||||
done(item !== "b");
|
||||
}, function(notAborted, arr) {
|
||||
that.track("done", notAborted, arr);
|
||||
test.deepEqual(that.order, [
|
||||
"each", "a", 0, arr,
|
||||
"each", "b", 1, arr,
|
||||
"done", false, arr
|
||||
], "should call eachFn for each array item, in order, followed by doneFn.");
|
||||
test.done();
|
||||
});
|
||||
},
|
||||
'Sparse array support': function(test) {
|
||||
test.expect(1);
|
||||
var that = this;
|
||||
|
||||
var arr = [];
|
||||
arr[0] = "a";
|
||||
arr[9] = "z";
|
||||
|
||||
forEach(arr, function(item, index, arr) {
|
||||
that.track("each", item, index, arr);
|
||||
});
|
||||
|
||||
test.deepEqual(that.order, [
|
||||
"each", "a", 0, arr,
|
||||
"each", "z", 9, arr
|
||||
], "should skip nonexistent array items.");
|
||||
test.done();
|
||||
},
|
||||
'Invalid length sanitization': function(test) {
|
||||
test.expect(1);
|
||||
var that = this;
|
||||
|
||||
var obj = {length: 4294967299, 0: "a", 2: "b", 3: "c" };
|
||||
|
||||
forEach(obj, function(item, index, arr) {
|
||||
that.track("each", item, index, arr);
|
||||
});
|
||||
|
||||
test.deepEqual(that.order, [
|
||||
"each", "a", 0, obj,
|
||||
"each", "b", 2, obj
|
||||
], "should sanitize length property (ToUint32).");
|
||||
test.done();
|
||||
}
|
||||
};
|
||||
-2
@@ -1,2 +0,0 @@
|
||||
coverage
|
||||
.nyc_output
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"check-coverage": false,
|
||||
"lines": 99,
|
||||
"statements": 99,
|
||||
"functions": 99,
|
||||
"branches": 99,
|
||||
"include": [
|
||||
"index.js"
|
||||
]
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- "6"
|
||||
- "8"
|
||||
- "10"
|
||||
- "node"
|
||||
script: npm run travis
|
||||
cache:
|
||||
yarn: true
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
The MIT License (MIT)
|
||||
Copyright (c) 2017 Samuel Reed <samuel.trace.reed@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.
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
function Queue(options) {
|
||||
if (!(this instanceof Queue)) {
|
||||
return new Queue(options);
|
||||
}
|
||||
|
||||
options = options || {};
|
||||
this.concurrency = options.concurrency || Infinity;
|
||||
this.pending = 0;
|
||||
this.jobs = [];
|
||||
this.cbs = [];
|
||||
this._done = done.bind(this);
|
||||
}
|
||||
|
||||
var arrayAddMethods = [
|
||||
'push',
|
||||
'unshift',
|
||||
'splice'
|
||||
];
|
||||
|
||||
arrayAddMethods.forEach(function(method) {
|
||||
Queue.prototype[method] = function() {
|
||||
var methodResult = Array.prototype[method].apply(this.jobs, arguments);
|
||||
this._run();
|
||||
return methodResult;
|
||||
};
|
||||
});
|
||||
|
||||
Object.defineProperty(Queue.prototype, 'length', {
|
||||
get: function() {
|
||||
return this.pending + this.jobs.length;
|
||||
}
|
||||
});
|
||||
|
||||
Queue.prototype._run = function() {
|
||||
if (this.pending === this.concurrency) {
|
||||
return;
|
||||
}
|
||||
if (this.jobs.length) {
|
||||
var job = this.jobs.shift();
|
||||
this.pending++;
|
||||
job(this._done);
|
||||
this._run();
|
||||
}
|
||||
|
||||
if (this.pending === 0) {
|
||||
while (this.cbs.length !== 0) {
|
||||
var cb = this.cbs.pop();
|
||||
process.nextTick(cb);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Queue.prototype.onDone = function(cb) {
|
||||
if (typeof cb === 'function') {
|
||||
this.cbs.push(cb);
|
||||
this._run();
|
||||
}
|
||||
};
|
||||
|
||||
function done() {
|
||||
this.pending--;
|
||||
this._run();
|
||||
}
|
||||
|
||||
module.exports = Queue;
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
{
|
||||
"_from": "async-limiter@~1.0.0",
|
||||
"_id": "async-limiter@1.0.1",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ==",
|
||||
"_location": "/async-limiter",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "async-limiter@~1.0.0",
|
||||
"name": "async-limiter",
|
||||
"escapedName": "async-limiter",
|
||||
"rawSpec": "~1.0.0",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "~1.0.0"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/ws"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.1.tgz",
|
||||
"_shasum": "dd379e94f0db8310b08291f9d64c3209766617fd",
|
||||
"_spec": "async-limiter@~1.0.0",
|
||||
"_where": "O:\\zero\\zero.Web\\node_modules\\ws",
|
||||
"author": {
|
||||
"name": "Samuel Reed"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/strml/async-limiter/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {},
|
||||
"deprecated": false,
|
||||
"description": "asynchronous function queue with adjustable concurrency",
|
||||
"devDependencies": {
|
||||
"coveralls": "^3.0.3",
|
||||
"eslint": "^5.16.0",
|
||||
"eslint-plugin-mocha": "^5.3.0",
|
||||
"intelli-espower-loader": "^1.0.1",
|
||||
"mocha": "^6.1.4",
|
||||
"nyc": "^14.1.1",
|
||||
"power-assert": "^1.6.1"
|
||||
},
|
||||
"homepage": "https://github.com/strml/async-limiter#readme",
|
||||
"keywords": [
|
||||
"throttle",
|
||||
"async",
|
||||
"limiter",
|
||||
"asynchronous",
|
||||
"job",
|
||||
"task",
|
||||
"concurrency",
|
||||
"concurrent"
|
||||
],
|
||||
"license": "MIT",
|
||||
"name": "async-limiter",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/strml/async-limiter.git"
|
||||
},
|
||||
"scripts": {
|
||||
"coverage": "nyc npm test && nyc report --reporter=text-lcov | coveralls",
|
||||
"example": "node example",
|
||||
"lint": "eslint .",
|
||||
"test": "mocha --require intelli-espower-loader test/",
|
||||
"travis": "npm run lint && npm run test"
|
||||
},
|
||||
"version": "1.0.1"
|
||||
}
|
||||
-132
@@ -1,132 +0,0 @@
|
||||
# Async-Limiter
|
||||
|
||||
A module for limiting concurrent asynchronous actions in flight. Forked from [queue](https://github.com/jessetane/queue).
|
||||
|
||||
[](http://www.npmjs.org/async-limiter)
|
||||
[](https://travis-ci.org/STRML/async-limiter)
|
||||
[](https://coveralls.io/r/STRML/async-limiter)
|
||||
|
||||
This module exports a class `Limiter` that implements some of the `Array` API.
|
||||
Pass async functions (ones that accept a callback or return a promise) to an instance's additive array methods.
|
||||
|
||||
## Motivation
|
||||
|
||||
Certain functions, like `zlib`, have [undesirable behavior](https://github.com/nodejs/node/issues/8871#issuecomment-250915913) when
|
||||
run at infinite concurrency.
|
||||
|
||||
In this case, it is actually faster, and takes far less memory, to limit concurrency.
|
||||
|
||||
This module should do the absolute minimum work necessary to queue up functions. PRs are welcome that would
|
||||
make this module faster or lighter, but new functionality is not desired.
|
||||
|
||||
Style should confirm to nodejs/node style.
|
||||
|
||||
## Example
|
||||
|
||||
``` javascript
|
||||
var Limiter = require('async-limiter')
|
||||
|
||||
var t = new Limiter({concurrency: 2});
|
||||
var results = []
|
||||
|
||||
// add jobs using the familiar Array API
|
||||
t.push(function (cb) {
|
||||
results.push('two')
|
||||
cb()
|
||||
})
|
||||
|
||||
t.push(
|
||||
function (cb) {
|
||||
results.push('four')
|
||||
cb()
|
||||
},
|
||||
function (cb) {
|
||||
results.push('five')
|
||||
cb()
|
||||
}
|
||||
)
|
||||
|
||||
t.unshift(function (cb) {
|
||||
results.push('one')
|
||||
cb()
|
||||
})
|
||||
|
||||
t.splice(2, 0, function (cb) {
|
||||
results.push('three')
|
||||
cb()
|
||||
})
|
||||
|
||||
// Jobs run automatically. If you want a callback when all are done,
|
||||
// call 'onDone()'.
|
||||
t.onDone(function () {
|
||||
console.log('all done:', results)
|
||||
})
|
||||
```
|
||||
|
||||
## Zlib Example
|
||||
|
||||
```js
|
||||
const zlib = require('zlib');
|
||||
const Limiter = require('async-limiter');
|
||||
|
||||
const message = {some: "data"};
|
||||
const payload = new Buffer(JSON.stringify(message));
|
||||
|
||||
// Try with different concurrency values to see how this actually
|
||||
// slows significantly with higher concurrency!
|
||||
//
|
||||
// 5: 1398.607ms
|
||||
// 10: 1375.668ms
|
||||
// Infinity: 4423.300ms
|
||||
//
|
||||
const t = new Limiter({concurrency: 5});
|
||||
function deflate(payload, cb) {
|
||||
t.push(function(done) {
|
||||
zlib.deflate(payload, function(err, buffer) {
|
||||
done();
|
||||
cb(err, buffer);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
console.time('deflate');
|
||||
for(let i = 0; i < 30000; ++i) {
|
||||
deflate(payload, function (err, buffer) {});
|
||||
}
|
||||
t.onDone(function() {
|
||||
console.timeEnd('deflate');
|
||||
});
|
||||
```
|
||||
|
||||
## Install
|
||||
|
||||
`npm install async-limiter`
|
||||
|
||||
## Test
|
||||
|
||||
`npm test`
|
||||
|
||||
## API
|
||||
|
||||
### `var t = new Limiter([opts])`
|
||||
Constructor. `opts` may contain inital values for:
|
||||
* `t.concurrency`
|
||||
|
||||
## Instance methods
|
||||
|
||||
### `t.onDone(fn)`
|
||||
`fn` will be called once and only once, when the queue is empty.
|
||||
|
||||
## Instance methods mixed in from `Array`
|
||||
Mozilla has docs on how these methods work [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array).
|
||||
### `t.push(element1, ..., elementN)`
|
||||
### `t.unshift(element1, ..., elementN)`
|
||||
### `t.splice(index , howMany[, element1[, ...[, elementN]]])`
|
||||
|
||||
## Properties
|
||||
### `t.concurrency`
|
||||
Max number of jobs the queue should process concurrently, defaults to `Infinity`.
|
||||
|
||||
### `t.length`
|
||||
Jobs pending + jobs to process (readonly).
|
||||
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = until;
|
||||
|
||||
var _whilst = require('./whilst');
|
||||
|
||||
var _whilst2 = _interopRequireDefault(_whilst);
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
/**
|
||||
* Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when
|
||||
* stopped, or an error occurs. `callback` will be passed an error and any
|
||||
* arguments passed to the final `iteratee`'s callback.
|
||||
*
|
||||
* The inverse of [whilst]{@link module:ControlFlow.whilst}.
|
||||
*
|
||||
* @name until
|
||||
* @static
|
||||
* @memberOf module:ControlFlow
|
||||
* @method
|
||||
* @see [async.whilst]{@link module:ControlFlow.whilst}
|
||||
* @category Control Flow
|
||||
* @param {Function} test - synchronous truth test to perform before each
|
||||
* execution of `iteratee`. Invoked with ().
|
||||
* @param {AsyncFunction} iteratee - An async function which is called each time
|
||||
* `test` fails. Invoked with (callback).
|
||||
* @param {Function} [callback] - A callback which is called after the test
|
||||
* function has passed and repeated execution of `iteratee` has stopped. `callback`
|
||||
* will be passed an error and any arguments passed to the final `iteratee`'s
|
||||
* callback. Invoked with (err, [results]);
|
||||
*/
|
||||
function until(test, iteratee, callback) {
|
||||
(0, _whilst2.default)(function () {
|
||||
return !test.apply(this, arguments);
|
||||
}, iteratee, callback);
|
||||
}
|
||||
module.exports = exports['default'];
|
||||
-113
@@ -1,113 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
|
||||
exports.default = function (tasks, callback) {
|
||||
callback = (0, _once2.default)(callback || _noop2.default);
|
||||
if (!(0, _isArray2.default)(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));
|
||||
if (!tasks.length) return callback();
|
||||
var taskIndex = 0;
|
||||
|
||||
function nextTask(args) {
|
||||
var task = (0, _wrapAsync2.default)(tasks[taskIndex++]);
|
||||
args.push((0, _onlyOnce2.default)(next));
|
||||
task.apply(null, args);
|
||||
}
|
||||
|
||||
function next(err /*, ...args*/) {
|
||||
if (err || taskIndex === tasks.length) {
|
||||
return callback.apply(null, arguments);
|
||||
}
|
||||
nextTask((0, _slice2.default)(arguments, 1));
|
||||
}
|
||||
|
||||
nextTask([]);
|
||||
};
|
||||
|
||||
var _isArray = require('lodash/isArray');
|
||||
|
||||
var _isArray2 = _interopRequireDefault(_isArray);
|
||||
|
||||
var _noop = require('lodash/noop');
|
||||
|
||||
var _noop2 = _interopRequireDefault(_noop);
|
||||
|
||||
var _once = require('./internal/once');
|
||||
|
||||
var _once2 = _interopRequireDefault(_once);
|
||||
|
||||
var _slice = require('./internal/slice');
|
||||
|
||||
var _slice2 = _interopRequireDefault(_slice);
|
||||
|
||||
var _onlyOnce = require('./internal/onlyOnce');
|
||||
|
||||
var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
|
||||
|
||||
var _wrapAsync = require('./internal/wrapAsync');
|
||||
|
||||
var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
module.exports = exports['default'];
|
||||
|
||||
/**
|
||||
* Runs the `tasks` array of functions in series, each passing their results to
|
||||
* the next in the array. However, if any of the `tasks` pass an error to their
|
||||
* own callback, the next function is not executed, and the main `callback` is
|
||||
* immediately called with the error.
|
||||
*
|
||||
* @name waterfall
|
||||
* @static
|
||||
* @memberOf module:ControlFlow
|
||||
* @method
|
||||
* @category Control Flow
|
||||
* @param {Array} tasks - An array of [async functions]{@link AsyncFunction}
|
||||
* to run.
|
||||
* Each function should complete with any number of `result` values.
|
||||
* The `result` values will be passed as arguments, in order, to the next task.
|
||||
* @param {Function} [callback] - An optional callback to run once all the
|
||||
* functions have completed. This will be passed the results of the last task's
|
||||
* callback. Invoked with (err, [results]).
|
||||
* @returns undefined
|
||||
* @example
|
||||
*
|
||||
* async.waterfall([
|
||||
* function(callback) {
|
||||
* callback(null, 'one', 'two');
|
||||
* },
|
||||
* function(arg1, arg2, callback) {
|
||||
* // arg1 now equals 'one' and arg2 now equals 'two'
|
||||
* callback(null, 'three');
|
||||
* },
|
||||
* function(arg1, callback) {
|
||||
* // arg1 now equals 'three'
|
||||
* callback(null, 'done');
|
||||
* }
|
||||
* ], function (err, result) {
|
||||
* // result now equals 'done'
|
||||
* });
|
||||
*
|
||||
* // Or, with named functions:
|
||||
* async.waterfall([
|
||||
* myFirstFunction,
|
||||
* mySecondFunction,
|
||||
* myLastFunction,
|
||||
* ], function (err, result) {
|
||||
* // result now equals 'done'
|
||||
* });
|
||||
* function myFirstFunction(callback) {
|
||||
* callback(null, 'one', 'two');
|
||||
* }
|
||||
* function mySecondFunction(arg1, arg2, callback) {
|
||||
* // arg1 now equals 'one' and arg2 now equals 'two'
|
||||
* callback(null, 'three');
|
||||
* }
|
||||
* function myLastFunction(arg1, callback) {
|
||||
* // arg1 now equals 'three'
|
||||
* callback(null, 'done');
|
||||
* }
|
||||
*/
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = whilst;
|
||||
|
||||
var _noop = require('lodash/noop');
|
||||
|
||||
var _noop2 = _interopRequireDefault(_noop);
|
||||
|
||||
var _slice = require('./internal/slice');
|
||||
|
||||
var _slice2 = _interopRequireDefault(_slice);
|
||||
|
||||
var _onlyOnce = require('./internal/onlyOnce');
|
||||
|
||||
var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
|
||||
|
||||
var _wrapAsync = require('./internal/wrapAsync');
|
||||
|
||||
var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
/**
|
||||
* Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when
|
||||
* stopped, or an error occurs.
|
||||
*
|
||||
* @name whilst
|
||||
* @static
|
||||
* @memberOf module:ControlFlow
|
||||
* @method
|
||||
* @category Control Flow
|
||||
* @param {Function} test - synchronous truth test to perform before each
|
||||
* execution of `iteratee`. Invoked with ().
|
||||
* @param {AsyncFunction} iteratee - An async function which is called each time
|
||||
* `test` passes. Invoked with (callback).
|
||||
* @param {Function} [callback] - A callback which is called after the test
|
||||
* function has failed and repeated execution of `iteratee` has stopped. `callback`
|
||||
* will be passed an error and any arguments passed to the final `iteratee`'s
|
||||
* callback. Invoked with (err, [results]);
|
||||
* @returns undefined
|
||||
* @example
|
||||
*
|
||||
* var count = 0;
|
||||
* async.whilst(
|
||||
* function() { return count < 5; },
|
||||
* function(callback) {
|
||||
* count++;
|
||||
* setTimeout(function() {
|
||||
* callback(null, count);
|
||||
* }, 1000);
|
||||
* },
|
||||
* function (err, n) {
|
||||
* // 5 seconds have passed, n = 5
|
||||
* }
|
||||
* );
|
||||
*/
|
||||
function whilst(test, iteratee, callback) {
|
||||
callback = (0, _onlyOnce2.default)(callback || _noop2.default);
|
||||
var _iteratee = (0, _wrapAsync2.default)(iteratee);
|
||||
if (!test()) return callback(null);
|
||||
var next = function (err /*, ...args*/) {
|
||||
if (err) return callback(err);
|
||||
if (test()) return _iteratee(next);
|
||||
var args = (0, _slice2.default)(arguments, 1);
|
||||
callback.apply(null, [null].concat(args));
|
||||
};
|
||||
_iteratee(next);
|
||||
}
|
||||
module.exports = exports['default'];
|
||||
-110
@@ -1,110 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = asyncify;
|
||||
|
||||
var _isObject = require('lodash/isObject');
|
||||
|
||||
var _isObject2 = _interopRequireDefault(_isObject);
|
||||
|
||||
var _initialParams = require('./internal/initialParams');
|
||||
|
||||
var _initialParams2 = _interopRequireDefault(_initialParams);
|
||||
|
||||
var _setImmediate = require('./internal/setImmediate');
|
||||
|
||||
var _setImmediate2 = _interopRequireDefault(_setImmediate);
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
/**
|
||||
* Take a sync function and make it async, passing its return value to a
|
||||
* callback. This is useful for plugging sync functions into a waterfall,
|
||||
* series, or other async functions. Any arguments passed to the generated
|
||||
* function will be passed to the wrapped function (except for the final
|
||||
* callback argument). Errors thrown will be passed to the callback.
|
||||
*
|
||||
* If the function passed to `asyncify` returns a Promise, that promises's
|
||||
* resolved/rejected state will be used to call the callback, rather than simply
|
||||
* the synchronous return value.
|
||||
*
|
||||
* This also means you can asyncify ES2017 `async` functions.
|
||||
*
|
||||
* @name asyncify
|
||||
* @static
|
||||
* @memberOf module:Utils
|
||||
* @method
|
||||
* @alias wrapSync
|
||||
* @category Util
|
||||
* @param {Function} func - The synchronous function, or Promise-returning
|
||||
* function to convert to an {@link AsyncFunction}.
|
||||
* @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be
|
||||
* invoked with `(args..., callback)`.
|
||||
* @example
|
||||
*
|
||||
* // passing a regular synchronous function
|
||||
* async.waterfall([
|
||||
* async.apply(fs.readFile, filename, "utf8"),
|
||||
* async.asyncify(JSON.parse),
|
||||
* function (data, next) {
|
||||
* // data is the result of parsing the text.
|
||||
* // If there was a parsing error, it would have been caught.
|
||||
* }
|
||||
* ], callback);
|
||||
*
|
||||
* // passing a function returning a promise
|
||||
* async.waterfall([
|
||||
* async.apply(fs.readFile, filename, "utf8"),
|
||||
* async.asyncify(function (contents) {
|
||||
* return db.model.create(contents);
|
||||
* }),
|
||||
* function (model, next) {
|
||||
* // `model` is the instantiated model object.
|
||||
* // If there was an error, this function would be skipped.
|
||||
* }
|
||||
* ], callback);
|
||||
*
|
||||
* // es2017 example, though `asyncify` is not needed if your JS environment
|
||||
* // supports async functions out of the box
|
||||
* var q = async.queue(async.asyncify(async function(file) {
|
||||
* var intermediateStep = await processFile(file);
|
||||
* return await somePromise(intermediateStep)
|
||||
* }));
|
||||
*
|
||||
* q.push(files);
|
||||
*/
|
||||
function asyncify(func) {
|
||||
return (0, _initialParams2.default)(function (args, callback) {
|
||||
var result;
|
||||
try {
|
||||
result = func.apply(this, args);
|
||||
} catch (e) {
|
||||
return callback(e);
|
||||
}
|
||||
// if result is Promise object
|
||||
if ((0, _isObject2.default)(result) && typeof result.then === 'function') {
|
||||
result.then(function (value) {
|
||||
invokeCallback(callback, null, value);
|
||||
}, function (err) {
|
||||
invokeCallback(callback, err.message ? err : new Error(err));
|
||||
});
|
||||
} else {
|
||||
callback(null, result);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function invokeCallback(callback, error, value) {
|
||||
try {
|
||||
callback(error, value);
|
||||
} catch (e) {
|
||||
(0, _setImmediate2.default)(rethrow, e);
|
||||
}
|
||||
}
|
||||
|
||||
function rethrow(error) {
|
||||
throw error;
|
||||
}
|
||||
module.exports = exports['default'];
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016 Alex Indigo
|
||||
|
||||
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.
|
||||
-233
@@ -1,233 +0,0 @@
|
||||
# asynckit [](https://www.npmjs.com/package/asynckit)
|
||||
|
||||
Minimal async jobs utility library, with streams support.
|
||||
|
||||
[](https://travis-ci.org/alexindigo/asynckit)
|
||||
[](https://travis-ci.org/alexindigo/asynckit)
|
||||
[](https://ci.appveyor.com/project/alexindigo/asynckit)
|
||||
|
||||
[](https://coveralls.io/github/alexindigo/asynckit?branch=master)
|
||||
[](https://david-dm.org/alexindigo/asynckit)
|
||||
[](https://www.bithound.io/github/alexindigo/asynckit)
|
||||
|
||||
<!-- [](https://www.npmjs.com/package/reamde) -->
|
||||
|
||||
AsyncKit provides harness for `parallel` and `serial` iterators over list of items represented by arrays or objects.
|
||||
Optionally it accepts abort function (should be synchronously return by iterator for each item), and terminates left over jobs upon an error event. For specific iteration order built-in (`ascending` and `descending`) and custom sort helpers also supported, via `asynckit.serialOrdered` method.
|
||||
|
||||
It ensures async operations to keep behavior more stable and prevent `Maximum call stack size exceeded` errors, from sync iterators.
|
||||
|
||||
| compression | size |
|
||||
| :----------------- | -------: |
|
||||
| asynckit.js | 12.34 kB |
|
||||
| asynckit.min.js | 4.11 kB |
|
||||
| asynckit.min.js.gz | 1.47 kB |
|
||||
|
||||
|
||||
## Install
|
||||
|
||||
```sh
|
||||
$ npm install --save asynckit
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Parallel Jobs
|
||||
|
||||
Runs iterator over provided array in parallel. Stores output in the `result` array,
|
||||
on the matching positions. In unlikely event of an error from one of the jobs,
|
||||
will terminate rest of the active jobs (if abort function is provided)
|
||||
and return error along with salvaged data to the main callback function.
|
||||
|
||||
#### Input Array
|
||||
|
||||
```javascript
|
||||
var parallel = require('asynckit').parallel
|
||||
, assert = require('assert')
|
||||
;
|
||||
|
||||
var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
|
||||
, expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ]
|
||||
, expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ]
|
||||
, target = []
|
||||
;
|
||||
|
||||
parallel(source, asyncJob, function(err, result)
|
||||
{
|
||||
assert.deepEqual(result, expectedResult);
|
||||
assert.deepEqual(target, expectedTarget);
|
||||
});
|
||||
|
||||
// async job accepts one element from the array
|
||||
// and a callback function
|
||||
function asyncJob(item, cb)
|
||||
{
|
||||
// different delays (in ms) per item
|
||||
var delay = item * 25;
|
||||
|
||||
// pretend different jobs take different time to finish
|
||||
// and not in consequential order
|
||||
var timeoutId = setTimeout(function() {
|
||||
target.push(item);
|
||||
cb(null, item * 2);
|
||||
}, delay);
|
||||
|
||||
// allow to cancel "leftover" jobs upon error
|
||||
// return function, invoking of which will abort this job
|
||||
return clearTimeout.bind(null, timeoutId);
|
||||
}
|
||||
```
|
||||
|
||||
More examples could be found in [test/test-parallel-array.js](test/test-parallel-array.js).
|
||||
|
||||
#### Input Object
|
||||
|
||||
Also it supports named jobs, listed via object.
|
||||
|
||||
```javascript
|
||||
var parallel = require('asynckit/parallel')
|
||||
, assert = require('assert')
|
||||
;
|
||||
|
||||
var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 }
|
||||
, expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 }
|
||||
, expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ]
|
||||
, expectedKeys = [ 'first', 'one', 'two', 'four', 'eight', 'sixteen', 'thirtyTwo', 'sixtyFour' ]
|
||||
, target = []
|
||||
, keys = []
|
||||
;
|
||||
|
||||
parallel(source, asyncJob, function(err, result)
|
||||
{
|
||||
assert.deepEqual(result, expectedResult);
|
||||
assert.deepEqual(target, expectedTarget);
|
||||
assert.deepEqual(keys, expectedKeys);
|
||||
});
|
||||
|
||||
// supports full value, key, callback (shortcut) interface
|
||||
function asyncJob(item, key, cb)
|
||||
{
|
||||
// different delays (in ms) per item
|
||||
var delay = item * 25;
|
||||
|
||||
// pretend different jobs take different time to finish
|
||||
// and not in consequential order
|
||||
var timeoutId = setTimeout(function() {
|
||||
keys.push(key);
|
||||
target.push(item);
|
||||
cb(null, item * 2);
|
||||
}, delay);
|
||||
|
||||
// allow to cancel "leftover" jobs upon error
|
||||
// return function, invoking of which will abort this job
|
||||
return clearTimeout.bind(null, timeoutId);
|
||||
}
|
||||
```
|
||||
|
||||
More examples could be found in [test/test-parallel-object.js](test/test-parallel-object.js).
|
||||
|
||||
### Serial Jobs
|
||||
|
||||
Runs iterator over provided array sequentially. Stores output in the `result` array,
|
||||
on the matching positions. In unlikely event of an error from one of the jobs,
|
||||
will not proceed to the rest of the items in the list
|
||||
and return error along with salvaged data to the main callback function.
|
||||
|
||||
#### Input Array
|
||||
|
||||
```javascript
|
||||
var serial = require('asynckit/serial')
|
||||
, assert = require('assert')
|
||||
;
|
||||
|
||||
var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
|
||||
, expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ]
|
||||
, expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ]
|
||||
, target = []
|
||||
;
|
||||
|
||||
serial(source, asyncJob, function(err, result)
|
||||
{
|
||||
assert.deepEqual(result, expectedResult);
|
||||
assert.deepEqual(target, expectedTarget);
|
||||
});
|
||||
|
||||
// extended interface (item, key, callback)
|
||||
// also supported for arrays
|
||||
function asyncJob(item, key, cb)
|
||||
{
|
||||
target.push(key);
|
||||
|
||||
// it will be automatically made async
|
||||
// even it iterator "returns" in the same event loop
|
||||
cb(null, item * 2);
|
||||
}
|
||||
```
|
||||
|
||||
More examples could be found in [test/test-serial-array.js](test/test-serial-array.js).
|
||||
|
||||
#### Input Object
|
||||
|
||||
Also it supports named jobs, listed via object.
|
||||
|
||||
```javascript
|
||||
var serial = require('asynckit').serial
|
||||
, assert = require('assert')
|
||||
;
|
||||
|
||||
var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
|
||||
, expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ]
|
||||
, expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ]
|
||||
, target = []
|
||||
;
|
||||
|
||||
var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 }
|
||||
, expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 }
|
||||
, expectedTarget = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
|
||||
, target = []
|
||||
;
|
||||
|
||||
|
||||
serial(source, asyncJob, function(err, result)
|
||||
{
|
||||
assert.deepEqual(result, expectedResult);
|
||||
assert.deepEqual(target, expectedTarget);
|
||||
});
|
||||
|
||||
// shortcut interface (item, callback)
|
||||
// works for object as well as for the arrays
|
||||
function asyncJob(item, cb)
|
||||
{
|
||||
target.push(item);
|
||||
|
||||
// it will be automatically made async
|
||||
// even it iterator "returns" in the same event loop
|
||||
cb(null, item * 2);
|
||||
}
|
||||
```
|
||||
|
||||
More examples could be found in [test/test-serial-object.js](test/test-serial-object.js).
|
||||
|
||||
_Note: Since _object_ is an _unordered_ collection of properties,
|
||||
it may produce unexpected results with sequential iterations.
|
||||
Whenever order of the jobs' execution is important please use `serialOrdered` method._
|
||||
|
||||
### Ordered Serial Iterations
|
||||
|
||||
TBD
|
||||
|
||||
For example [compare-property](compare-property) package.
|
||||
|
||||
### Streaming interface
|
||||
|
||||
TBD
|
||||
|
||||
## Want to Know More?
|
||||
|
||||
More examples can be found in [test folder](test/).
|
||||
|
||||
Or open an [issue](https://github.com/alexindigo/asynckit/issues) with questions and/or suggestions.
|
||||
|
||||
## License
|
||||
|
||||
AsyncKit is licensed under the MIT license.
|
||||
-76
@@ -1,76 +0,0 @@
|
||||
/* eslint no-console: "off" */
|
||||
|
||||
var asynckit = require('./')
|
||||
, async = require('async')
|
||||
, assert = require('assert')
|
||||
, expected = 0
|
||||
;
|
||||
|
||||
var Benchmark = require('benchmark');
|
||||
var suite = new Benchmark.Suite;
|
||||
|
||||
var source = [];
|
||||
for (var z = 1; z < 100; z++)
|
||||
{
|
||||
source.push(z);
|
||||
expected += z;
|
||||
}
|
||||
|
||||
suite
|
||||
// add tests
|
||||
|
||||
.add('async.map', function(deferred)
|
||||
{
|
||||
var total = 0;
|
||||
|
||||
async.map(source,
|
||||
function(i, cb)
|
||||
{
|
||||
setImmediate(function()
|
||||
{
|
||||
total += i;
|
||||
cb(null, total);
|
||||
});
|
||||
},
|
||||
function(err, result)
|
||||
{
|
||||
assert.ifError(err);
|
||||
assert.equal(result[result.length - 1], expected);
|
||||
deferred.resolve();
|
||||
});
|
||||
}, {'defer': true})
|
||||
|
||||
|
||||
.add('asynckit.parallel', function(deferred)
|
||||
{
|
||||
var total = 0;
|
||||
|
||||
asynckit.parallel(source,
|
||||
function(i, cb)
|
||||
{
|
||||
setImmediate(function()
|
||||
{
|
||||
total += i;
|
||||
cb(null, total);
|
||||
});
|
||||
},
|
||||
function(err, result)
|
||||
{
|
||||
assert.ifError(err);
|
||||
assert.equal(result[result.length - 1], expected);
|
||||
deferred.resolve();
|
||||
});
|
||||
}, {'defer': true})
|
||||
|
||||
|
||||
// add listeners
|
||||
.on('cycle', function(ev)
|
||||
{
|
||||
console.log(String(ev.target));
|
||||
})
|
||||
.on('complete', function()
|
||||
{
|
||||
console.log('Fastest is ' + this.filter('fastest').map('name'));
|
||||
})
|
||||
// run async
|
||||
.run({ 'async': true });
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
module.exports =
|
||||
{
|
||||
parallel : require('./parallel.js'),
|
||||
serial : require('./serial.js'),
|
||||
serialOrdered : require('./serialOrdered.js')
|
||||
};
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
// API
|
||||
module.exports = abort;
|
||||
|
||||
/**
|
||||
* Aborts leftover active jobs
|
||||
*
|
||||
* @param {object} state - current state object
|
||||
*/
|
||||
function abort(state)
|
||||
{
|
||||
Object.keys(state.jobs).forEach(clean.bind(state));
|
||||
|
||||
// reset leftover jobs
|
||||
state.jobs = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans up leftover job by invoking abort function for the provided job id
|
||||
*
|
||||
* @this state
|
||||
* @param {string|number} key - job id to abort
|
||||
*/
|
||||
function clean(key)
|
||||
{
|
||||
if (typeof this.jobs[key] == 'function')
|
||||
{
|
||||
this.jobs[key]();
|
||||
}
|
||||
}
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
var defer = require('./defer.js');
|
||||
|
||||
// API
|
||||
module.exports = async;
|
||||
|
||||
/**
|
||||
* Runs provided callback asynchronously
|
||||
* even if callback itself is not
|
||||
*
|
||||
* @param {function} callback - callback to invoke
|
||||
* @returns {function} - augmented callback
|
||||
*/
|
||||
function async(callback)
|
||||
{
|
||||
var isAsync = false;
|
||||
|
||||
// check if async happened
|
||||
defer(function() { isAsync = true; });
|
||||
|
||||
return function async_callback(err, result)
|
||||
{
|
||||
if (isAsync)
|
||||
{
|
||||
callback(err, result);
|
||||
}
|
||||
else
|
||||
{
|
||||
defer(function nextTick_callback()
|
||||
{
|
||||
callback(err, result);
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
module.exports = defer;
|
||||
|
||||
/**
|
||||
* Runs provided function on next iteration of the event loop
|
||||
*
|
||||
* @param {function} fn - function to run
|
||||
*/
|
||||
function defer(fn)
|
||||
{
|
||||
var nextTick = typeof setImmediate == 'function'
|
||||
? setImmediate
|
||||
: (
|
||||
typeof process == 'object' && typeof process.nextTick == 'function'
|
||||
? process.nextTick
|
||||
: null
|
||||
);
|
||||
|
||||
if (nextTick)
|
||||
{
|
||||
nextTick(fn);
|
||||
}
|
||||
else
|
||||
{
|
||||
setTimeout(fn, 0);
|
||||
}
|
||||
}
|
||||
-75
@@ -1,75 +0,0 @@
|
||||
var async = require('./async.js')
|
||||
, abort = require('./abort.js')
|
||||
;
|
||||
|
||||
// API
|
||||
module.exports = iterate;
|
||||
|
||||
/**
|
||||
* Iterates over each job object
|
||||
*
|
||||
* @param {array|object} list - array or object (named list) to iterate over
|
||||
* @param {function} iterator - iterator to run
|
||||
* @param {object} state - current job status
|
||||
* @param {function} callback - invoked when all elements processed
|
||||
*/
|
||||
function iterate(list, iterator, state, callback)
|
||||
{
|
||||
// store current index
|
||||
var key = state['keyedList'] ? state['keyedList'][state.index] : state.index;
|
||||
|
||||
state.jobs[key] = runJob(iterator, key, list[key], function(error, output)
|
||||
{
|
||||
// don't repeat yourself
|
||||
// skip secondary callbacks
|
||||
if (!(key in state.jobs))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// clean up jobs
|
||||
delete state.jobs[key];
|
||||
|
||||
if (error)
|
||||
{
|
||||
// don't process rest of the results
|
||||
// stop still active jobs
|
||||
// and reset the list
|
||||
abort(state);
|
||||
}
|
||||
else
|
||||
{
|
||||
state.results[key] = output;
|
||||
}
|
||||
|
||||
// return salvaged results
|
||||
callback(error, state.results);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs iterator over provided job element
|
||||
*
|
||||
* @param {function} iterator - iterator to invoke
|
||||
* @param {string|number} key - key/index of the element in the list of jobs
|
||||
* @param {mixed} item - job description
|
||||
* @param {function} callback - invoked after iterator is done with the job
|
||||
* @returns {function|mixed} - job abort function or something else
|
||||
*/
|
||||
function runJob(iterator, key, item, callback)
|
||||
{
|
||||
var aborter;
|
||||
|
||||
// allow shortcut if iterator expects only two arguments
|
||||
if (iterator.length == 2)
|
||||
{
|
||||
aborter = iterator(item, async(callback));
|
||||
}
|
||||
// otherwise go with full three arguments
|
||||
else
|
||||
{
|
||||
aborter = iterator(item, key, async(callback));
|
||||
}
|
||||
|
||||
return aborter;
|
||||
}
|
||||
-91
@@ -1,91 +0,0 @@
|
||||
var streamify = require('./streamify.js')
|
||||
, defer = require('./defer.js')
|
||||
;
|
||||
|
||||
// API
|
||||
module.exports = ReadableAsyncKit;
|
||||
|
||||
/**
|
||||
* Base constructor for all streams
|
||||
* used to hold properties/methods
|
||||
*/
|
||||
function ReadableAsyncKit()
|
||||
{
|
||||
ReadableAsyncKit.super_.apply(this, arguments);
|
||||
|
||||
// list of active jobs
|
||||
this.jobs = {};
|
||||
|
||||
// add stream methods
|
||||
this.destroy = destroy;
|
||||
this._start = _start;
|
||||
this._read = _read;
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroys readable stream,
|
||||
* by aborting outstanding jobs
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
function destroy()
|
||||
{
|
||||
if (this.destroyed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.destroyed = true;
|
||||
|
||||
if (typeof this.terminator == 'function')
|
||||
{
|
||||
this.terminator();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts provided jobs in async manner
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
function _start()
|
||||
{
|
||||
// first argument – runner function
|
||||
var runner = arguments[0]
|
||||
// take away first argument
|
||||
, args = Array.prototype.slice.call(arguments, 1)
|
||||
// second argument - input data
|
||||
, input = args[0]
|
||||
// last argument - result callback
|
||||
, endCb = streamify.callback.call(this, args[args.length - 1])
|
||||
;
|
||||
|
||||
args[args.length - 1] = endCb;
|
||||
// third argument - iterator
|
||||
args[1] = streamify.iterator.call(this, args[1]);
|
||||
|
||||
// allow time for proper setup
|
||||
defer(function()
|
||||
{
|
||||
if (!this.destroyed)
|
||||
{
|
||||
this.terminator = runner.apply(null, args);
|
||||
}
|
||||
else
|
||||
{
|
||||
endCb(null, Array.isArray(input) ? [] : {});
|
||||
}
|
||||
}.bind(this));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Implement _read to comply with Readable streams
|
||||
* Doesn't really make sense for flowing object mode
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
function _read()
|
||||
{
|
||||
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
var parallel = require('../parallel.js');
|
||||
|
||||
// API
|
||||
module.exports = ReadableParallel;
|
||||
|
||||
/**
|
||||
* Streaming wrapper to `asynckit.parallel`
|
||||
*
|
||||
* @param {array|object} list - array or object (named list) to iterate over
|
||||
* @param {function} iterator - iterator to run
|
||||
* @param {function} callback - invoked when all elements processed
|
||||
* @returns {stream.Readable#}
|
||||
*/
|
||||
function ReadableParallel(list, iterator, callback)
|
||||
{
|
||||
if (!(this instanceof ReadableParallel))
|
||||
{
|
||||
return new ReadableParallel(list, iterator, callback);
|
||||
}
|
||||
|
||||
// turn on object mode
|
||||
ReadableParallel.super_.call(this, {objectMode: true});
|
||||
|
||||
this._start(parallel, list, iterator, callback);
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
var serial = require('../serial.js');
|
||||
|
||||
// API
|
||||
module.exports = ReadableSerial;
|
||||
|
||||
/**
|
||||
* Streaming wrapper to `asynckit.serial`
|
||||
*
|
||||
* @param {array|object} list - array or object (named list) to iterate over
|
||||
* @param {function} iterator - iterator to run
|
||||
* @param {function} callback - invoked when all elements processed
|
||||
* @returns {stream.Readable#}
|
||||
*/
|
||||
function ReadableSerial(list, iterator, callback)
|
||||
{
|
||||
if (!(this instanceof ReadableSerial))
|
||||
{
|
||||
return new ReadableSerial(list, iterator, callback);
|
||||
}
|
||||
|
||||
// turn on object mode
|
||||
ReadableSerial.super_.call(this, {objectMode: true});
|
||||
|
||||
this._start(serial, list, iterator, callback);
|
||||
}
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
var serialOrdered = require('../serialOrdered.js');
|
||||
|
||||
// API
|
||||
module.exports = ReadableSerialOrdered;
|
||||
// expose sort helpers
|
||||
module.exports.ascending = serialOrdered.ascending;
|
||||
module.exports.descending = serialOrdered.descending;
|
||||
|
||||
/**
|
||||
* Streaming wrapper to `asynckit.serialOrdered`
|
||||
*
|
||||
* @param {array|object} list - array or object (named list) to iterate over
|
||||
* @param {function} iterator - iterator to run
|
||||
* @param {function} sortMethod - custom sort function
|
||||
* @param {function} callback - invoked when all elements processed
|
||||
* @returns {stream.Readable#}
|
||||
*/
|
||||
function ReadableSerialOrdered(list, iterator, sortMethod, callback)
|
||||
{
|
||||
if (!(this instanceof ReadableSerialOrdered))
|
||||
{
|
||||
return new ReadableSerialOrdered(list, iterator, sortMethod, callback);
|
||||
}
|
||||
|
||||
// turn on object mode
|
||||
ReadableSerialOrdered.super_.call(this, {objectMode: true});
|
||||
|
||||
this._start(serialOrdered, list, iterator, sortMethod, callback);
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
// API
|
||||
module.exports = state;
|
||||
|
||||
/**
|
||||
* Creates initial state object
|
||||
* for iteration over list
|
||||
*
|
||||
* @param {array|object} list - list to iterate over
|
||||
* @param {function|null} sortMethod - function to use for keys sort,
|
||||
* or `null` to keep them as is
|
||||
* @returns {object} - initial state object
|
||||
*/
|
||||
function state(list, sortMethod)
|
||||
{
|
||||
var isNamedList = !Array.isArray(list)
|
||||
, initState =
|
||||
{
|
||||
index : 0,
|
||||
keyedList: isNamedList || sortMethod ? Object.keys(list) : null,
|
||||
jobs : {},
|
||||
results : isNamedList ? {} : [],
|
||||
size : isNamedList ? Object.keys(list).length : list.length
|
||||
}
|
||||
;
|
||||
|
||||
if (sortMethod)
|
||||
{
|
||||
// sort array keys based on it's values
|
||||
// sort object's keys just on own merit
|
||||
initState.keyedList.sort(isNamedList ? sortMethod : function(a, b)
|
||||
{
|
||||
return sortMethod(list[a], list[b]);
|
||||
});
|
||||
}
|
||||
|
||||
return initState;
|
||||
}
|
||||
-141
@@ -1,141 +0,0 @@
|
||||
var async = require('./async.js');
|
||||
|
||||
// API
|
||||
module.exports = {
|
||||
iterator: wrapIterator,
|
||||
callback: wrapCallback
|
||||
};
|
||||
|
||||
/**
|
||||
* Wraps iterators with long signature
|
||||
*
|
||||
* @this ReadableAsyncKit#
|
||||
* @param {function} iterator - function to wrap
|
||||
* @returns {function} - wrapped function
|
||||
*/
|
||||
function wrapIterator(iterator)
|
||||
{
|
||||
var stream = this;
|
||||
|
||||
return function(item, key, cb)
|
||||
{
|
||||
var aborter
|
||||
, wrappedCb = async(wrapIteratorCallback.call(stream, cb, key))
|
||||
;
|
||||
|
||||
stream.jobs[key] = wrappedCb;
|
||||
|
||||
// it's either shortcut (item, cb)
|
||||
if (iterator.length == 2)
|
||||
{
|
||||
aborter = iterator(item, wrappedCb);
|
||||
}
|
||||
// or long format (item, key, cb)
|
||||
else
|
||||
{
|
||||
aborter = iterator(item, key, wrappedCb);
|
||||
}
|
||||
|
||||
return aborter;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps provided callback function
|
||||
* allowing to execute snitch function before
|
||||
* real callback
|
||||
*
|
||||
* @this ReadableAsyncKit#
|
||||
* @param {function} callback - function to wrap
|
||||
* @returns {function} - wrapped function
|
||||
*/
|
||||
function wrapCallback(callback)
|
||||
{
|
||||
var stream = this;
|
||||
|
||||
var wrapped = function(error, result)
|
||||
{
|
||||
return finisher.call(stream, error, result, callback);
|
||||
};
|
||||
|
||||
return wrapped;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps provided iterator callback function
|
||||
* makes sure snitch only called once,
|
||||
* but passes secondary calls to the original callback
|
||||
*
|
||||
* @this ReadableAsyncKit#
|
||||
* @param {function} callback - callback to wrap
|
||||
* @param {number|string} key - iteration key
|
||||
* @returns {function} wrapped callback
|
||||
*/
|
||||
function wrapIteratorCallback(callback, key)
|
||||
{
|
||||
var stream = this;
|
||||
|
||||
return function(error, output)
|
||||
{
|
||||
// don't repeat yourself
|
||||
if (!(key in stream.jobs))
|
||||
{
|
||||
callback(error, output);
|
||||
return;
|
||||
}
|
||||
|
||||
// clean up jobs
|
||||
delete stream.jobs[key];
|
||||
|
||||
return streamer.call(stream, error, {key: key, value: output}, callback);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream wrapper for iterator callback
|
||||
*
|
||||
* @this ReadableAsyncKit#
|
||||
* @param {mixed} error - error response
|
||||
* @param {mixed} output - iterator output
|
||||
* @param {function} callback - callback that expects iterator results
|
||||
*/
|
||||
function streamer(error, output, callback)
|
||||
{
|
||||
if (error && !this.error)
|
||||
{
|
||||
this.error = error;
|
||||
this.pause();
|
||||
this.emit('error', error);
|
||||
// send back value only, as expected
|
||||
callback(error, output && output.value);
|
||||
return;
|
||||
}
|
||||
|
||||
// stream stuff
|
||||
this.push(output);
|
||||
|
||||
// back to original track
|
||||
// send back value only, as expected
|
||||
callback(error, output && output.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream wrapper for finishing callback
|
||||
*
|
||||
* @this ReadableAsyncKit#
|
||||
* @param {mixed} error - error response
|
||||
* @param {mixed} output - iterator output
|
||||
* @param {function} callback - callback that expects final results
|
||||
*/
|
||||
function finisher(error, output, callback)
|
||||
{
|
||||
// signal end of the stream
|
||||
// only for successfully finished streams
|
||||
if (!error)
|
||||
{
|
||||
this.push(null);
|
||||
}
|
||||
|
||||
// back to original track
|
||||
callback(error, output);
|
||||
}
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
var abort = require('./abort.js')
|
||||
, async = require('./async.js')
|
||||
;
|
||||
|
||||
// API
|
||||
module.exports = terminator;
|
||||
|
||||
/**
|
||||
* Terminates jobs in the attached state context
|
||||
*
|
||||
* @this AsyncKitState#
|
||||
* @param {function} callback - final callback to invoke after termination
|
||||
*/
|
||||
function terminator(callback)
|
||||
{
|
||||
if (!Object.keys(this.jobs).length)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// fast forward iteration index
|
||||
this.index = this.size;
|
||||
|
||||
// abort jobs
|
||||
abort(this);
|
||||
|
||||
// send back results we have so far
|
||||
async(callback)(null, this.results);
|
||||
}
|
||||
-91
@@ -1,91 +0,0 @@
|
||||
{
|
||||
"_from": "asynckit@^0.4.0",
|
||||
"_id": "asynckit@0.4.0",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=",
|
||||
"_location": "/asynckit",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "asynckit@^0.4.0",
|
||||
"name": "asynckit",
|
||||
"escapedName": "asynckit",
|
||||
"rawSpec": "^0.4.0",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^0.4.0"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/form-data"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
|
||||
"_shasum": "c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79",
|
||||
"_spec": "asynckit@^0.4.0",
|
||||
"_where": "O:\\zero\\zero.Web\\node_modules\\form-data",
|
||||
"author": {
|
||||
"name": "Alex Indigo",
|
||||
"email": "iam@alexindigo.com"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/alexindigo/asynckit/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {},
|
||||
"deprecated": false,
|
||||
"description": "Minimal async jobs utility library, with streams support",
|
||||
"devDependencies": {
|
||||
"browserify": "^13.0.0",
|
||||
"browserify-istanbul": "^2.0.0",
|
||||
"coveralls": "^2.11.9",
|
||||
"eslint": "^2.9.0",
|
||||
"istanbul": "^0.4.3",
|
||||
"obake": "^0.1.2",
|
||||
"phantomjs-prebuilt": "^2.1.7",
|
||||
"pre-commit": "^1.1.3",
|
||||
"reamde": "^1.1.0",
|
||||
"rimraf": "^2.5.2",
|
||||
"size-table": "^0.2.0",
|
||||
"tap-spec": "^4.1.1",
|
||||
"tape": "^4.5.1"
|
||||
},
|
||||
"homepage": "https://github.com/alexindigo/asynckit#readme",
|
||||
"keywords": [
|
||||
"async",
|
||||
"jobs",
|
||||
"parallel",
|
||||
"serial",
|
||||
"iterator",
|
||||
"array",
|
||||
"object",
|
||||
"stream",
|
||||
"destroy",
|
||||
"terminate",
|
||||
"abort"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "index.js",
|
||||
"name": "asynckit",
|
||||
"pre-commit": [
|
||||
"clean",
|
||||
"lint",
|
||||
"test",
|
||||
"browser",
|
||||
"report",
|
||||
"size"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/alexindigo/asynckit.git"
|
||||
},
|
||||
"scripts": {
|
||||
"browser": "browserify -t browserify-istanbul test/lib/browserify_adjustment.js test/test-*.js | obake --coverage | tap-spec",
|
||||
"clean": "rimraf coverage",
|
||||
"debug": "tape test/test-*.js",
|
||||
"lint": "eslint *.js lib/*.js test/*.js",
|
||||
"report": "istanbul report",
|
||||
"size": "browserify index.js | size-table asynckit",
|
||||
"test": "istanbul cover --reporter=json tape -- 'test/test-*.js' | tap-spec",
|
||||
"win-test": "tape test/test-*.js"
|
||||
},
|
||||
"version": "0.4.0"
|
||||
}
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
var iterate = require('./lib/iterate.js')
|
||||
, initState = require('./lib/state.js')
|
||||
, terminator = require('./lib/terminator.js')
|
||||
;
|
||||
|
||||
// Public API
|
||||
module.exports = parallel;
|
||||
|
||||
/**
|
||||
* Runs iterator over provided array elements in parallel
|
||||
*
|
||||
* @param {array|object} list - array or object (named list) to iterate over
|
||||
* @param {function} iterator - iterator to run
|
||||
* @param {function} callback - invoked when all elements processed
|
||||
* @returns {function} - jobs terminator
|
||||
*/
|
||||
function parallel(list, iterator, callback)
|
||||
{
|
||||
var state = initState(list);
|
||||
|
||||
while (state.index < (state['keyedList'] || list).length)
|
||||
{
|
||||
iterate(list, iterator, state, function(error, result)
|
||||
{
|
||||
if (error)
|
||||
{
|
||||
callback(error, result);
|
||||
return;
|
||||
}
|
||||
|
||||
// looks like it's the last one
|
||||
if (Object.keys(state.jobs).length === 0)
|
||||
{
|
||||
callback(null, state.results);
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
state.index++;
|
||||
}
|
||||
|
||||
return terminator.bind(state, callback);
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
var serialOrdered = require('./serialOrdered.js');
|
||||
|
||||
// Public API
|
||||
module.exports = serial;
|
||||
|
||||
/**
|
||||
* Runs iterator over provided array elements in series
|
||||
*
|
||||
* @param {array|object} list - array or object (named list) to iterate over
|
||||
* @param {function} iterator - iterator to run
|
||||
* @param {function} callback - invoked when all elements processed
|
||||
* @returns {function} - jobs terminator
|
||||
*/
|
||||
function serial(list, iterator, callback)
|
||||
{
|
||||
return serialOrdered(list, iterator, null, callback);
|
||||
}
|
||||
-75
@@ -1,75 +0,0 @@
|
||||
var iterate = require('./lib/iterate.js')
|
||||
, initState = require('./lib/state.js')
|
||||
, terminator = require('./lib/terminator.js')
|
||||
;
|
||||
|
||||
// Public API
|
||||
module.exports = serialOrdered;
|
||||
// sorting helpers
|
||||
module.exports.ascending = ascending;
|
||||
module.exports.descending = descending;
|
||||
|
||||
/**
|
||||
* Runs iterator over provided sorted array elements in series
|
||||
*
|
||||
* @param {array|object} list - array or object (named list) to iterate over
|
||||
* @param {function} iterator - iterator to run
|
||||
* @param {function} sortMethod - custom sort function
|
||||
* @param {function} callback - invoked when all elements processed
|
||||
* @returns {function} - jobs terminator
|
||||
*/
|
||||
function serialOrdered(list, iterator, sortMethod, callback)
|
||||
{
|
||||
var state = initState(list, sortMethod);
|
||||
|
||||
iterate(list, iterator, state, function iteratorHandler(error, result)
|
||||
{
|
||||
if (error)
|
||||
{
|
||||
callback(error, result);
|
||||
return;
|
||||
}
|
||||
|
||||
state.index++;
|
||||
|
||||
// are we there yet?
|
||||
if (state.index < (state['keyedList'] || list).length)
|
||||
{
|
||||
iterate(list, iterator, state, iteratorHandler);
|
||||
return;
|
||||
}
|
||||
|
||||
// done here
|
||||
callback(null, state.results);
|
||||
});
|
||||
|
||||
return terminator.bind(state, callback);
|
||||
}
|
||||
|
||||
/*
|
||||
* -- Sort methods
|
||||
*/
|
||||
|
||||
/**
|
||||
* sort helper to sort array elements in ascending order
|
||||
*
|
||||
* @param {mixed} a - an item to compare
|
||||
* @param {mixed} b - an item to compare
|
||||
* @returns {number} - comparison result
|
||||
*/
|
||||
function ascending(a, b)
|
||||
{
|
||||
return a < b ? -1 : a > b ? 1 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* sort helper to sort array elements in descending order
|
||||
*
|
||||
* @param {mixed} a - an item to compare
|
||||
* @param {mixed} b - an item to compare
|
||||
* @returns {number} - comparison result
|
||||
*/
|
||||
function descending(a, b)
|
||||
{
|
||||
return -1 * ascending(a, b);
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
var inherits = require('util').inherits
|
||||
, Readable = require('stream').Readable
|
||||
, ReadableAsyncKit = require('./lib/readable_asynckit.js')
|
||||
, ReadableParallel = require('./lib/readable_parallel.js')
|
||||
, ReadableSerial = require('./lib/readable_serial.js')
|
||||
, ReadableSerialOrdered = require('./lib/readable_serial_ordered.js')
|
||||
;
|
||||
|
||||
// API
|
||||
module.exports =
|
||||
{
|
||||
parallel : ReadableParallel,
|
||||
serial : ReadableSerial,
|
||||
serialOrdered : ReadableSerialOrdered,
|
||||
};
|
||||
|
||||
inherits(ReadableAsyncKit, Readable);
|
||||
|
||||
inherits(ReadableParallel, ReadableAsyncKit);
|
||||
inherits(ReadableSerial, ReadableAsyncKit);
|
||||
inherits(ReadableSerialOrdered, ReadableAsyncKit);
|
||||
-230
@@ -1,230 +0,0 @@
|
||||
At your option you may choose either of the following licenses:
|
||||
|
||||
* The MIT License (MIT)
|
||||
* The Apache License 2.0 (Apache-2.0)
|
||||
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 AJ ONeal
|
||||
|
||||
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 2015 AJ ONeal
|
||||
|
||||
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.
|
||||
-319
@@ -1,319 +0,0 @@
|
||||
Creative Commons Legal Code
|
||||
|
||||
Attribution 3.0 Unported
|
||||
|
||||
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
|
||||
LEGAL SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN
|
||||
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
|
||||
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
|
||||
REGARDING THE INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR
|
||||
DAMAGES RESULTING FROM ITS USE.
|
||||
|
||||
License
|
||||
|
||||
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE
|
||||
COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY
|
||||
COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS
|
||||
AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
|
||||
|
||||
BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE
|
||||
TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY
|
||||
BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS
|
||||
CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND
|
||||
CONDITIONS.
|
||||
|
||||
1. Definitions
|
||||
|
||||
a. "Adaptation" means a work based upon the Work, or upon the Work and
|
||||
other pre-existing works, such as a translation, adaptation,
|
||||
derivative work, arrangement of music or other alterations of a
|
||||
literary or artistic work, or phonogram or performance and includes
|
||||
cinematographic adaptations or any other form in which the Work may be
|
||||
recast, transformed, or adapted including in any form recognizably
|
||||
derived from the original, except that a work that constitutes a
|
||||
Collection will not be considered an Adaptation for the purpose of
|
||||
this License. For the avoidance of doubt, where the Work is a musical
|
||||
work, performance or phonogram, the synchronization of the Work in
|
||||
timed-relation with a moving image ("synching") will be considered an
|
||||
Adaptation for the purpose of this License.
|
||||
b. "Collection" means a collection of literary or artistic works, such as
|
||||
encyclopedias and anthologies, or performances, phonograms or
|
||||
broadcasts, or other works or subject matter other than works listed
|
||||
in Section 1(f) below, which, by reason of the selection and
|
||||
arrangement of their contents, constitute intellectual creations, in
|
||||
which the Work is included in its entirety in unmodified form along
|
||||
with one or more other contributions, each constituting separate and
|
||||
independent works in themselves, which together are assembled into a
|
||||
collective whole. A work that constitutes a Collection will not be
|
||||
considered an Adaptation (as defined above) for the purposes of this
|
||||
License.
|
||||
c. "Distribute" means to make available to the public the original and
|
||||
copies of the Work or Adaptation, as appropriate, through sale or
|
||||
other transfer of ownership.
|
||||
d. "Licensor" means the individual, individuals, entity or entities that
|
||||
offer(s) the Work under the terms of this License.
|
||||
e. "Original Author" means, in the case of a literary or artistic work,
|
||||
the individual, individuals, entity or entities who created the Work
|
||||
or if no individual or entity can be identified, the publisher; and in
|
||||
addition (i) in the case of a performance the actors, singers,
|
||||
musicians, dancers, and other persons who act, sing, deliver, declaim,
|
||||
play in, interpret or otherwise perform literary or artistic works or
|
||||
expressions of folklore; (ii) in the case of a phonogram the producer
|
||||
being the person or legal entity who first fixes the sounds of a
|
||||
performance or other sounds; and, (iii) in the case of broadcasts, the
|
||||
organization that transmits the broadcast.
|
||||
f. "Work" means the literary and/or artistic work offered under the terms
|
||||
of this License including without limitation any production in the
|
||||
literary, scientific and artistic domain, whatever may be the mode or
|
||||
form of its expression including digital form, such as a book,
|
||||
pamphlet and other writing; a lecture, address, sermon or other work
|
||||
of the same nature; a dramatic or dramatico-musical work; a
|
||||
choreographic work or entertainment in dumb show; a musical
|
||||
composition with or without words; a cinematographic work to which are
|
||||
assimilated works expressed by a process analogous to cinematography;
|
||||
a work of drawing, painting, architecture, sculpture, engraving or
|
||||
lithography; a photographic work to which are assimilated works
|
||||
expressed by a process analogous to photography; a work of applied
|
||||
art; an illustration, map, plan, sketch or three-dimensional work
|
||||
relative to geography, topography, architecture or science; a
|
||||
performance; a broadcast; a phonogram; a compilation of data to the
|
||||
extent it is protected as a copyrightable work; or a work performed by
|
||||
a variety or circus performer to the extent it is not otherwise
|
||||
considered a literary or artistic work.
|
||||
g. "You" means an individual or entity exercising rights under this
|
||||
License who has not previously violated the terms of this License with
|
||||
respect to the Work, or who has received express permission from the
|
||||
Licensor to exercise rights under this License despite a previous
|
||||
violation.
|
||||
h. "Publicly Perform" means to perform public recitations of the Work and
|
||||
to communicate to the public those public recitations, by any means or
|
||||
process, including by wire or wireless means or public digital
|
||||
performances; to make available to the public Works in such a way that
|
||||
members of the public may access these Works from a place and at a
|
||||
place individually chosen by them; to perform the Work to the public
|
||||
by any means or process and the communication to the public of the
|
||||
performances of the Work, including by public digital performance; to
|
||||
broadcast and rebroadcast the Work by any means including signs,
|
||||
sounds or images.
|
||||
i. "Reproduce" means to make copies of the Work by any means including
|
||||
without limitation by sound or visual recordings and the right of
|
||||
fixation and reproducing fixations of the Work, including storage of a
|
||||
protected performance or phonogram in digital form or other electronic
|
||||
medium.
|
||||
|
||||
2. Fair Dealing Rights. Nothing in this License is intended to reduce,
|
||||
limit, or restrict any uses free from copyright or rights arising from
|
||||
limitations or exceptions that are provided for in connection with the
|
||||
copyright protection under copyright law or other applicable laws.
|
||||
|
||||
3. License Grant. Subject to the terms and conditions of this License,
|
||||
Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
|
||||
perpetual (for the duration of the applicable copyright) license to
|
||||
exercise the rights in the Work as stated below:
|
||||
|
||||
a. to Reproduce the Work, to incorporate the Work into one or more
|
||||
Collections, and to Reproduce the Work as incorporated in the
|
||||
Collections;
|
||||
b. to create and Reproduce Adaptations provided that any such Adaptation,
|
||||
including any translation in any medium, takes reasonable steps to
|
||||
clearly label, demarcate or otherwise identify that changes were made
|
||||
to the original Work. For example, a translation could be marked "The
|
||||
original work was translated from English to Spanish," or a
|
||||
modification could indicate "The original work has been modified.";
|
||||
c. to Distribute and Publicly Perform the Work including as incorporated
|
||||
in Collections; and,
|
||||
d. to Distribute and Publicly Perform Adaptations.
|
||||
e. For the avoidance of doubt:
|
||||
|
||||
i. Non-waivable Compulsory License Schemes. In those jurisdictions in
|
||||
which the right to collect royalties through any statutory or
|
||||
compulsory licensing scheme cannot be waived, the Licensor
|
||||
reserves the exclusive right to collect such royalties for any
|
||||
exercise by You of the rights granted under this License;
|
||||
ii. Waivable Compulsory License Schemes. In those jurisdictions in
|
||||
which the right to collect royalties through any statutory or
|
||||
compulsory licensing scheme can be waived, the Licensor waives the
|
||||
exclusive right to collect such royalties for any exercise by You
|
||||
of the rights granted under this License; and,
|
||||
iii. Voluntary License Schemes. The Licensor waives the right to
|
||||
collect royalties, whether individually or, in the event that the
|
||||
Licensor is a member of a collecting society that administers
|
||||
voluntary licensing schemes, via that society, from any exercise
|
||||
by You of the rights granted under this License.
|
||||
|
||||
The above rights may be exercised in all media and formats whether now
|
||||
known or hereafter devised. The above rights include the right to make
|
||||
such modifications as are technically necessary to exercise the rights in
|
||||
other media and formats. Subject to Section 8(f), all rights not expressly
|
||||
granted by Licensor are hereby reserved.
|
||||
|
||||
4. Restrictions. The license granted in Section 3 above is expressly made
|
||||
subject to and limited by the following restrictions:
|
||||
|
||||
a. You may Distribute or Publicly Perform the Work only under the terms
|
||||
of this License. You must include a copy of, or the Uniform Resource
|
||||
Identifier (URI) for, this License with every copy of the Work You
|
||||
Distribute or Publicly Perform. You may not offer or impose any terms
|
||||
on the Work that restrict the terms of this License or the ability of
|
||||
the recipient of the Work to exercise the rights granted to that
|
||||
recipient under the terms of the License. You may not sublicense the
|
||||
Work. You must keep intact all notices that refer to this License and
|
||||
to the disclaimer of warranties with every copy of the Work You
|
||||
Distribute or Publicly Perform. When You Distribute or Publicly
|
||||
Perform the Work, You may not impose any effective technological
|
||||
measures on the Work that restrict the ability of a recipient of the
|
||||
Work from You to exercise the rights granted to that recipient under
|
||||
the terms of the License. This Section 4(a) applies to the Work as
|
||||
incorporated in a Collection, but this does not require the Collection
|
||||
apart from the Work itself to be made subject to the terms of this
|
||||
License. If You create a Collection, upon notice from any Licensor You
|
||||
must, to the extent practicable, remove from the Collection any credit
|
||||
as required by Section 4(b), as requested. If You create an
|
||||
Adaptation, upon notice from any Licensor You must, to the extent
|
||||
practicable, remove from the Adaptation any credit as required by
|
||||
Section 4(b), as requested.
|
||||
b. If You Distribute, or Publicly Perform the Work or any Adaptations or
|
||||
Collections, You must, unless a request has been made pursuant to
|
||||
Section 4(a), keep intact all copyright notices for the Work and
|
||||
provide, reasonable to the medium or means You are utilizing: (i) the
|
||||
name of the Original Author (or pseudonym, if applicable) if supplied,
|
||||
and/or if the Original Author and/or Licensor designate another party
|
||||
or parties (e.g., a sponsor institute, publishing entity, journal) for
|
||||
attribution ("Attribution Parties") in Licensor's copyright notice,
|
||||
terms of service or by other reasonable means, the name of such party
|
||||
or parties; (ii) the title of the Work if supplied; (iii) to the
|
||||
extent reasonably practicable, the URI, if any, that Licensor
|
||||
specifies to be associated with the Work, unless such URI does not
|
||||
refer to the copyright notice or licensing information for the Work;
|
||||
and (iv) , consistent with Section 3(b), in the case of an Adaptation,
|
||||
a credit identifying the use of the Work in the Adaptation (e.g.,
|
||||
"French translation of the Work by Original Author," or "Screenplay
|
||||
based on original Work by Original Author"). The credit required by
|
||||
this Section 4 (b) may be implemented in any reasonable manner;
|
||||
provided, however, that in the case of a Adaptation or Collection, at
|
||||
a minimum such credit will appear, if a credit for all contributing
|
||||
authors of the Adaptation or Collection appears, then as part of these
|
||||
credits and in a manner at least as prominent as the credits for the
|
||||
other contributing authors. For the avoidance of doubt, You may only
|
||||
use the credit required by this Section for the purpose of attribution
|
||||
in the manner set out above and, by exercising Your rights under this
|
||||
License, You may not implicitly or explicitly assert or imply any
|
||||
connection with, sponsorship or endorsement by the Original Author,
|
||||
Licensor and/or Attribution Parties, as appropriate, of You or Your
|
||||
use of the Work, without the separate, express prior written
|
||||
permission of the Original Author, Licensor and/or Attribution
|
||||
Parties.
|
||||
c. Except as otherwise agreed in writing by the Licensor or as may be
|
||||
otherwise permitted by applicable law, if You Reproduce, Distribute or
|
||||
Publicly Perform the Work either by itself or as part of any
|
||||
Adaptations or Collections, You must not distort, mutilate, modify or
|
||||
take other derogatory action in relation to the Work which would be
|
||||
prejudicial to the Original Author's honor or reputation. Licensor
|
||||
agrees that in those jurisdictions (e.g. Japan), in which any exercise
|
||||
of the right granted in Section 3(b) of this License (the right to
|
||||
make Adaptations) would be deemed to be a distortion, mutilation,
|
||||
modification or other derogatory action prejudicial to the Original
|
||||
Author's honor and reputation, the Licensor will waive or not assert,
|
||||
as appropriate, this Section, to the fullest extent permitted by the
|
||||
applicable national law, to enable You to reasonably exercise Your
|
||||
right under Section 3(b) of this License (right to make Adaptations)
|
||||
but not otherwise.
|
||||
|
||||
5. Representations, Warranties and Disclaimer
|
||||
|
||||
UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR
|
||||
OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY
|
||||
KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE,
|
||||
INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF
|
||||
LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS,
|
||||
WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION
|
||||
OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
|
||||
|
||||
6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE
|
||||
LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR
|
||||
ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES
|
||||
ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS
|
||||
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
7. Termination
|
||||
|
||||
a. This License and the rights granted hereunder will terminate
|
||||
automatically upon any breach by You of the terms of this License.
|
||||
Individuals or entities who have received Adaptations or Collections
|
||||
from You under this License, however, will not have their licenses
|
||||
terminated provided such individuals or entities remain in full
|
||||
compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will
|
||||
survive any termination of this License.
|
||||
b. Subject to the above terms and conditions, the license granted here is
|
||||
perpetual (for the duration of the applicable copyright in the Work).
|
||||
Notwithstanding the above, Licensor reserves the right to release the
|
||||
Work under different license terms or to stop distributing the Work at
|
||||
any time; provided, however that any such election will not serve to
|
||||
withdraw this License (or any other license that has been, or is
|
||||
required to be, granted under the terms of this License), and this
|
||||
License will continue in full force and effect unless terminated as
|
||||
stated above.
|
||||
|
||||
8. Miscellaneous
|
||||
|
||||
a. Each time You Distribute or Publicly Perform the Work or a Collection,
|
||||
the Licensor offers to the recipient a license to the Work on the same
|
||||
terms and conditions as the license granted to You under this License.
|
||||
b. Each time You Distribute or Publicly Perform an Adaptation, Licensor
|
||||
offers to the recipient a license to the original Work on the same
|
||||
terms and conditions as the license granted to You under this License.
|
||||
c. If any provision of this License is invalid or unenforceable under
|
||||
applicable law, it shall not affect the validity or enforceability of
|
||||
the remainder of the terms of this License, and without further action
|
||||
by the parties to this agreement, such provision shall be reformed to
|
||||
the minimum extent necessary to make such provision valid and
|
||||
enforceable.
|
||||
d. No term or provision of this License shall be deemed waived and no
|
||||
breach consented to unless such waiver or consent shall be in writing
|
||||
and signed by the party to be charged with such waiver or consent.
|
||||
e. This License constitutes the entire agreement between the parties with
|
||||
respect to the Work licensed here. There are no understandings,
|
||||
agreements or representations with respect to the Work not specified
|
||||
here. Licensor shall not be bound by any additional provisions that
|
||||
may appear in any communication from You. This License may not be
|
||||
modified without the mutual written agreement of the Licensor and You.
|
||||
f. The rights granted under, and the subject matter referenced, in this
|
||||
License were drafted utilizing the terminology of the Berne Convention
|
||||
for the Protection of Literary and Artistic Works (as amended on
|
||||
September 28, 1979), the Rome Convention of 1961, the WIPO Copyright
|
||||
Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996
|
||||
and the Universal Copyright Convention (as revised on July 24, 1971).
|
||||
These rights and subject matter take effect in the relevant
|
||||
jurisdiction in which the License terms are sought to be enforced
|
||||
according to the corresponding provisions of the implementation of
|
||||
those treaty provisions in the applicable national law. If the
|
||||
standard suite of rights granted under applicable copyright law
|
||||
includes additional rights not granted under this License, such
|
||||
additional rights are deemed to be included in the License; this
|
||||
License is not intended to restrict the license of any rights under
|
||||
applicable law.
|
||||
|
||||
|
||||
Creative Commons Notice
|
||||
|
||||
Creative Commons is not a party to this License, and makes no warranty
|
||||
whatsoever in connection with the Work. Creative Commons will not be
|
||||
liable to You or any party on any legal theory for any damages
|
||||
whatsoever, including without limitation any general, special,
|
||||
incidental or consequential damages arising in connection to this
|
||||
license. Notwithstanding the foregoing two (2) sentences, if Creative
|
||||
Commons has expressly identified itself as the Licensor hereunder, it
|
||||
shall have all rights and obligations of Licensor.
|
||||
|
||||
Except for the limited purpose of indicating to the public that the
|
||||
Work is licensed under the CCPL, Creative Commons does not authorize
|
||||
the use by either party of the trademark "Creative Commons" or any
|
||||
related trademark or logo of Creative Commons without the prior
|
||||
written consent of Creative Commons. Any permitted use will be in
|
||||
compliance with Creative Commons' then-current trademark usage
|
||||
guidelines, as may be published on its website or otherwise made
|
||||
available upon request from time to time. For the avoidance of doubt,
|
||||
this trademark restriction does not form part of this License.
|
||||
|
||||
Creative Commons may be contacted at http://creativecommons.org/.
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
atob
|
||||
===
|
||||
|
||||
| **atob**
|
||||
| [btoa](https://git.coolaj86.com/coolaj86/btoa.js)
|
||||
| [unibabel.js](https://git.coolaj86.com/coolaj86/unibabel.js)
|
||||
| Sponsored by [ppl](https://ppl.family)
|
||||
|
||||
Uses `Buffer` to emulate the exact functionality of the browser's atob.
|
||||
|
||||
Note: Unicode may be handled incorrectly (like the browser).
|
||||
|
||||
It turns base64-encoded <strong>a</strong>scii data back **to** <strong>b</strong>inary.
|
||||
|
||||
```javascript
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
var atob = require('atob');
|
||||
var b64 = "SGVsbG8sIFdvcmxkIQ==";
|
||||
var bin = atob(b64);
|
||||
|
||||
console.log(bin); // "Hello, World!"
|
||||
}());
|
||||
```
|
||||
|
||||
### Need Unicode and Binary Support in the Browser?
|
||||
|
||||
Check out [unibabel.js](https://git.coolaj86.com/coolaj86/unibabel.js)
|
||||
|
||||
Changelog
|
||||
=======
|
||||
|
||||
* v2.1.0 address a few issues and PRs, update URLs
|
||||
* v2.0.0 provide browser version for ios web workers
|
||||
* v1.2.0 provide (empty) browser version
|
||||
* v1.1.3 add MIT license
|
||||
* v1.1.2 node only
|
||||
|
||||
LICENSE
|
||||
=======
|
||||
|
||||
Code copyright 2012-2018 AJ ONeal
|
||||
|
||||
Dual-licensed MIT and Apache-2.0
|
||||
|
||||
Docs copyright 2012-2018 AJ ONeal
|
||||
|
||||
Docs released under [Creative Commons](https://git.coolaj86.com/coolaj86/atob.js/blob/master/LICENSE.DOCS).
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
|
||||
var atob = require('../node-atob');
|
||||
var str = process.argv[2];
|
||||
console.log(atob(str));
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"name": "atob",
|
||||
"description": "atob for isomorphic environments",
|
||||
"main": "browser-atob.js",
|
||||
"authors": [
|
||||
"AJ ONeal <coolaj86@gmail.com> (https://coolaj86.com)"
|
||||
],
|
||||
"license": "(MIT OR Apache-2.0)",
|
||||
"keywords": [
|
||||
"atob",
|
||||
"browser"
|
||||
],
|
||||
"homepage": "https://github.com/node-browser-compat/atob",
|
||||
"moduleType": [
|
||||
"globals"
|
||||
],
|
||||
"ignore": [
|
||||
"**/.*",
|
||||
"node_modules",
|
||||
"bower_components",
|
||||
"test",
|
||||
"tests"
|
||||
]
|
||||
}
|
||||
-44
@@ -1,44 +0,0 @@
|
||||
(function (w) {
|
||||
"use strict";
|
||||
|
||||
function findBest(atobNative) {
|
||||
// normal window
|
||||
if ('function' === typeof atobNative) { return atobNative; }
|
||||
|
||||
|
||||
// browserify (web worker)
|
||||
if ('function' === typeof Buffer) {
|
||||
return function atobBrowserify(a) {
|
||||
//!! Deliberately using an API that's deprecated in node.js because
|
||||
//!! this file is for browsers and we expect them to cope with it.
|
||||
//!! Discussion: github.com/node-browser-compat/atob/pull/9
|
||||
return new Buffer(a, 'base64').toString('binary');
|
||||
};
|
||||
}
|
||||
|
||||
// ios web worker with base64js
|
||||
if ('object' === typeof w.base64js) {
|
||||
// bufferToBinaryString
|
||||
// https://git.coolaj86.com/coolaj86/unibabel.js/blob/master/index.js#L50
|
||||
return function atobWebWorker_iOS(a) {
|
||||
var buf = w.base64js.b64ToByteArray(a);
|
||||
return Array.prototype.map.call(buf, function (ch) {
|
||||
return String.fromCharCode(ch);
|
||||
}).join('');
|
||||
};
|
||||
}
|
||||
|
||||
return function () {
|
||||
// ios web worker without base64js
|
||||
throw new Error("You're probably in an old browser or an iOS webworker." +
|
||||
" It might help to include beatgammit's base64-js.");
|
||||
};
|
||||
}
|
||||
|
||||
var atobBest = findBest(w.atob);
|
||||
w.atob = atobBest;
|
||||
|
||||
if ((typeof module === 'object') && module && module.exports) {
|
||||
module.exports = atobBest;
|
||||
}
|
||||
}(window));
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
function atob(str) {
|
||||
return Buffer.from(str, 'base64').toString('binary');
|
||||
}
|
||||
|
||||
module.exports = atob.atob = atob;
|
||||
-53
@@ -1,53 +0,0 @@
|
||||
{
|
||||
"_from": "atob@^2.1.2",
|
||||
"_id": "atob@2.1.2",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==",
|
||||
"_location": "/atob",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "atob@^2.1.2",
|
||||
"name": "atob",
|
||||
"escapedName": "atob",
|
||||
"rawSpec": "^2.1.2",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^2.1.2"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/source-map-resolve"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz",
|
||||
"_shasum": "6d9517eb9e030d2436666651e86bd9f6f13533c9",
|
||||
"_spec": "atob@^2.1.2",
|
||||
"_where": "O:\\zero\\zero.Web\\node_modules\\source-map-resolve",
|
||||
"author": {
|
||||
"name": "AJ ONeal",
|
||||
"email": "coolaj86@gmail.com",
|
||||
"url": "https://coolaj86.com"
|
||||
},
|
||||
"bin": {
|
||||
"atob": "bin/atob.js"
|
||||
},
|
||||
"browser": "browser-atob.js",
|
||||
"bundleDependencies": false,
|
||||
"deprecated": false,
|
||||
"description": "atob for Node.JS and Linux / Mac / Windows CLI (it's a one-liner)",
|
||||
"engines": {
|
||||
"node": ">= 4.5.0"
|
||||
},
|
||||
"homepage": "https://git.coolaj86.com/coolaj86/atob.js.git",
|
||||
"keywords": [
|
||||
"atob",
|
||||
"browser"
|
||||
],
|
||||
"license": "(MIT OR Apache-2.0)",
|
||||
"main": "node-atob.js",
|
||||
"name": "atob",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://git.coolaj86.com/coolaj86/atob.js.git"
|
||||
},
|
||||
"version": "2.1.2"
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
var atob = require('.');
|
||||
var encoded = "SGVsbG8sIFdvcmxkIQ=="
|
||||
var unencoded = "Hello, World!";
|
||||
/*
|
||||
, encoded = "SGVsbG8sIBZM"
|
||||
, unencoded = "Hello, 世界"
|
||||
*/
|
||||
|
||||
if (unencoded !== atob(encoded)) {
|
||||
console.log('[FAIL]', unencoded, atob(encoded));
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[PASS] all tests pass');
|
||||
}());
|
||||
-55
@@ -1,55 +0,0 @@
|
||||
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
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
aws-sign
|
||||
========
|
||||
|
||||
AWS signing. Originally pulled from LearnBoost/knox, maintained as vendor in request, now a standalone module.
|
||||
-212
@@ -1,212 +0,0 @@
|
||||
|
||||
/*!
|
||||
* Copyright 2010 LearnBoost <dev@learnboost.com>
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var crypto = require('crypto')
|
||||
, parse = require('url').parse
|
||||
;
|
||||
|
||||
/**
|
||||
* Valid keys.
|
||||
*/
|
||||
|
||||
var keys =
|
||||
[ 'acl'
|
||||
, 'location'
|
||||
, 'logging'
|
||||
, 'notification'
|
||||
, 'partNumber'
|
||||
, 'policy'
|
||||
, 'requestPayment'
|
||||
, 'torrent'
|
||||
, 'uploadId'
|
||||
, 'uploads'
|
||||
, 'versionId'
|
||||
, 'versioning'
|
||||
, 'versions'
|
||||
, 'website'
|
||||
]
|
||||
|
||||
/**
|
||||
* Return an "Authorization" header value with the given `options`
|
||||
* in the form of "AWS <key>:<signature>"
|
||||
*
|
||||
* @param {Object} options
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function authorization (options) {
|
||||
return 'AWS ' + options.key + ':' + sign(options)
|
||||
}
|
||||
|
||||
module.exports = authorization
|
||||
module.exports.authorization = authorization
|
||||
|
||||
/**
|
||||
* Simple HMAC-SHA1 Wrapper
|
||||
*
|
||||
* @param {Object} options
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function hmacSha1 (options) {
|
||||
return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64')
|
||||
}
|
||||
|
||||
module.exports.hmacSha1 = hmacSha1
|
||||
|
||||
/**
|
||||
* Create a base64 sha1 HMAC for `options`.
|
||||
*
|
||||
* @param {Object} options
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function sign (options) {
|
||||
options.message = stringToSign(options)
|
||||
return hmacSha1(options)
|
||||
}
|
||||
module.exports.sign = sign
|
||||
|
||||
/**
|
||||
* Create a base64 sha1 HMAC for `options`.
|
||||
*
|
||||
* Specifically to be used with S3 presigned URLs
|
||||
*
|
||||
* @param {Object} options
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function signQuery (options) {
|
||||
options.message = queryStringToSign(options)
|
||||
return hmacSha1(options)
|
||||
}
|
||||
module.exports.signQuery= signQuery
|
||||
|
||||
/**
|
||||
* Return a string for sign() with the given `options`.
|
||||
*
|
||||
* Spec:
|
||||
*
|
||||
* <verb>\n
|
||||
* <md5>\n
|
||||
* <content-type>\n
|
||||
* <date>\n
|
||||
* [headers\n]
|
||||
* <resource>
|
||||
*
|
||||
* @param {Object} options
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function stringToSign (options) {
|
||||
var headers = options.amazonHeaders || ''
|
||||
if (headers) headers += '\n'
|
||||
var r =
|
||||
[ options.verb
|
||||
, options.md5
|
||||
, options.contentType
|
||||
, options.date ? options.date.toUTCString() : ''
|
||||
, headers + options.resource
|
||||
]
|
||||
return r.join('\n')
|
||||
}
|
||||
module.exports.stringToSign = stringToSign
|
||||
|
||||
/**
|
||||
* Return a string for sign() with the given `options`, but is meant exclusively
|
||||
* for S3 presigned URLs
|
||||
*
|
||||
* Spec:
|
||||
*
|
||||
* <date>\n
|
||||
* <resource>
|
||||
*
|
||||
* @param {Object} options
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function queryStringToSign (options){
|
||||
return 'GET\n\n\n' + options.date + '\n' + options.resource
|
||||
}
|
||||
module.exports.queryStringToSign = queryStringToSign
|
||||
|
||||
/**
|
||||
* Perform the following:
|
||||
*
|
||||
* - ignore non-amazon headers
|
||||
* - lowercase fields
|
||||
* - sort lexicographically
|
||||
* - trim whitespace between ":"
|
||||
* - join with newline
|
||||
*
|
||||
* @param {Object} headers
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function canonicalizeHeaders (headers) {
|
||||
var buf = []
|
||||
, fields = Object.keys(headers)
|
||||
;
|
||||
for (var i = 0, len = fields.length; i < len; ++i) {
|
||||
var field = fields[i]
|
||||
, val = headers[field]
|
||||
, field = field.toLowerCase()
|
||||
;
|
||||
if (0 !== field.indexOf('x-amz')) continue
|
||||
buf.push(field + ':' + val)
|
||||
}
|
||||
return buf.sort().join('\n')
|
||||
}
|
||||
module.exports.canonicalizeHeaders = canonicalizeHeaders
|
||||
|
||||
/**
|
||||
* Perform the following:
|
||||
*
|
||||
* - ignore non sub-resources
|
||||
* - sort lexicographically
|
||||
*
|
||||
* @param {String} resource
|
||||
* @return {String}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function canonicalizeResource (resource) {
|
||||
var url = parse(resource, true)
|
||||
, path = url.pathname
|
||||
, buf = []
|
||||
;
|
||||
|
||||
Object.keys(url.query).forEach(function(key){
|
||||
if (!~keys.indexOf(key)) return
|
||||
var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key])
|
||||
buf.push(key + val)
|
||||
})
|
||||
|
||||
return path + (buf.length ? '?' + buf.sort().join('&') : '')
|
||||
}
|
||||
module.exports.canonicalizeResource = canonicalizeResource
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
{
|
||||
"_from": "aws-sign2@~0.7.0",
|
||||
"_id": "aws-sign2@0.7.0",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=",
|
||||
"_location": "/aws-sign2",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "aws-sign2@~0.7.0",
|
||||
"name": "aws-sign2",
|
||||
"escapedName": "aws-sign2",
|
||||
"rawSpec": "~0.7.0",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "~0.7.0"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/request"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz",
|
||||
"_shasum": "b46e890934a9591f2d2f6f86d7e6a9f1b3fe76a8",
|
||||
"_spec": "aws-sign2@~0.7.0",
|
||||
"_where": "O:\\zero\\zero.Web\\node_modules\\request",
|
||||
"author": {
|
||||
"name": "Mikeal Rogers",
|
||||
"email": "mikeal.rogers@gmail.com",
|
||||
"url": "http://www.futurealoof.com"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/mikeal/aws-sign/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {},
|
||||
"deprecated": false,
|
||||
"description": "AWS signing. Originally pulled from LearnBoost/knox, maintained as vendor in request, now a standalone module.",
|
||||
"devDependencies": {},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
},
|
||||
"homepage": "https://github.com/mikeal/aws-sign#readme",
|
||||
"license": "Apache-2.0",
|
||||
"main": "index.js",
|
||||
"name": "aws-sign2",
|
||||
"optionalDependencies": {},
|
||||
"repository": {
|
||||
"url": "git+https://github.com/mikeal/aws-sign.git"
|
||||
},
|
||||
"version": "0.7.0"
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- "0.10"
|
||||
- "0.12"
|
||||
- "4"
|
||||
- "6"
|
||||
- "8"
|
||||
- "10"
|
||||
- "12"
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
Copyright 2013 Michael Hart (michael.hart.au@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.
|
||||
-523
@@ -1,523 +0,0 @@
|
||||
aws4
|
||||
----
|
||||
|
||||
[](http://travis-ci.org/mhart/aws4)
|
||||
|
||||
A small utility to sign vanilla Node.js http(s) request options using Amazon's
|
||||
[AWS Signature Version 4](http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html).
|
||||
|
||||
If you want to sign and send AWS requests in a modern browser, or an environment like [Cloudflare Workers](https://developers.cloudflare.com/workers/), then check out [aws4fetch](https://github.com/mhart/aws4fetch) – otherwise you can also bundle this library for use [in the browser](./browser).
|
||||
|
||||
This signature is supported by nearly all Amazon services, including
|
||||
[S3](http://docs.aws.amazon.com/AmazonS3/latest/API/),
|
||||
[EC2](http://docs.aws.amazon.com/AWSEC2/latest/APIReference/),
|
||||
[DynamoDB](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/API.html),
|
||||
[Kinesis](http://docs.aws.amazon.com/kinesis/latest/APIReference/),
|
||||
[Lambda](http://docs.aws.amazon.com/lambda/latest/dg/API_Reference.html),
|
||||
[SQS](http://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/),
|
||||
[SNS](http://docs.aws.amazon.com/sns/latest/api/),
|
||||
[IAM](http://docs.aws.amazon.com/IAM/latest/APIReference/),
|
||||
[STS](http://docs.aws.amazon.com/STS/latest/APIReference/),
|
||||
[RDS](http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/),
|
||||
[CloudWatch](http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/),
|
||||
[CloudWatch Logs](http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/),
|
||||
[CodeDeploy](http://docs.aws.amazon.com/codedeploy/latest/APIReference/),
|
||||
[CloudFront](http://docs.aws.amazon.com/AmazonCloudFront/latest/APIReference/),
|
||||
[CloudTrail](http://docs.aws.amazon.com/awscloudtrail/latest/APIReference/),
|
||||
[ElastiCache](http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/),
|
||||
[EMR](http://docs.aws.amazon.com/ElasticMapReduce/latest/API/),
|
||||
[Glacier](http://docs.aws.amazon.com/amazonglacier/latest/dev/amazon-glacier-api.html),
|
||||
[CloudSearch](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/APIReq.html),
|
||||
[Elastic Load Balancing](http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/),
|
||||
[Elastic Transcoder](http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/api-reference.html),
|
||||
[CloudFormation](http://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/),
|
||||
[Elastic Beanstalk](http://docs.aws.amazon.com/elasticbeanstalk/latest/api/),
|
||||
[Storage Gateway](http://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html),
|
||||
[Data Pipeline](http://docs.aws.amazon.com/datapipeline/latest/APIReference/),
|
||||
[Direct Connect](http://docs.aws.amazon.com/directconnect/latest/APIReference/),
|
||||
[Redshift](http://docs.aws.amazon.com/redshift/latest/APIReference/),
|
||||
[OpsWorks](http://docs.aws.amazon.com/opsworks/latest/APIReference/),
|
||||
[SES](http://docs.aws.amazon.com/ses/latest/APIReference/),
|
||||
[SWF](http://docs.aws.amazon.com/amazonswf/latest/apireference/),
|
||||
[AutoScaling](http://docs.aws.amazon.com/AutoScaling/latest/APIReference/),
|
||||
[Mobile Analytics](http://docs.aws.amazon.com/mobileanalytics/latest/ug/server-reference.html),
|
||||
[Cognito Identity](http://docs.aws.amazon.com/cognitoidentity/latest/APIReference/),
|
||||
[Cognito Sync](http://docs.aws.amazon.com/cognitosync/latest/APIReference/),
|
||||
[Container Service](http://docs.aws.amazon.com/AmazonECS/latest/APIReference/),
|
||||
[AppStream](http://docs.aws.amazon.com/appstream/latest/developerguide/appstream-api-rest.html),
|
||||
[Key Management Service](http://docs.aws.amazon.com/kms/latest/APIReference/),
|
||||
[Config](http://docs.aws.amazon.com/config/latest/APIReference/),
|
||||
[CloudHSM](http://docs.aws.amazon.com/cloudhsm/latest/dg/api-ref.html),
|
||||
[Route53](http://docs.aws.amazon.com/Route53/latest/APIReference/requests-rest.html) and
|
||||
[Route53 Domains](http://docs.aws.amazon.com/Route53/latest/APIReference/requests-rpc.html).
|
||||
|
||||
Indeed, the only AWS services that *don't* support v4 as of 2014-12-30 are
|
||||
[Import/Export](http://docs.aws.amazon.com/AWSImportExport/latest/DG/api-reference.html) and
|
||||
[SimpleDB](http://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API.html)
|
||||
(they only support [AWS Signature Version 2](https://github.com/mhart/aws2)).
|
||||
|
||||
It also provides defaults for a number of core AWS headers and
|
||||
request parameters, making it very easy to query AWS services, or
|
||||
build out a fully-featured AWS library.
|
||||
|
||||
Example
|
||||
-------
|
||||
|
||||
```javascript
|
||||
var http = require('http'),
|
||||
https = require('https'),
|
||||
aws4 = require('aws4')
|
||||
|
||||
// given an options object you could pass to http.request
|
||||
var opts = {host: 'sqs.us-east-1.amazonaws.com', path: '/?Action=ListQueues'}
|
||||
|
||||
// alternatively (as aws4 can infer the host):
|
||||
opts = {service: 'sqs', region: 'us-east-1', path: '/?Action=ListQueues'}
|
||||
|
||||
// alternatively (as us-east-1 is default):
|
||||
opts = {service: 'sqs', path: '/?Action=ListQueues'}
|
||||
|
||||
aws4.sign(opts) // assumes AWS credentials are available in process.env
|
||||
|
||||
console.log(opts)
|
||||
/*
|
||||
{
|
||||
host: 'sqs.us-east-1.amazonaws.com',
|
||||
path: '/?Action=ListQueues',
|
||||
headers: {
|
||||
Host: 'sqs.us-east-1.amazonaws.com',
|
||||
'X-Amz-Date': '20121226T061030Z',
|
||||
Authorization: 'AWS4-HMAC-SHA256 Credential=ABCDEF/20121226/us-east-1/sqs/aws4_request, ...'
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
// we can now use this to query AWS using the standard node.js http API
|
||||
http.request(opts, function(res) { res.pipe(process.stdout) }).end()
|
||||
/*
|
||||
<?xml version="1.0"?>
|
||||
<ListQueuesResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/">
|
||||
...
|
||||
*/
|
||||
```
|
||||
|
||||
More options
|
||||
------------
|
||||
|
||||
```javascript
|
||||
// you can also pass AWS credentials in explicitly (otherwise taken from process.env)
|
||||
aws4.sign(opts, {accessKeyId: '', secretAccessKey: ''})
|
||||
|
||||
// can also add the signature to query strings
|
||||
aws4.sign({service: 's3', path: '/my-bucket?X-Amz-Expires=12345', signQuery: true})
|
||||
|
||||
// create a utility function to pipe to stdout (with https this time)
|
||||
function request(o) { https.request(o, function(res) { res.pipe(process.stdout) }).end(o.body || '') }
|
||||
|
||||
// aws4 can infer the HTTP method if a body is passed in
|
||||
// method will be POST and Content-Type: 'application/x-www-form-urlencoded; charset=utf-8'
|
||||
request(aws4.sign({service: 'iam', body: 'Action=ListGroups&Version=2010-05-08'}))
|
||||
/*
|
||||
<ListGroupsResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/">
|
||||
...
|
||||
*/
|
||||
|
||||
// can specify any custom option or header as per usual
|
||||
request(aws4.sign({
|
||||
service: 'dynamodb',
|
||||
region: 'ap-southeast-2',
|
||||
method: 'POST',
|
||||
path: '/',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-amz-json-1.0',
|
||||
'X-Amz-Target': 'DynamoDB_20120810.ListTables'
|
||||
},
|
||||
body: '{}'
|
||||
}))
|
||||
/*
|
||||
{"TableNames":[]}
|
||||
...
|
||||
*/
|
||||
|
||||
// works with all other services that support Signature Version 4
|
||||
|
||||
request(aws4.sign({service: 's3', path: '/', signQuery: true}))
|
||||
/*
|
||||
<ListAllMyBucketsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'ec2', path: '/?Action=DescribeRegions&Version=2014-06-15'}))
|
||||
/*
|
||||
<DescribeRegionsResponse xmlns="http://ec2.amazonaws.com/doc/2014-06-15/">
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'sns', path: '/?Action=ListTopics&Version=2010-03-31'}))
|
||||
/*
|
||||
<ListTopicsResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/">
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'sts', path: '/?Action=GetSessionToken&Version=2011-06-15'}))
|
||||
/*
|
||||
<GetSessionTokenResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'cloudsearch', path: '/?Action=ListDomainNames&Version=2013-01-01'}))
|
||||
/*
|
||||
<ListDomainNamesResponse xmlns="http://cloudsearch.amazonaws.com/doc/2013-01-01/">
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'ses', path: '/?Action=ListIdentities&Version=2010-12-01'}))
|
||||
/*
|
||||
<ListIdentitiesResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/">
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'autoscaling', path: '/?Action=DescribeAutoScalingInstances&Version=2011-01-01'}))
|
||||
/*
|
||||
<DescribeAutoScalingInstancesResponse xmlns="http://autoscaling.amazonaws.com/doc/2011-01-01/">
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'elasticloadbalancing', path: '/?Action=DescribeLoadBalancers&Version=2012-06-01'}))
|
||||
/*
|
||||
<DescribeLoadBalancersResponse xmlns="http://elasticloadbalancing.amazonaws.com/doc/2012-06-01/">
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'cloudformation', path: '/?Action=ListStacks&Version=2010-05-15'}))
|
||||
/*
|
||||
<ListStacksResponse xmlns="http://cloudformation.amazonaws.com/doc/2010-05-15/">
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'elasticbeanstalk', path: '/?Action=ListAvailableSolutionStacks&Version=2010-12-01'}))
|
||||
/*
|
||||
<ListAvailableSolutionStacksResponse xmlns="http://elasticbeanstalk.amazonaws.com/docs/2010-12-01/">
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'rds', path: '/?Action=DescribeDBInstances&Version=2012-09-17'}))
|
||||
/*
|
||||
<DescribeDBInstancesResponse xmlns="http://rds.amazonaws.com/doc/2012-09-17/">
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'monitoring', path: '/?Action=ListMetrics&Version=2010-08-01'}))
|
||||
/*
|
||||
<ListMetricsResponse xmlns="http://monitoring.amazonaws.com/doc/2010-08-01/">
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'redshift', path: '/?Action=DescribeClusters&Version=2012-12-01'}))
|
||||
/*
|
||||
<DescribeClustersResponse xmlns="http://redshift.amazonaws.com/doc/2012-12-01/">
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'cloudfront', path: '/2014-05-31/distribution'}))
|
||||
/*
|
||||
<DistributionList xmlns="http://cloudfront.amazonaws.com/doc/2014-05-31/">
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'elasticache', path: '/?Action=DescribeCacheClusters&Version=2014-07-15'}))
|
||||
/*
|
||||
<DescribeCacheClustersResponse xmlns="http://elasticache.amazonaws.com/doc/2014-07-15/">
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'elasticmapreduce', path: '/?Action=DescribeJobFlows&Version=2009-03-31'}))
|
||||
/*
|
||||
<DescribeJobFlowsResponse xmlns="http://elasticmapreduce.amazonaws.com/doc/2009-03-31">
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'route53', path: '/2013-04-01/hostedzone'}))
|
||||
/*
|
||||
<ListHostedZonesResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'appstream', path: '/applications'}))
|
||||
/*
|
||||
{"_links":{"curie":[{"href":"http://docs.aws.amazon.com/appstream/latest/...
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'cognito-sync', path: '/identitypools'}))
|
||||
/*
|
||||
{"Count":0,"IdentityPoolUsages":[],"MaxResults":16,"NextToken":null}
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'elastictranscoder', path: '/2012-09-25/pipelines'}))
|
||||
/*
|
||||
{"NextPageToken":null,"Pipelines":[]}
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'lambda', path: '/2014-11-13/functions/'}))
|
||||
/*
|
||||
{"Functions":[],"NextMarker":null}
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'ecs', path: '/?Action=ListClusters&Version=2014-11-13'}))
|
||||
/*
|
||||
<ListClustersResponse xmlns="http://ecs.amazonaws.com/doc/2014-11-13/">
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'glacier', path: '/-/vaults', headers: {'X-Amz-Glacier-Version': '2012-06-01'}}))
|
||||
/*
|
||||
{"Marker":null,"VaultList":[]}
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'storagegateway', body: '{}', headers: {
|
||||
'Content-Type': 'application/x-amz-json-1.1',
|
||||
'X-Amz-Target': 'StorageGateway_20120630.ListGateways'
|
||||
}}))
|
||||
/*
|
||||
{"Gateways":[]}
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'datapipeline', body: '{}', headers: {
|
||||
'Content-Type': 'application/x-amz-json-1.1',
|
||||
'X-Amz-Target': 'DataPipeline.ListPipelines'
|
||||
}}))
|
||||
/*
|
||||
{"hasMoreResults":false,"pipelineIdList":[]}
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'opsworks', body: '{}', headers: {
|
||||
'Content-Type': 'application/x-amz-json-1.1',
|
||||
'X-Amz-Target': 'OpsWorks_20130218.DescribeStacks'
|
||||
}}))
|
||||
/*
|
||||
{"Stacks":[]}
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'route53domains', body: '{}', headers: {
|
||||
'Content-Type': 'application/x-amz-json-1.1',
|
||||
'X-Amz-Target': 'Route53Domains_v20140515.ListDomains'
|
||||
}}))
|
||||
/*
|
||||
{"Domains":[]}
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'kinesis', body: '{}', headers: {
|
||||
'Content-Type': 'application/x-amz-json-1.1',
|
||||
'X-Amz-Target': 'Kinesis_20131202.ListStreams'
|
||||
}}))
|
||||
/*
|
||||
{"HasMoreStreams":false,"StreamNames":[]}
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'cloudtrail', body: '{}', headers: {
|
||||
'Content-Type': 'application/x-amz-json-1.1',
|
||||
'X-Amz-Target': 'CloudTrail_20131101.DescribeTrails'
|
||||
}}))
|
||||
/*
|
||||
{"trailList":[]}
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'logs', body: '{}', headers: {
|
||||
'Content-Type': 'application/x-amz-json-1.1',
|
||||
'X-Amz-Target': 'Logs_20140328.DescribeLogGroups'
|
||||
}}))
|
||||
/*
|
||||
{"logGroups":[]}
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'codedeploy', body: '{}', headers: {
|
||||
'Content-Type': 'application/x-amz-json-1.1',
|
||||
'X-Amz-Target': 'CodeDeploy_20141006.ListApplications'
|
||||
}}))
|
||||
/*
|
||||
{"applications":[]}
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'directconnect', body: '{}', headers: {
|
||||
'Content-Type': 'application/x-amz-json-1.1',
|
||||
'X-Amz-Target': 'OvertureService.DescribeConnections'
|
||||
}}))
|
||||
/*
|
||||
{"connections":[]}
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'kms', body: '{}', headers: {
|
||||
'Content-Type': 'application/x-amz-json-1.1',
|
||||
'X-Amz-Target': 'TrentService.ListKeys'
|
||||
}}))
|
||||
/*
|
||||
{"Keys":[],"Truncated":false}
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'config', body: '{}', headers: {
|
||||
'Content-Type': 'application/x-amz-json-1.1',
|
||||
'X-Amz-Target': 'StarlingDoveService.DescribeDeliveryChannels'
|
||||
}}))
|
||||
/*
|
||||
{"DeliveryChannels":[]}
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({service: 'cloudhsm', body: '{}', headers: {
|
||||
'Content-Type': 'application/x-amz-json-1.1',
|
||||
'X-Amz-Target': 'CloudHsmFrontendService.ListAvailableZones'
|
||||
}}))
|
||||
/*
|
||||
{"AZList":["us-east-1a","us-east-1b","us-east-1c"]}
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({
|
||||
service: 'swf',
|
||||
body: '{"registrationStatus":"REGISTERED"}',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-amz-json-1.0',
|
||||
'X-Amz-Target': 'SimpleWorkflowService.ListDomains'
|
||||
}
|
||||
}))
|
||||
/*
|
||||
{"domainInfos":[]}
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({
|
||||
service: 'cognito-identity',
|
||||
body: '{"MaxResults": 1}',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-amz-json-1.1',
|
||||
'X-Amz-Target': 'AWSCognitoIdentityService.ListIdentityPools'
|
||||
}
|
||||
}))
|
||||
/*
|
||||
{"IdentityPools":[]}
|
||||
...
|
||||
*/
|
||||
|
||||
request(aws4.sign({
|
||||
service: 'mobileanalytics',
|
||||
path: '/2014-06-05/events',
|
||||
body: JSON.stringify({events:[{
|
||||
eventType: 'a',
|
||||
timestamp: new Date().toISOString(),
|
||||
session: {},
|
||||
}]}),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Amz-Client-Context': JSON.stringify({
|
||||
client: {client_id: 'a', app_title: 'a'},
|
||||
custom: {},
|
||||
env: {platform: 'a'},
|
||||
services: {},
|
||||
}),
|
||||
}
|
||||
}))
|
||||
/*
|
||||
(HTTP 202, empty response)
|
||||
*/
|
||||
|
||||
// Generate CodeCommit Git access password
|
||||
var signer = new aws4.RequestSigner({
|
||||
service: 'codecommit',
|
||||
host: 'git-codecommit.us-east-1.amazonaws.com',
|
||||
method: 'GIT',
|
||||
path: '/v1/repos/MyAwesomeRepo',
|
||||
})
|
||||
var password = signer.getDateTime() + 'Z' + signer.signature()
|
||||
```
|
||||
|
||||
API
|
||||
---
|
||||
|
||||
### aws4.sign(requestOptions, [credentials])
|
||||
|
||||
This calculates and populates the `Authorization` header of
|
||||
`requestOptions`, and any other necessary AWS headers and/or request
|
||||
options. Returns `requestOptions` as a convenience for chaining.
|
||||
|
||||
`requestOptions` is an object holding the same options that the node.js
|
||||
[http.request](http://nodejs.org/docs/latest/api/http.html#http_http_request_options_callback)
|
||||
function takes.
|
||||
|
||||
The following properties of `requestOptions` are used in the signing or
|
||||
populated if they don't already exist:
|
||||
|
||||
- `hostname` or `host` (will be determined from `service` and `region` if not given)
|
||||
- `method` (will use `'GET'` if not given or `'POST'` if there is a `body`)
|
||||
- `path` (will use `'/'` if not given)
|
||||
- `body` (will use `''` if not given)
|
||||
- `service` (will be calculated from `hostname` or `host` if not given)
|
||||
- `region` (will be calculated from `hostname` or `host` or use `'us-east-1'` if not given)
|
||||
- `headers['Host']` (will use `hostname` or `host` or be calculated if not given)
|
||||
- `headers['Content-Type']` (will use `'application/x-www-form-urlencoded; charset=utf-8'`
|
||||
if not given and there is a `body`)
|
||||
- `headers['Date']` (used to calculate the signature date if given, otherwise `new Date` is used)
|
||||
|
||||
Your AWS credentials (which can be found in your
|
||||
[AWS console](https://portal.aws.amazon.com/gp/aws/securityCredentials))
|
||||
can be specified in one of two ways:
|
||||
|
||||
- As the second argument, like this:
|
||||
|
||||
```javascript
|
||||
aws4.sign(requestOptions, {
|
||||
secretAccessKey: "<your-secret-access-key>",
|
||||
accessKeyId: "<your-access-key-id>",
|
||||
sessionToken: "<your-session-token>"
|
||||
})
|
||||
```
|
||||
|
||||
- From `process.env`, such as this:
|
||||
|
||||
```
|
||||
export AWS_SECRET_ACCESS_KEY="<your-secret-access-key>"
|
||||
export AWS_ACCESS_KEY_ID="<your-access-key-id>"
|
||||
export AWS_SESSION_TOKEN="<your-session-token>"
|
||||
```
|
||||
|
||||
(will also use `AWS_ACCESS_KEY` and `AWS_SECRET_KEY` if available)
|
||||
|
||||
The `sessionToken` property and `AWS_SESSION_TOKEN` environment variable are optional for signing
|
||||
with [IAM STS temporary credentials](http://docs.aws.amazon.com/STS/latest/UsingSTS/using-temp-creds.html).
|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
With [npm](http://npmjs.org/) do:
|
||||
|
||||
```
|
||||
npm install aws4
|
||||
```
|
||||
|
||||
Can also be used [in the browser](./browser).
|
||||
|
||||
Thanks
|
||||
------
|
||||
|
||||
Thanks to [@jed](https://github.com/jed) for his
|
||||
[dynamo-client](https://github.com/jed/dynamo-client) lib where I first
|
||||
committed and subsequently extracted this code.
|
||||
|
||||
Also thanks to the
|
||||
[official node.js AWS SDK](https://github.com/aws/aws-sdk-js) for giving
|
||||
me a start on implementing the v4 signature.
|
||||
|
||||
-345
@@ -1,345 +0,0 @@
|
||||
var aws4 = exports,
|
||||
url = require('url'),
|
||||
querystring = require('querystring'),
|
||||
crypto = require('crypto'),
|
||||
lru = require('./lru'),
|
||||
credentialsCache = lru(1000)
|
||||
|
||||
// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html
|
||||
|
||||
function hmac(key, string, encoding) {
|
||||
return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding)
|
||||
}
|
||||
|
||||
function hash(string, encoding) {
|
||||
return crypto.createHash('sha256').update(string, 'utf8').digest(encoding)
|
||||
}
|
||||
|
||||
// This function assumes the string has already been percent encoded
|
||||
function encodeRfc3986(urlEncodedString) {
|
||||
return urlEncodedString.replace(/[!'()*]/g, function(c) {
|
||||
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
|
||||
})
|
||||
}
|
||||
|
||||
function encodeRfc3986Full(str) {
|
||||
return encodeRfc3986(encodeURIComponent(str))
|
||||
}
|
||||
|
||||
// request: { path | body, [host], [method], [headers], [service], [region] }
|
||||
// credentials: { accessKeyId, secretAccessKey, [sessionToken] }
|
||||
function RequestSigner(request, credentials) {
|
||||
|
||||
if (typeof request === 'string') request = url.parse(request)
|
||||
|
||||
var headers = request.headers = (request.headers || {}),
|
||||
hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host)
|
||||
|
||||
this.request = request
|
||||
this.credentials = credentials || this.defaultCredentials()
|
||||
|
||||
this.service = request.service || hostParts[0] || ''
|
||||
this.region = request.region || hostParts[1] || 'us-east-1'
|
||||
|
||||
// SES uses a different domain from the service name
|
||||
if (this.service === 'email') this.service = 'ses'
|
||||
|
||||
if (!request.method && request.body)
|
||||
request.method = 'POST'
|
||||
|
||||
if (!headers.Host && !headers.host) {
|
||||
headers.Host = request.hostname || request.host || this.createHost()
|
||||
|
||||
// If a port is specified explicitly, use it as is
|
||||
if (request.port)
|
||||
headers.Host += ':' + request.port
|
||||
}
|
||||
if (!request.hostname && !request.host)
|
||||
request.hostname = headers.Host || headers.host
|
||||
|
||||
this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT'
|
||||
}
|
||||
|
||||
RequestSigner.prototype.matchHost = function(host) {
|
||||
var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)
|
||||
var hostParts = (match || []).slice(1, 3)
|
||||
|
||||
// ES's hostParts are sometimes the other way round, if the value that is expected
|
||||
// to be region equals ‘es’ switch them back
|
||||
// e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com
|
||||
if (hostParts[1] === 'es')
|
||||
hostParts = hostParts.reverse()
|
||||
|
||||
return hostParts
|
||||
}
|
||||
|
||||
// http://docs.aws.amazon.com/general/latest/gr/rande.html
|
||||
RequestSigner.prototype.isSingleRegion = function() {
|
||||
// Special case for S3 and SimpleDB in us-east-1
|
||||
if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true
|
||||
|
||||
return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts']
|
||||
.indexOf(this.service) >= 0
|
||||
}
|
||||
|
||||
RequestSigner.prototype.createHost = function() {
|
||||
var region = this.isSingleRegion() ? '' :
|
||||
(this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region,
|
||||
service = this.service === 'ses' ? 'email' : this.service
|
||||
return service + region + '.amazonaws.com'
|
||||
}
|
||||
|
||||
RequestSigner.prototype.prepareRequest = function() {
|
||||
this.parsePath()
|
||||
|
||||
var request = this.request, headers = request.headers, query
|
||||
|
||||
if (request.signQuery) {
|
||||
|
||||
this.parsedPath.query = query = this.parsedPath.query || {}
|
||||
|
||||
if (this.credentials.sessionToken)
|
||||
query['X-Amz-Security-Token'] = this.credentials.sessionToken
|
||||
|
||||
if (this.service === 's3' && !query['X-Amz-Expires'])
|
||||
query['X-Amz-Expires'] = 86400
|
||||
|
||||
if (query['X-Amz-Date'])
|
||||
this.datetime = query['X-Amz-Date']
|
||||
else
|
||||
query['X-Amz-Date'] = this.getDateTime()
|
||||
|
||||
query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256'
|
||||
query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString()
|
||||
query['X-Amz-SignedHeaders'] = this.signedHeaders()
|
||||
|
||||
} else {
|
||||
|
||||
if (!request.doNotModifyHeaders && !this.isCodeCommitGit) {
|
||||
if (request.body && !headers['Content-Type'] && !headers['content-type'])
|
||||
headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
|
||||
|
||||
if (request.body && !headers['Content-Length'] && !headers['content-length'])
|
||||
headers['Content-Length'] = Buffer.byteLength(request.body)
|
||||
|
||||
if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token'])
|
||||
headers['X-Amz-Security-Token'] = this.credentials.sessionToken
|
||||
|
||||
if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256'])
|
||||
headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex')
|
||||
|
||||
if (headers['X-Amz-Date'] || headers['x-amz-date'])
|
||||
this.datetime = headers['X-Amz-Date'] || headers['x-amz-date']
|
||||
else
|
||||
headers['X-Amz-Date'] = this.getDateTime()
|
||||
}
|
||||
|
||||
delete headers.Authorization
|
||||
delete headers.authorization
|
||||
}
|
||||
}
|
||||
|
||||
RequestSigner.prototype.sign = function() {
|
||||
if (!this.parsedPath) this.prepareRequest()
|
||||
|
||||
if (this.request.signQuery) {
|
||||
this.parsedPath.query['X-Amz-Signature'] = this.signature()
|
||||
} else {
|
||||
this.request.headers.Authorization = this.authHeader()
|
||||
}
|
||||
|
||||
this.request.path = this.formatPath()
|
||||
|
||||
return this.request
|
||||
}
|
||||
|
||||
RequestSigner.prototype.getDateTime = function() {
|
||||
if (!this.datetime) {
|
||||
var headers = this.request.headers,
|
||||
date = new Date(headers.Date || headers.date || new Date)
|
||||
|
||||
this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '')
|
||||
|
||||
// Remove the trailing 'Z' on the timestamp string for CodeCommit git access
|
||||
if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1)
|
||||
}
|
||||
return this.datetime
|
||||
}
|
||||
|
||||
RequestSigner.prototype.getDate = function() {
|
||||
return this.getDateTime().substr(0, 8)
|
||||
}
|
||||
|
||||
RequestSigner.prototype.authHeader = function() {
|
||||
return [
|
||||
'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(),
|
||||
'SignedHeaders=' + this.signedHeaders(),
|
||||
'Signature=' + this.signature(),
|
||||
].join(', ')
|
||||
}
|
||||
|
||||
RequestSigner.prototype.signature = function() {
|
||||
var date = this.getDate(),
|
||||
cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(),
|
||||
kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey)
|
||||
if (!kCredentials) {
|
||||
kDate = hmac('AWS4' + this.credentials.secretAccessKey, date)
|
||||
kRegion = hmac(kDate, this.region)
|
||||
kService = hmac(kRegion, this.service)
|
||||
kCredentials = hmac(kService, 'aws4_request')
|
||||
credentialsCache.set(cacheKey, kCredentials)
|
||||
}
|
||||
return hmac(kCredentials, this.stringToSign(), 'hex')
|
||||
}
|
||||
|
||||
RequestSigner.prototype.stringToSign = function() {
|
||||
return [
|
||||
'AWS4-HMAC-SHA256',
|
||||
this.getDateTime(),
|
||||
this.credentialString(),
|
||||
hash(this.canonicalString(), 'hex'),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
RequestSigner.prototype.canonicalString = function() {
|
||||
if (!this.parsedPath) this.prepareRequest()
|
||||
|
||||
var pathStr = this.parsedPath.path,
|
||||
query = this.parsedPath.query,
|
||||
headers = this.request.headers,
|
||||
queryStr = '',
|
||||
normalizePath = this.service !== 's3',
|
||||
decodePath = this.service === 's3' || this.request.doNotEncodePath,
|
||||
decodeSlashesInPath = this.service === 's3',
|
||||
firstValOnly = this.service === 's3',
|
||||
bodyHash
|
||||
|
||||
if (this.service === 's3' && this.request.signQuery) {
|
||||
bodyHash = 'UNSIGNED-PAYLOAD'
|
||||
} else if (this.isCodeCommitGit) {
|
||||
bodyHash = ''
|
||||
} else {
|
||||
bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] ||
|
||||
hash(this.request.body || '', 'hex')
|
||||
}
|
||||
|
||||
if (query) {
|
||||
var reducedQuery = Object.keys(query).reduce(function(obj, key) {
|
||||
if (!key) return obj
|
||||
obj[encodeRfc3986Full(key)] = !Array.isArray(query[key]) ? query[key] :
|
||||
(firstValOnly ? query[key][0] : query[key])
|
||||
return obj
|
||||
}, {})
|
||||
var encodedQueryPieces = []
|
||||
Object.keys(reducedQuery).sort().forEach(function(key) {
|
||||
if (!Array.isArray(reducedQuery[key])) {
|
||||
encodedQueryPieces.push(key + '=' + encodeRfc3986Full(reducedQuery[key]))
|
||||
} else {
|
||||
reducedQuery[key].map(encodeRfc3986Full).sort()
|
||||
.forEach(function(val) { encodedQueryPieces.push(key + '=' + val) })
|
||||
}
|
||||
})
|
||||
queryStr = encodedQueryPieces.join('&')
|
||||
}
|
||||
if (pathStr !== '/') {
|
||||
if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/')
|
||||
pathStr = pathStr.split('/').reduce(function(path, piece) {
|
||||
if (normalizePath && piece === '..') {
|
||||
path.pop()
|
||||
} else if (!normalizePath || piece !== '.') {
|
||||
if (decodePath) piece = decodeURIComponent(piece).replace(/\+/g, ' ')
|
||||
path.push(encodeRfc3986Full(piece))
|
||||
}
|
||||
return path
|
||||
}, []).join('/')
|
||||
if (pathStr[0] !== '/') pathStr = '/' + pathStr
|
||||
if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/')
|
||||
}
|
||||
|
||||
return [
|
||||
this.request.method || 'GET',
|
||||
pathStr,
|
||||
queryStr,
|
||||
this.canonicalHeaders() + '\n',
|
||||
this.signedHeaders(),
|
||||
bodyHash,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
RequestSigner.prototype.canonicalHeaders = function() {
|
||||
var headers = this.request.headers
|
||||
function trimAll(header) {
|
||||
return header.toString().trim().replace(/\s+/g, ' ')
|
||||
}
|
||||
return Object.keys(headers)
|
||||
.sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 })
|
||||
.map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) })
|
||||
.join('\n')
|
||||
}
|
||||
|
||||
RequestSigner.prototype.signedHeaders = function() {
|
||||
return Object.keys(this.request.headers)
|
||||
.map(function(key) { return key.toLowerCase() })
|
||||
.sort()
|
||||
.join(';')
|
||||
}
|
||||
|
||||
RequestSigner.prototype.credentialString = function() {
|
||||
return [
|
||||
this.getDate(),
|
||||
this.region,
|
||||
this.service,
|
||||
'aws4_request',
|
||||
].join('/')
|
||||
}
|
||||
|
||||
RequestSigner.prototype.defaultCredentials = function() {
|
||||
var env = process.env
|
||||
return {
|
||||
accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,
|
||||
secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,
|
||||
sessionToken: env.AWS_SESSION_TOKEN,
|
||||
}
|
||||
}
|
||||
|
||||
RequestSigner.prototype.parsePath = function() {
|
||||
var path = this.request.path || '/'
|
||||
|
||||
// S3 doesn't always encode characters > 127 correctly and
|
||||
// all services don't encode characters > 255 correctly
|
||||
// So if there are non-reserved chars (and it's not already all % encoded), just encode them all
|
||||
if (/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(path)) {
|
||||
path = encodeURI(decodeURI(path))
|
||||
}
|
||||
|
||||
var queryIx = path.indexOf('?'),
|
||||
query = null
|
||||
|
||||
if (queryIx >= 0) {
|
||||
query = querystring.parse(path.slice(queryIx + 1))
|
||||
path = path.slice(0, queryIx)
|
||||
}
|
||||
|
||||
this.parsedPath = {
|
||||
path: path,
|
||||
query: query,
|
||||
}
|
||||
}
|
||||
|
||||
RequestSigner.prototype.formatPath = function() {
|
||||
var path = this.parsedPath.path,
|
||||
query = this.parsedPath.query
|
||||
|
||||
if (!query) return path
|
||||
|
||||
// Services don't support empty query string keys
|
||||
if (query[''] != null) delete query['']
|
||||
|
||||
return path + '?' + encodeRfc3986(querystring.stringify(query))
|
||||
}
|
||||
|
||||
aws4.RequestSigner = RequestSigner
|
||||
|
||||
aws4.sign = function(request, credentials) {
|
||||
return new RequestSigner(request, credentials).sign()
|
||||
}
|
||||
-96
@@ -1,96 +0,0 @@
|
||||
module.exports = function(size) {
|
||||
return new LruCache(size)
|
||||
}
|
||||
|
||||
function LruCache(size) {
|
||||
this.capacity = size | 0
|
||||
this.map = Object.create(null)
|
||||
this.list = new DoublyLinkedList()
|
||||
}
|
||||
|
||||
LruCache.prototype.get = function(key) {
|
||||
var node = this.map[key]
|
||||
if (node == null) return undefined
|
||||
this.used(node)
|
||||
return node.val
|
||||
}
|
||||
|
||||
LruCache.prototype.set = function(key, val) {
|
||||
var node = this.map[key]
|
||||
if (node != null) {
|
||||
node.val = val
|
||||
} else {
|
||||
if (!this.capacity) this.prune()
|
||||
if (!this.capacity) return false
|
||||
node = new DoublyLinkedNode(key, val)
|
||||
this.map[key] = node
|
||||
this.capacity--
|
||||
}
|
||||
this.used(node)
|
||||
return true
|
||||
}
|
||||
|
||||
LruCache.prototype.used = function(node) {
|
||||
this.list.moveToFront(node)
|
||||
}
|
||||
|
||||
LruCache.prototype.prune = function() {
|
||||
var node = this.list.pop()
|
||||
if (node != null) {
|
||||
delete this.map[node.key]
|
||||
this.capacity++
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function DoublyLinkedList() {
|
||||
this.firstNode = null
|
||||
this.lastNode = null
|
||||
}
|
||||
|
||||
DoublyLinkedList.prototype.moveToFront = function(node) {
|
||||
if (this.firstNode == node) return
|
||||
|
||||
this.remove(node)
|
||||
|
||||
if (this.firstNode == null) {
|
||||
this.firstNode = node
|
||||
this.lastNode = node
|
||||
node.prev = null
|
||||
node.next = null
|
||||
} else {
|
||||
node.prev = null
|
||||
node.next = this.firstNode
|
||||
node.next.prev = node
|
||||
this.firstNode = node
|
||||
}
|
||||
}
|
||||
|
||||
DoublyLinkedList.prototype.pop = function() {
|
||||
var lastNode = this.lastNode
|
||||
if (lastNode != null) {
|
||||
this.remove(lastNode)
|
||||
}
|
||||
return lastNode
|
||||
}
|
||||
|
||||
DoublyLinkedList.prototype.remove = function(node) {
|
||||
if (this.firstNode == node) {
|
||||
this.firstNode = node.next
|
||||
} else if (node.prev != null) {
|
||||
node.prev.next = node.next
|
||||
}
|
||||
if (this.lastNode == node) {
|
||||
this.lastNode = node.prev
|
||||
} else if (node.next != null) {
|
||||
node.next.prev = node.prev
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function DoublyLinkedNode(key, val) {
|
||||
this.key = key
|
||||
this.val = val
|
||||
this.prev = null
|
||||
this.next = null
|
||||
}
|
||||
-105
@@ -1,105 +0,0 @@
|
||||
{
|
||||
"_from": "aws4@^1.8.0",
|
||||
"_id": "aws4@1.9.1",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-wMHVg2EOHaMRxbzgFJ9gtjOOCrI80OHLG14rxi28XwOW8ux6IiEbRCGGGqCtdAIg4FQCbW20k9RsT4y3gJlFug==",
|
||||
"_location": "/aws4",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "aws4@^1.8.0",
|
||||
"name": "aws4",
|
||||
"escapedName": "aws4",
|
||||
"rawSpec": "^1.8.0",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^1.8.0"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/request"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/aws4/-/aws4-1.9.1.tgz",
|
||||
"_shasum": "7e33d8f7d449b3f673cd72deb9abdc552dbe528e",
|
||||
"_spec": "aws4@^1.8.0",
|
||||
"_where": "O:\\zero\\zero.Web\\node_modules\\request",
|
||||
"author": {
|
||||
"name": "Michael Hart",
|
||||
"email": "michael.hart.au@gmail.com",
|
||||
"url": "http://github.com/mhart"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/mhart/aws4/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"deprecated": false,
|
||||
"description": "Signs and prepares requests using AWS Signature Version 4",
|
||||
"devDependencies": {
|
||||
"mocha": "^2.4.5",
|
||||
"should": "^8.2.2"
|
||||
},
|
||||
"homepage": "https://github.com/mhart/aws4#readme",
|
||||
"keywords": [
|
||||
"amazon",
|
||||
"aws",
|
||||
"signature",
|
||||
"s3",
|
||||
"ec2",
|
||||
"autoscaling",
|
||||
"cloudformation",
|
||||
"elasticloadbalancing",
|
||||
"elb",
|
||||
"elasticbeanstalk",
|
||||
"cloudsearch",
|
||||
"dynamodb",
|
||||
"kinesis",
|
||||
"lambda",
|
||||
"glacier",
|
||||
"sqs",
|
||||
"sns",
|
||||
"iam",
|
||||
"sts",
|
||||
"ses",
|
||||
"swf",
|
||||
"storagegateway",
|
||||
"datapipeline",
|
||||
"directconnect",
|
||||
"redshift",
|
||||
"opsworks",
|
||||
"rds",
|
||||
"monitoring",
|
||||
"cloudtrail",
|
||||
"cloudfront",
|
||||
"codedeploy",
|
||||
"elasticache",
|
||||
"elasticmapreduce",
|
||||
"elastictranscoder",
|
||||
"emr",
|
||||
"cloudwatch",
|
||||
"mobileanalytics",
|
||||
"cognitoidentity",
|
||||
"cognitosync",
|
||||
"cognito",
|
||||
"containerservice",
|
||||
"ecs",
|
||||
"appstream",
|
||||
"keymanagementservice",
|
||||
"kms",
|
||||
"config",
|
||||
"cloudhsm",
|
||||
"route53",
|
||||
"route53domains",
|
||||
"logs"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "aws4.js",
|
||||
"name": "aws4",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/mhart/aws4.git"
|
||||
},
|
||||
"scripts": {
|
||||
"integration": "node ./test/slow.js",
|
||||
"test": "mocha ./test/fast.js -b -t 100s -R list"
|
||||
},
|
||||
"version": "1.9.1"
|
||||
}
|
||||
-413
@@ -1,413 +0,0 @@
|
||||
# Changelog
|
||||
|
||||
### 0.19.2 (Jan 20, 2020)
|
||||
|
||||
- Remove unnecessary XSS check ([#2679](https://github.com/axios/axios/pull/2679)) (see ([#2646](https://github.com/axios/axios/issues/2646)) for discussion)
|
||||
|
||||
### 0.19.1 (Jan 7, 2020)
|
||||
|
||||
Fixes and Functionality:
|
||||
|
||||
- Fixing invalid agent issue ([#1904](https://github.com/axios/axios/pull/1904))
|
||||
- Fix ignore set withCredentials false ([#2582](https://github.com/axios/axios/pull/2582))
|
||||
- Delete useless default to hash ([#2458](https://github.com/axios/axios/pull/2458))
|
||||
- Fix HTTP/HTTPs agents passing to follow-redirect ([#1904](https://github.com/axios/axios/pull/1904))
|
||||
- Fix ignore set withCredentials false ([#2582](https://github.com/axios/axios/pull/2582))
|
||||
- Fix CI build failure ([#2570](https://github.com/axios/axios/pull/2570))
|
||||
- Remove dependency on is-buffer from package.json ([#1816](https://github.com/axios/axios/pull/1816))
|
||||
- Adding options typings ([#2341](https://github.com/axios/axios/pull/2341))
|
||||
- Adding Typescript HTTP method definition for LINK and UNLINK. ([#2444](https://github.com/axios/axios/pull/2444))
|
||||
- Update dist with newest changes, fixes Custom Attributes issue
|
||||
- Change syntax to see if build passes ([#2488](https://github.com/axios/axios/pull/2488))
|
||||
- Update Webpack + deps, remove now unnecessary polyfills ([#2410](https://github.com/axios/axios/pull/2410))
|
||||
- Fix to prevent XSS, throw an error when the URL contains a JS script ([#2464](https://github.com/axios/axios/pull/2464))
|
||||
- Add custom timeout error copy in config ([#2275](https://github.com/axios/axios/pull/2275))
|
||||
- Add error toJSON example ([#2466](https://github.com/axios/axios/pull/2466))
|
||||
- Fixing Vulnerability A Fortify Scan finds a critical Cross-Site Scrip… ([#2451](https://github.com/axios/axios/pull/2451))
|
||||
- Fixing subdomain handling on no_proxy ([#2442](https://github.com/axios/axios/pull/2442))
|
||||
- Make redirection from HTTP to HTTPS work ([#2426](https://github.com/axios/axios/pull/2426] and ([#2547](https://github.com/axios/axios/pull/2547))
|
||||
- Add toJSON property to AxiosError type ([#2427](https://github.com/axios/axios/pull/2427))
|
||||
- Fixing socket hang up error on node side for slow response. ([#1752](https://github.com/axios/axios/pull/1752))
|
||||
- Alternative syntax to send data into the body ([#2317](https://github.com/axios/axios/pull/2317))
|
||||
- Fixing custom config options ([#2207](https://github.com/axios/axios/pull/2207))
|
||||
- Fixing set `config.method` after mergeConfig for Axios.prototype.request ([#2383](https://github.com/axios/axios/pull/2383))
|
||||
- Axios create url bug ([#2290](https://github.com/axios/axios/pull/2290))
|
||||
- Do not modify config.url when using a relative baseURL (resolves [#1628](https://github.com/axios/axios/issues/1098)) ([#2391](https://github.com/axios/axios/pull/2391))
|
||||
- Add typescript HTTP method definition for LINK and UNLINK ([#2444](https://github.com/axios/axios/pull/2444))
|
||||
|
||||
Internal:
|
||||
|
||||
- Revert "Update Webpack + deps, remove now unnecessary polyfills" ([#2479](https://github.com/axios/axios/pull/2479))
|
||||
- Order of if/else blocks is causing unit tests mocking XHR. ([#2201](https://github.com/axios/axios/pull/2201))
|
||||
- Add license badge ([#2446](https://github.com/axios/axios/pull/2446))
|
||||
- Fix travis CI build [#2386](https://github.com/axios/axios/pull/2386)
|
||||
- Fix cancellation error on build master. #2290 #2207 ([#2407](https://github.com/axios/axios/pull/2407))
|
||||
|
||||
Documentation:
|
||||
|
||||
- Fixing typo in CHANGELOG.md: s/Functionallity/Functionality ([#2639](https://github.com/axios/axios/pull/2639))
|
||||
- Fix badge, use master branch ([#2538](https://github.com/axios/axios/pull/2538))
|
||||
- Fix typo in changelog [#2193](https://github.com/axios/axios/pull/2193)
|
||||
- Document fix ([#2514](https://github.com/axios/axios/pull/2514))
|
||||
- Update docs with no_proxy change, issue #2484 ([#2513](https://github.com/axios/axios/pull/2513))
|
||||
- Fixing missing words in docs template ([#2259](https://github.com/axios/axios/pull/2259))
|
||||
- 🐛Fix request finally documentation in README ([#2189](https://github.com/axios/axios/pull/2189))
|
||||
- updating spelling and adding link to docs ([#2212](https://github.com/axios/axios/pull/2212))
|
||||
- docs: minor tweak ([#2404](https://github.com/axios/axios/pull/2404))
|
||||
- Update response interceptor docs ([#2399](https://github.com/axios/axios/pull/2399))
|
||||
- Update README.md ([#2504](https://github.com/axios/axios/pull/2504))
|
||||
- Fix word 'sintaxe' to 'syntax' in README.md ([#2432](https://github.com/axios/axios/pull/2432))
|
||||
- upadating README: notes on CommonJS autocomplete ([#2256](https://github.com/axios/axios/pull/2256))
|
||||
- Fix grammar in README.md ([#2271](https://github.com/axios/axios/pull/2271))
|
||||
- Doc fixes, minor examples cleanup ([#2198](https://github.com/axios/axios/pull/2198))
|
||||
|
||||
### 0.19.0 (May 30, 2019)
|
||||
|
||||
Fixes and Functionality:
|
||||
|
||||
- Added support for no_proxy env variable ([#1693](https://github.com/axios/axios/pull/1693/files)) - Chance Dickson
|
||||
- Unzip response body only for statuses != 204 ([#1129](https://github.com/axios/axios/pull/1129)) - drawski
|
||||
- Destroy stream on exceeding maxContentLength (fixes [#1098](https://github.com/axios/axios/issues/1098)) ([#1485](https://github.com/axios/axios/pull/1485)) - Gadzhi Gadzhiev
|
||||
- Makes Axios error generic to use AxiosResponse ([#1738](https://github.com/axios/axios/pull/1738)) - Suman Lama
|
||||
- Fixing Mocha tests by locking follow-redirects version to 1.5.10 ([#1993](https://github.com/axios/axios/pull/1993)) - grumblerchester
|
||||
- Allow uppercase methods in typings. ([#1781](https://github.com/axios/axios/pull/1781)) - Ken Powers
|
||||
- Fixing building url with hash mark ([#1771](https://github.com/axios/axios/pull/1771)) - Anatoly Ryabov
|
||||
- This commit fix building url with hash map (fragment identifier) when parameters are present: they must not be added after `#`, because client cut everything after `#`
|
||||
- Preserve HTTP method when following redirect ([#1758](https://github.com/axios/axios/pull/1758)) - Rikki Gibson
|
||||
- Add `getUri` signature to TypeScript definition. ([#1736](https://github.com/axios/axios/pull/1736)) - Alexander Trauzzi
|
||||
- Adding isAxiosError flag to errors thrown by axios ([#1419](https://github.com/axios/axios/pull/1419)) - Ayush Gupta
|
||||
|
||||
Internal:
|
||||
|
||||
- Fixing .eslintrc without extension ([#1789](https://github.com/axios/axios/pull/1789)) - Manoel
|
||||
- Fix failing SauceLabs tests by updating configuration - Emily Morehouse
|
||||
- Add issue templates - Emily Morehouse
|
||||
|
||||
Documentation:
|
||||
|
||||
- Consistent coding style in README ([#1787](https://github.com/axios/axios/pull/1787)) - Ali Servet Donmez
|
||||
- Add information about auth parameter to README ([#2166](https://github.com/axios/axios/pull/2166)) - xlaguna
|
||||
- Add DELETE to list of methods that allow data as a config option ([#2169](https://github.com/axios/axios/pull/2169)) - Daniela Borges Matos de Carvalho
|
||||
- Update ECOSYSTEM.md - Add Axios Endpoints ([#2176](https://github.com/axios/axios/pull/2176)) - Renan
|
||||
- Add r2curl in ECOSYSTEM ([#2141](https://github.com/axios/axios/pull/2141)) - 유용우 / CX
|
||||
- Update README.md - Add instructions for installing with yarn ([#2036](https://github.com/axios/axios/pull/2036)) - Victor Hermes
|
||||
- Fixing spacing for README.md ([#2066](https://github.com/axios/axios/pull/2066)) - Josh McCarty
|
||||
- Update README.md. - Change `.then` to `.finally` in example code ([#2090](https://github.com/axios/axios/pull/2090)) - Omar Cai
|
||||
- Clarify what values responseType can have in Node ([#2121](https://github.com/axios/axios/pull/2121)) - Tyler Breisacher
|
||||
- docs(ECOSYSTEM): add axios-api-versioning ([#2020](https://github.com/axios/axios/pull/2020)) - Weffe
|
||||
- It seems that `responseType: 'blob'` doesn't actually work in Node (when I tried using it, response.data was a string, not a Blob, since Node doesn't have Blobs), so this clarifies that this option should only be used in the browser
|
||||
- Update README.md. - Add Querystring library note ([#1896](https://github.com/axios/axios/pull/1896)) - Dmitriy Eroshenko
|
||||
- Add react-hooks-axios to Libraries section of ECOSYSTEM.md ([#1925](https://github.com/axios/axios/pull/1925)) - Cody Chan
|
||||
- Clarify in README that default timeout is 0 (no timeout) ([#1750](https://github.com/axios/axios/pull/1750)) - Ben Standefer
|
||||
|
||||
### 0.19.0-beta.1 (Aug 9, 2018)
|
||||
|
||||
**NOTE:** This is a beta version of this release. There may be functionality that is broken in
|
||||
certain browsers, though we suspect that builds are hanging and not erroring. See
|
||||
https://saucelabs.com/u/axios for the most up-to-date information.
|
||||
|
||||
New Functionality:
|
||||
|
||||
- Add getUri method ([#1712](https://github.com/axios/axios/issues/1712))
|
||||
- Add support for no_proxy env variable ([#1693](https://github.com/axios/axios/issues/1693))
|
||||
- Add toJSON to decorated Axios errors to faciliate serialization ([#1625](https://github.com/axios/axios/issues/1625))
|
||||
- Add second then on axios call ([#1623](https://github.com/axios/axios/issues/1623))
|
||||
- Typings: allow custom return types
|
||||
- Add option to specify character set in responses (with http adapter)
|
||||
|
||||
Fixes:
|
||||
|
||||
- Fix Keep defaults local to instance ([#385](https://github.com/axios/axios/issues/385))
|
||||
- Correctly catch exception in http test ([#1475](https://github.com/axios/axios/issues/1475))
|
||||
- Fix accept header normalization ([#1698](https://github.com/axios/axios/issues/1698))
|
||||
- Fix http adapter to allow HTTPS connections via HTTP ([#959](https://github.com/axios/axios/issues/959))
|
||||
- Fix Removes usage of deprecated Buffer constructor. ([#1555](https://github.com/axios/axios/issues/1555), [#1622](https://github.com/axios/axios/issues/1622))
|
||||
- Fix defaults to use httpAdapter if available ([#1285](https://github.com/axios/axios/issues/1285))
|
||||
- Fixing defaults to use httpAdapter if available
|
||||
- Use a safer, cross-platform method to detect the Node environment
|
||||
- Fix Reject promise if request is cancelled by the browser ([#537](https://github.com/axios/axios/issues/537))
|
||||
- [Typescript] Fix missing type parameters on delete/head methods
|
||||
- [NS]: Send `false` flag isStandardBrowserEnv for Nativescript
|
||||
- Fix missing type parameters on delete/head
|
||||
- Fix Default method for an instance always overwritten by get
|
||||
- Fix type error when socketPath option in AxiosRequestConfig
|
||||
- Capture errors on request data streams
|
||||
- Decorate resolve and reject to clear timeout in all cases
|
||||
|
||||
Huge thanks to everyone who contributed to this release via code (authors listed
|
||||
below) or via reviews and triaging on GitHub:
|
||||
|
||||
- Andrew Scott <ascott18@gmail.com>
|
||||
- Anthony Gauthier <antho325@hotmail.com>
|
||||
- arpit <arpit2438735@gmail.com>
|
||||
- ascott18
|
||||
- Benedikt Rötsch <axe312ger@users.noreply.github.com>
|
||||
- Chance Dickson <me@chancedickson.com>
|
||||
- Dave Stewart <info@davestewart.co.uk>
|
||||
- Deric Cain <deric.cain@gmail.com>
|
||||
- Guillaume Briday <guillaumebriday@gmail.com>
|
||||
- Jacob Wejendorp <jacob@wejendorp.dk>
|
||||
- Jim Lynch <mrdotjim@gmail.com>
|
||||
- johntron
|
||||
- Justin Beckwith <beckwith@google.com>
|
||||
- Justin Beckwith <justin.beckwith@gmail.com>
|
||||
- Khaled Garbaya <khaledgarbaya@gmail.com>
|
||||
- Lim Jing Rong <jjingrong@users.noreply.github.com>
|
||||
- Mark van den Broek <mvdnbrk@gmail.com>
|
||||
- Martti Laine <martti@codeclown.net>
|
||||
- mattridley
|
||||
- mattridley <matt.r@joinblink.com>
|
||||
- Nicolas Del Valle <nicolas.delvalle@gmail.com>
|
||||
- Nilegfx
|
||||
- pbarbiero
|
||||
- Rikki Gibson <rikkigibson@gmail.com>
|
||||
- Sako Hartounian <sakohartounian@yahoo.com>
|
||||
- Shane Fitzpatrick <fitzpasd@gmail.com>
|
||||
- Stephan Schneider <stephanschndr@gmail.com>
|
||||
- Steven <steven@ceriously.com>
|
||||
- Tim Garthwaite <tim.garthwaite@jibo.com>
|
||||
- Tim Johns <timjohns@yahoo.com>
|
||||
- Yutaro Miyazaki <yutaro@studio-rubbish.com>
|
||||
|
||||
### 0.18.0 (Feb 19, 2018)
|
||||
|
||||
- Adding support for UNIX Sockets when running with Node.js ([#1070](https://github.com/axios/axios/pull/1070))
|
||||
- Fixing typings ([#1177](https://github.com/axios/axios/pull/1177)):
|
||||
- AxiosRequestConfig.proxy: allows type false
|
||||
- AxiosProxyConfig: added auth field
|
||||
- Adding function signature in AxiosInstance interface so AxiosInstance can be invoked ([#1192](https://github.com/axios/axios/pull/1192), [#1254](https://github.com/axios/axios/pull/1254))
|
||||
- Allowing maxContentLength to pass through to redirected calls as maxBodyLength in follow-redirects config ([#1287](https://github.com/axios/axios/pull/1287))
|
||||
- Fixing configuration when using an instance - method can now be set ([#1342](https://github.com/axios/axios/pull/1342))
|
||||
|
||||
### 0.17.1 (Nov 11, 2017)
|
||||
|
||||
- Fixing issue with web workers ([#1160](https://github.com/axios/axios/pull/1160))
|
||||
- Allowing overriding transport ([#1080](https://github.com/axios/axios/pull/1080))
|
||||
- Updating TypeScript typings ([#1165](https://github.com/axios/axios/pull/1165), [#1125](https://github.com/axios/axios/pull/1125), [#1131](https://github.com/axios/axios/pull/1131))
|
||||
|
||||
### 0.17.0 (Oct 21, 2017)
|
||||
|
||||
- **BREAKING** Fixing issue with `baseURL` and interceptors ([#950](https://github.com/axios/axios/pull/950))
|
||||
- **BREAKING** Improving handing of duplicate headers ([#874](https://github.com/axios/axios/pull/874))
|
||||
- Adding support for disabling proxies ([#691](https://github.com/axios/axios/pull/691))
|
||||
- Updating TypeScript typings with generic type parameters ([#1061](https://github.com/axios/axios/pull/1061))
|
||||
|
||||
### 0.16.2 (Jun 3, 2017)
|
||||
|
||||
- Fixing issue with including `buffer` in bundle ([#887](https://github.com/axios/axios/pull/887))
|
||||
- Including underlying request in errors ([#830](https://github.com/axios/axios/pull/830))
|
||||
- Convert `method` to lowercase ([#930](https://github.com/axios/axios/pull/930))
|
||||
|
||||
### 0.16.1 (Apr 8, 2017)
|
||||
|
||||
- Improving HTTP adapter to return last request in case of redirects ([#828](https://github.com/axios/axios/pull/828))
|
||||
- Updating `follow-redirects` dependency ([#829](https://github.com/axios/axios/pull/829))
|
||||
- Adding support for passing `Buffer` in node ([#773](https://github.com/axios/axios/pull/773))
|
||||
|
||||
### 0.16.0 (Mar 31, 2017)
|
||||
|
||||
- **BREAKING** Removing `Promise` from axios typings in favor of built-in type declarations ([#480](https://github.com/axios/axios/issues/480))
|
||||
- Adding `options` shortcut method ([#461](https://github.com/axios/axios/pull/461))
|
||||
- Fixing issue with using `responseType: 'json'` in browsers incompatible with XHR Level 2 ([#654](https://github.com/axios/axios/pull/654))
|
||||
- Improving React Native detection ([#731](https://github.com/axios/axios/pull/731))
|
||||
- Fixing `combineURLs` to support empty `relativeURL` ([#581](https://github.com/axios/axios/pull/581))
|
||||
- Removing `PROTECTION_PREFIX` support ([#561](https://github.com/axios/axios/pull/561))
|
||||
|
||||
### 0.15.3 (Nov 27, 2016)
|
||||
|
||||
- Fixing issue with custom instances and global defaults ([#443](https://github.com/axios/axios/issues/443))
|
||||
- Renaming `axios.d.ts` to `index.d.ts` ([#519](https://github.com/axios/axios/issues/519))
|
||||
- Adding `get`, `head`, and `delete` to `defaults.headers` ([#509](https://github.com/axios/axios/issues/509))
|
||||
- Fixing issue with `btoa` and IE ([#507](https://github.com/axios/axios/issues/507))
|
||||
- Adding support for proxy authentication ([#483](https://github.com/axios/axios/pull/483))
|
||||
- Improving HTTP adapter to use `http` protocol by default ([#493](https://github.com/axios/axios/pull/493))
|
||||
- Fixing proxy issues ([#491](https://github.com/axios/axios/pull/491))
|
||||
|
||||
### 0.15.2 (Oct 17, 2016)
|
||||
|
||||
- Fixing issue with calling `cancel` after response has been received ([#482](https://github.com/axios/axios/issues/482))
|
||||
|
||||
### 0.15.1 (Oct 14, 2016)
|
||||
|
||||
- Fixing issue with UMD ([#485](https://github.com/axios/axios/issues/485))
|
||||
|
||||
### 0.15.0 (Oct 10, 2016)
|
||||
|
||||
- Adding cancellation support ([#452](https://github.com/axios/axios/pull/452))
|
||||
- Moving default adapter to global defaults ([#437](https://github.com/axios/axios/pull/437))
|
||||
- Fixing issue with `file` URI scheme ([#440](https://github.com/axios/axios/pull/440))
|
||||
- Fixing issue with `params` objects that have no prototype ([#445](https://github.com/axios/axios/pull/445))
|
||||
|
||||
### 0.14.0 (Aug 27, 2016)
|
||||
|
||||
- **BREAKING** Updating TypeScript definitions ([#419](https://github.com/axios/axios/pull/419))
|
||||
- **BREAKING** Replacing `agent` option with `httpAgent` and `httpsAgent` ([#387](https://github.com/axios/axios/pull/387))
|
||||
- **BREAKING** Splitting `progress` event handlers into `onUploadProgress` and `onDownloadProgress` ([#423](https://github.com/axios/axios/pull/423))
|
||||
- Adding support for `http_proxy` and `https_proxy` environment variables ([#366](https://github.com/axios/axios/pull/366))
|
||||
- Fixing issue with `auth` config option and `Authorization` header ([#397](https://github.com/axios/axios/pull/397))
|
||||
- Don't set XSRF header if `xsrfCookieName` is `null` ([#406](https://github.com/axios/axios/pull/406))
|
||||
|
||||
### 0.13.1 (Jul 16, 2016)
|
||||
|
||||
- Fixing issue with response data not being transformed on error ([#378](https://github.com/axios/axios/issues/378))
|
||||
|
||||
### 0.13.0 (Jul 13, 2016)
|
||||
|
||||
- **BREAKING** Improved error handling ([#345](https://github.com/axios/axios/pull/345))
|
||||
- **BREAKING** Response transformer now invoked in dispatcher not adapter ([10eb238](https://github.com/axios/axios/commit/10eb23865101f9347570552c04e9d6211376e25e))
|
||||
- **BREAKING** Request adapters now return a `Promise` ([157efd5](https://github.com/axios/axios/commit/157efd5615890301824e3121cc6c9d2f9b21f94a))
|
||||
- Fixing issue with `withCredentials` not being overwritten ([#343](https://github.com/axios/axios/issues/343))
|
||||
- Fixing regression with request transformer being called before request interceptor ([#352](https://github.com/axios/axios/issues/352))
|
||||
- Fixing custom instance defaults ([#341](https://github.com/axios/axios/issues/341))
|
||||
- Fixing instances created from `axios.create` to have same API as default axios ([#217](https://github.com/axios/axios/issues/217))
|
||||
|
||||
### 0.12.0 (May 31, 2016)
|
||||
|
||||
- Adding support for `URLSearchParams` ([#317](https://github.com/axios/axios/pull/317))
|
||||
- Adding `maxRedirects` option ([#307](https://github.com/axios/axios/pull/307))
|
||||
|
||||
### 0.11.1 (May 17, 2016)
|
||||
|
||||
- Fixing IE CORS support ([#313](https://github.com/axios/axios/pull/313))
|
||||
- Fixing detection of `FormData` ([#325](https://github.com/axios/axios/pull/325))
|
||||
- Adding `Axios` class to exports ([#321](https://github.com/axios/axios/pull/321))
|
||||
|
||||
### 0.11.0 (Apr 26, 2016)
|
||||
|
||||
- Adding support for Stream with HTTP adapter ([#296](https://github.com/axios/axios/pull/296))
|
||||
- Adding support for custom HTTP status code error ranges ([#308](https://github.com/axios/axios/pull/308))
|
||||
- Fixing issue with ArrayBuffer ([#299](https://github.com/axios/axios/pull/299))
|
||||
|
||||
### 0.10.0 (Apr 20, 2016)
|
||||
|
||||
- Fixing issue with some requests sending `undefined` instead of `null` ([#250](https://github.com/axios/axios/pull/250))
|
||||
- Fixing basic auth for HTTP adapter ([#252](https://github.com/axios/axios/pull/252))
|
||||
- Fixing request timeout for XHR adapter ([#227](https://github.com/axios/axios/pull/227))
|
||||
- Fixing IE8 support by using `onreadystatechange` instead of `onload` ([#249](https://github.com/axios/axios/pull/249))
|
||||
- Fixing IE9 cross domain requests ([#251](https://github.com/axios/axios/pull/251))
|
||||
- Adding `maxContentLength` option ([#275](https://github.com/axios/axios/pull/275))
|
||||
- Fixing XHR support for WebWorker environment ([#279](https://github.com/axios/axios/pull/279))
|
||||
- Adding request instance to response ([#200](https://github.com/axios/axios/pull/200))
|
||||
|
||||
### 0.9.1 (Jan 24, 2016)
|
||||
|
||||
- Improving handling of request timeout in node ([#124](https://github.com/axios/axios/issues/124))
|
||||
- Fixing network errors not rejecting ([#205](https://github.com/axios/axios/pull/205))
|
||||
- Fixing issue with IE rejecting on HTTP 204 ([#201](https://github.com/axios/axios/issues/201))
|
||||
- Fixing host/port when following redirects ([#198](https://github.com/axios/axios/pull/198))
|
||||
|
||||
### 0.9.0 (Jan 18, 2016)
|
||||
|
||||
- Adding support for custom adapters
|
||||
- Fixing Content-Type header being removed when data is false ([#195](https://github.com/axios/axios/pull/195))
|
||||
- Improving XDomainRequest implementation ([#185](https://github.com/axios/axios/pull/185))
|
||||
- Improving config merging and order of precedence ([#183](https://github.com/axios/axios/pull/183))
|
||||
- Fixing XDomainRequest support for only <= IE9 ([#182](https://github.com/axios/axios/pull/182))
|
||||
|
||||
### 0.8.1 (Dec 14, 2015)
|
||||
|
||||
- Adding support for passing XSRF token for cross domain requests when using `withCredentials` ([#168](https://github.com/axios/axios/pull/168))
|
||||
- Fixing error with format of basic auth header ([#178](https://github.com/axios/axios/pull/173))
|
||||
- Fixing error with JSON payloads throwing `InvalidStateError` in some cases ([#174](https://github.com/axios/axios/pull/174))
|
||||
|
||||
### 0.8.0 (Dec 11, 2015)
|
||||
|
||||
- Adding support for creating instances of axios ([#123](https://github.com/axios/axios/pull/123))
|
||||
- Fixing http adapter to use `Buffer` instead of `String` in case of `responseType === 'arraybuffer'` ([#128](https://github.com/axios/axios/pull/128))
|
||||
- Adding support for using custom parameter serializer with `paramsSerializer` option ([#121](https://github.com/axios/axios/pull/121))
|
||||
- Fixing issue in IE8 caused by `forEach` on `arguments` ([#127](https://github.com/axios/axios/pull/127))
|
||||
- Adding support for following redirects in node ([#146](https://github.com/axios/axios/pull/146))
|
||||
- Adding support for transparent decompression if `content-encoding` is set ([#149](https://github.com/axios/axios/pull/149))
|
||||
- Adding support for transparent XDomainRequest to handle cross domain requests in IE9 ([#140](https://github.com/axios/axios/pull/140))
|
||||
- Adding support for HTTP basic auth via Authorization header ([#167](https://github.com/axios/axios/pull/167))
|
||||
- Adding support for baseURL option ([#160](https://github.com/axios/axios/pull/160))
|
||||
|
||||
### 0.7.0 (Sep 29, 2015)
|
||||
|
||||
- Fixing issue with minified bundle in IE8 ([#87](https://github.com/axios/axios/pull/87))
|
||||
- Adding support for passing agent in node ([#102](https://github.com/axios/axios/pull/102))
|
||||
- Adding support for returning result from `axios.spread` for chaining ([#106](https://github.com/axios/axios/pull/106))
|
||||
- Fixing typescript definition ([#105](https://github.com/axios/axios/pull/105))
|
||||
- Fixing default timeout config for node ([#112](https://github.com/axios/axios/pull/112))
|
||||
- Adding support for use in web workers, and react-native ([#70](https://github.com/axios/axios/issue/70)), ([#98](https://github.com/axios/axios/pull/98))
|
||||
- Adding support for fetch like API `axios(url[, config])` ([#116](https://github.com/axios/axios/issues/116))
|
||||
|
||||
### 0.6.0 (Sep 21, 2015)
|
||||
|
||||
- Removing deprecated success/error aliases
|
||||
- Fixing issue with array params not being properly encoded ([#49](https://github.com/axios/axios/pull/49))
|
||||
- Fixing issue with User-Agent getting overridden ([#69](https://github.com/axios/axios/issues/69))
|
||||
- Adding support for timeout config ([#56](https://github.com/axios/axios/issues/56))
|
||||
- Removing es6-promise dependency
|
||||
- Fixing issue preventing `length` to be used as a parameter ([#91](https://github.com/axios/axios/pull/91))
|
||||
- Fixing issue with IE8 ([#85](https://github.com/axios/axios/pull/85))
|
||||
- Converting build to UMD
|
||||
|
||||
### 0.5.4 (Apr 08, 2015)
|
||||
|
||||
- Fixing issue with FormData not being sent ([#53](https://github.com/axios/axios/issues/53))
|
||||
|
||||
### 0.5.3 (Apr 07, 2015)
|
||||
|
||||
- Using JSON.parse unconditionally when transforming response string ([#55](https://github.com/axios/axios/issues/55))
|
||||
|
||||
### 0.5.2 (Mar 13, 2015)
|
||||
|
||||
- Adding support for `statusText` in response ([#46](https://github.com/axios/axios/issues/46))
|
||||
|
||||
### 0.5.1 (Mar 10, 2015)
|
||||
|
||||
- Fixing issue using strict mode ([#45](https://github.com/axios/axios/issues/45))
|
||||
- Fixing issue with standalone build ([#47](https://github.com/axios/axios/issues/47))
|
||||
|
||||
### 0.5.0 (Jan 23, 2015)
|
||||
|
||||
- Adding support for intercepetors ([#14](https://github.com/axios/axios/issues/14))
|
||||
- Updating es6-promise dependency
|
||||
|
||||
### 0.4.2 (Dec 10, 2014)
|
||||
|
||||
- Fixing issue with `Content-Type` when using `FormData` ([#22](https://github.com/axios/axios/issues/22))
|
||||
- Adding support for TypeScript ([#25](https://github.com/axios/axios/issues/25))
|
||||
- Fixing issue with standalone build ([#29](https://github.com/axios/axios/issues/29))
|
||||
- Fixing issue with verbs needing to be capitalized in some browsers ([#30](https://github.com/axios/axios/issues/30))
|
||||
|
||||
### 0.4.1 (Oct 15, 2014)
|
||||
|
||||
- Adding error handling to request for node.js ([#18](https://github.com/axios/axios/issues/18))
|
||||
|
||||
### 0.4.0 (Oct 03, 2014)
|
||||
|
||||
- Adding support for `ArrayBuffer` and `ArrayBufferView` ([#10](https://github.com/axios/axios/issues/10))
|
||||
- Adding support for utf-8 for node.js ([#13](https://github.com/axios/axios/issues/13))
|
||||
- Adding support for SSL for node.js ([#12](https://github.com/axios/axios/issues/12))
|
||||
- Fixing incorrect `Content-Type` header ([#9](https://github.com/axios/axios/issues/9))
|
||||
- Adding standalone build without bundled es6-promise ([#11](https://github.com/axios/axios/issues/11))
|
||||
- Deprecating `success`/`error` in favor of `then`/`catch`
|
||||
|
||||
### 0.3.1 (Sep 16, 2014)
|
||||
|
||||
- Fixing missing post body when using node.js ([#3](https://github.com/axios/axios/issues/3))
|
||||
|
||||
### 0.3.0 (Sep 16, 2014)
|
||||
|
||||
- Fixing `success` and `error` to properly receive response data as individual arguments ([#8](https://github.com/axios/axios/issues/8))
|
||||
- Updating `then` and `catch` to receive response data as a single object ([#6](https://github.com/axios/axios/issues/6))
|
||||
- Fixing issue with `all` not working ([#7](https://github.com/axios/axios/issues/7))
|
||||
|
||||
### 0.2.2 (Sep 14, 2014)
|
||||
|
||||
- Fixing bundling with browserify ([#4](https://github.com/axios/axios/issues/4))
|
||||
|
||||
### 0.2.1 (Sep 12, 2014)
|
||||
|
||||
- Fixing build problem causing ridiculous file sizes
|
||||
|
||||
### 0.2.0 (Sep 12, 2014)
|
||||
|
||||
- Adding support for `all` and `spread`
|
||||
- Adding support for node.js ([#1](https://github.com/axios/axios/issues/1))
|
||||
|
||||
### 0.1.0 (Aug 29, 2014)
|
||||
|
||||
- Initial release
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
Copyright (c) 2014-present Matt Zabriskie
|
||||
|
||||
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.
|
||||
-709
@@ -1,709 +0,0 @@
|
||||
# axios
|
||||
|
||||
[](https://www.npmjs.org/package/axios)
|
||||
[](https://travis-ci.org/axios/axios)
|
||||
[](https://coveralls.io/r/mzabriskie/axios)
|
||||
[](https://packagephobia.now.sh/result?p=axios)
|
||||
[](http://npm-stat.com/charts.html?package=axios)
|
||||
[](https://gitter.im/mzabriskie/axios)
|
||||
[](https://www.codetriage.com/axios/axios)
|
||||
|
||||
Promise based HTTP client for the browser and node.js
|
||||
|
||||
## Features
|
||||
|
||||
- Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser
|
||||
- Make [http](http://nodejs.org/api/http.html) requests from node.js
|
||||
- Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API
|
||||
- Intercept request and response
|
||||
- Transform request and response data
|
||||
- Cancel requests
|
||||
- Automatic transforms for JSON data
|
||||
- Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
|
||||
|
||||
## Browser Support
|
||||
|
||||
 |  |  |  |  |  |
|
||||
--- | --- | --- | --- | --- | --- |
|
||||
Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ |
|
||||
|
||||
[](https://saucelabs.com/u/axios)
|
||||
|
||||
## Installing
|
||||
|
||||
Using npm:
|
||||
|
||||
```bash
|
||||
$ npm install axios
|
||||
```
|
||||
|
||||
Using bower:
|
||||
|
||||
```bash
|
||||
$ bower install axios
|
||||
```
|
||||
|
||||
Using yarn:
|
||||
|
||||
```bash
|
||||
$ yarn add axios
|
||||
```
|
||||
|
||||
Using cdn:
|
||||
|
||||
```html
|
||||
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
### note: CommonJS usage
|
||||
In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach:
|
||||
|
||||
```js
|
||||
const axios = require('axios').default;
|
||||
|
||||
// axios.<method> will now provide autocomplete and parameter typings
|
||||
```
|
||||
|
||||
Performing a `GET` request
|
||||
|
||||
```js
|
||||
const axios = require('axios');
|
||||
|
||||
// Make a request for a user with a given ID
|
||||
axios.get('/user?ID=12345')
|
||||
.then(function (response) {
|
||||
// handle success
|
||||
console.log(response);
|
||||
})
|
||||
.catch(function (error) {
|
||||
// handle error
|
||||
console.log(error);
|
||||
})
|
||||
.finally(function () {
|
||||
// always executed
|
||||
});
|
||||
|
||||
// Optionally the request above could also be done as
|
||||
axios.get('/user', {
|
||||
params: {
|
||||
ID: 12345
|
||||
}
|
||||
})
|
||||
.then(function (response) {
|
||||
console.log(response);
|
||||
})
|
||||
.catch(function (error) {
|
||||
console.log(error);
|
||||
})
|
||||
.finally(function () {
|
||||
// always executed
|
||||
});
|
||||
|
||||
// Want to use async/await? Add the `async` keyword to your outer function/method.
|
||||
async function getUser() {
|
||||
try {
|
||||
const response = await axios.get('/user?ID=12345');
|
||||
console.log(response);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet
|
||||
> Explorer and older browsers, so use with caution.
|
||||
|
||||
Performing a `POST` request
|
||||
|
||||
```js
|
||||
axios.post('/user', {
|
||||
firstName: 'Fred',
|
||||
lastName: 'Flintstone'
|
||||
})
|
||||
.then(function (response) {
|
||||
console.log(response);
|
||||
})
|
||||
.catch(function (error) {
|
||||
console.log(error);
|
||||
});
|
||||
```
|
||||
|
||||
Performing multiple concurrent requests
|
||||
|
||||
```js
|
||||
function getUserAccount() {
|
||||
return axios.get('/user/12345');
|
||||
}
|
||||
|
||||
function getUserPermissions() {
|
||||
return axios.get('/user/12345/permissions');
|
||||
}
|
||||
|
||||
axios.all([getUserAccount(), getUserPermissions()])
|
||||
.then(axios.spread(function (acct, perms) {
|
||||
// Both requests are now complete
|
||||
}));
|
||||
```
|
||||
|
||||
## axios API
|
||||
|
||||
Requests can be made by passing the relevant config to `axios`.
|
||||
|
||||
##### axios(config)
|
||||
|
||||
```js
|
||||
// Send a POST request
|
||||
axios({
|
||||
method: 'post',
|
||||
url: '/user/12345',
|
||||
data: {
|
||||
firstName: 'Fred',
|
||||
lastName: 'Flintstone'
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
```js
|
||||
// GET request for remote image
|
||||
axios({
|
||||
method: 'get',
|
||||
url: 'http://bit.ly/2mTM3nY',
|
||||
responseType: 'stream'
|
||||
})
|
||||
.then(function (response) {
|
||||
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
|
||||
});
|
||||
```
|
||||
|
||||
##### axios(url[, config])
|
||||
|
||||
```js
|
||||
// Send a GET request (default method)
|
||||
axios('/user/12345');
|
||||
```
|
||||
|
||||
### Request method aliases
|
||||
|
||||
For convenience aliases have been provided for all supported request methods.
|
||||
|
||||
##### axios.request(config)
|
||||
##### axios.get(url[, config])
|
||||
##### axios.delete(url[, config])
|
||||
##### axios.head(url[, config])
|
||||
##### axios.options(url[, config])
|
||||
##### axios.post(url[, data[, config]])
|
||||
##### axios.put(url[, data[, config]])
|
||||
##### axios.patch(url[, data[, config]])
|
||||
|
||||
###### NOTE
|
||||
When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.
|
||||
|
||||
### Concurrency
|
||||
|
||||
Helper functions for dealing with concurrent requests.
|
||||
|
||||
##### axios.all(iterable)
|
||||
##### axios.spread(callback)
|
||||
|
||||
### Creating an instance
|
||||
|
||||
You can create a new instance of axios with a custom config.
|
||||
|
||||
##### axios.create([config])
|
||||
|
||||
```js
|
||||
const instance = axios.create({
|
||||
baseURL: 'https://some-domain.com/api/',
|
||||
timeout: 1000,
|
||||
headers: {'X-Custom-Header': 'foobar'}
|
||||
});
|
||||
```
|
||||
|
||||
### Instance methods
|
||||
|
||||
The available instance methods are listed below. The specified config will be merged with the instance config.
|
||||
|
||||
##### axios#request(config)
|
||||
##### axios#get(url[, config])
|
||||
##### axios#delete(url[, config])
|
||||
##### axios#head(url[, config])
|
||||
##### axios#options(url[, config])
|
||||
##### axios#post(url[, data[, config]])
|
||||
##### axios#put(url[, data[, config]])
|
||||
##### axios#patch(url[, data[, config]])
|
||||
##### axios#getUri([config])
|
||||
|
||||
## Request Config
|
||||
|
||||
These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.
|
||||
|
||||
```js
|
||||
{
|
||||
// `url` is the server URL that will be used for the request
|
||||
url: '/user',
|
||||
|
||||
// `method` is the request method to be used when making the request
|
||||
method: 'get', // default
|
||||
|
||||
// `baseURL` will be prepended to `url` unless `url` is absolute.
|
||||
// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
|
||||
// to methods of that instance.
|
||||
baseURL: 'https://some-domain.com/api/',
|
||||
|
||||
// `transformRequest` allows changes to the request data before it is sent to the server
|
||||
// This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
|
||||
// The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
|
||||
// FormData or Stream
|
||||
// You may modify the headers object.
|
||||
transformRequest: [function (data, headers) {
|
||||
// Do whatever you want to transform the data
|
||||
|
||||
return data;
|
||||
}],
|
||||
|
||||
// `transformResponse` allows changes to the response data to be made before
|
||||
// it is passed to then/catch
|
||||
transformResponse: [function (data) {
|
||||
// Do whatever you want to transform the data
|
||||
|
||||
return data;
|
||||
}],
|
||||
|
||||
// `headers` are custom headers to be sent
|
||||
headers: {'X-Requested-With': 'XMLHttpRequest'},
|
||||
|
||||
// `params` are the URL parameters to be sent with the request
|
||||
// Must be a plain object or a URLSearchParams object
|
||||
params: {
|
||||
ID: 12345
|
||||
},
|
||||
|
||||
// `paramsSerializer` is an optional function in charge of serializing `params`
|
||||
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
|
||||
paramsSerializer: function (params) {
|
||||
return Qs.stringify(params, {arrayFormat: 'brackets'})
|
||||
},
|
||||
|
||||
// `data` is the data to be sent as the request body
|
||||
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
|
||||
// When no `transformRequest` is set, must be of one of the following types:
|
||||
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
|
||||
// - Browser only: FormData, File, Blob
|
||||
// - Node only: Stream, Buffer
|
||||
data: {
|
||||
firstName: 'Fred'
|
||||
},
|
||||
|
||||
// syntax alternative to send data into the body
|
||||
// method post
|
||||
// only the value is sent, not the key
|
||||
data: 'Country=Brasil&City=Belo Horizonte',
|
||||
|
||||
// `timeout` specifies the number of milliseconds before the request times out.
|
||||
// If the request takes longer than `timeout`, the request will be aborted.
|
||||
timeout: 1000, // default is `0` (no timeout)
|
||||
|
||||
// `withCredentials` indicates whether or not cross-site Access-Control requests
|
||||
// should be made using credentials
|
||||
withCredentials: false, // default
|
||||
|
||||
// `adapter` allows custom handling of requests which makes testing easier.
|
||||
// Return a promise and supply a valid response (see lib/adapters/README.md).
|
||||
adapter: function (config) {
|
||||
/* ... */
|
||||
},
|
||||
|
||||
// `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
|
||||
// This will set an `Authorization` header, overwriting any existing
|
||||
// `Authorization` custom headers you have set using `headers`.
|
||||
// Please note that only HTTP Basic auth is configurable through this parameter.
|
||||
// For Bearer tokens and such, use `Authorization` custom headers instead.
|
||||
auth: {
|
||||
username: 'janedoe',
|
||||
password: 's00pers3cret'
|
||||
},
|
||||
|
||||
// `responseType` indicates the type of data that the server will respond with
|
||||
// options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
|
||||
// browser only: 'blob'
|
||||
responseType: 'json', // default
|
||||
|
||||
// `responseEncoding` indicates encoding to use for decoding responses
|
||||
// Note: Ignored for `responseType` of 'stream' or client-side requests
|
||||
responseEncoding: 'utf8', // default
|
||||
|
||||
// `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
|
||||
xsrfCookieName: 'XSRF-TOKEN', // default
|
||||
|
||||
// `xsrfHeaderName` is the name of the http header that carries the xsrf token value
|
||||
xsrfHeaderName: 'X-XSRF-TOKEN', // default
|
||||
|
||||
// `onUploadProgress` allows handling of progress events for uploads
|
||||
onUploadProgress: function (progressEvent) {
|
||||
// Do whatever you want with the native progress event
|
||||
},
|
||||
|
||||
// `onDownloadProgress` allows handling of progress events for downloads
|
||||
onDownloadProgress: function (progressEvent) {
|
||||
// Do whatever you want with the native progress event
|
||||
},
|
||||
|
||||
// `maxContentLength` defines the max size of the http response content in bytes allowed
|
||||
maxContentLength: 2000,
|
||||
|
||||
// `validateStatus` defines whether to resolve or reject the promise for a given
|
||||
// HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
|
||||
// or `undefined`), the promise will be resolved; otherwise, the promise will be
|
||||
// rejected.
|
||||
validateStatus: function (status) {
|
||||
return status >= 200 && status < 300; // default
|
||||
},
|
||||
|
||||
// `maxRedirects` defines the maximum number of redirects to follow in node.js.
|
||||
// If set to 0, no redirects will be followed.
|
||||
maxRedirects: 5, // default
|
||||
|
||||
// `socketPath` defines a UNIX Socket to be used in node.js.
|
||||
// e.g. '/var/run/docker.sock' to send requests to the docker daemon.
|
||||
// Only either `socketPath` or `proxy` can be specified.
|
||||
// If both are specified, `socketPath` is used.
|
||||
socketPath: null, // default
|
||||
|
||||
// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
|
||||
// and https requests, respectively, in node.js. This allows options to be added like
|
||||
// `keepAlive` that are not enabled by default.
|
||||
httpAgent: new http.Agent({ keepAlive: true }),
|
||||
httpsAgent: new https.Agent({ keepAlive: true }),
|
||||
|
||||
// 'proxy' defines the hostname and port of the proxy server.
|
||||
// You can also define your proxy using the conventional `http_proxy` and
|
||||
// `https_proxy` environment variables. If you are using environment variables
|
||||
// for your proxy configuration, you can also define a `no_proxy` environment
|
||||
// variable as a comma-separated list of domains that should not be proxied.
|
||||
// Use `false` to disable proxies, ignoring environment variables.
|
||||
// `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
|
||||
// supplies credentials.
|
||||
// This will set an `Proxy-Authorization` header, overwriting any existing
|
||||
// `Proxy-Authorization` custom headers you have set using `headers`.
|
||||
proxy: {
|
||||
host: '127.0.0.1',
|
||||
port: 9000,
|
||||
auth: {
|
||||
username: 'mikeymike',
|
||||
password: 'rapunz3l'
|
||||
}
|
||||
},
|
||||
|
||||
// `cancelToken` specifies a cancel token that can be used to cancel the request
|
||||
// (see Cancellation section below for details)
|
||||
cancelToken: new CancelToken(function (cancel) {
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## Response Schema
|
||||
|
||||
The response for a request contains the following information.
|
||||
|
||||
```js
|
||||
{
|
||||
// `data` is the response that was provided by the server
|
||||
data: {},
|
||||
|
||||
// `status` is the HTTP status code from the server response
|
||||
status: 200,
|
||||
|
||||
// `statusText` is the HTTP status message from the server response
|
||||
statusText: 'OK',
|
||||
|
||||
// `headers` the headers that the server responded with
|
||||
// All header names are lower cased
|
||||
headers: {},
|
||||
|
||||
// `config` is the config that was provided to `axios` for the request
|
||||
config: {},
|
||||
|
||||
// `request` is the request that generated this response
|
||||
// It is the last ClientRequest instance in node.js (in redirects)
|
||||
// and an XMLHttpRequest instance in the browser
|
||||
request: {}
|
||||
}
|
||||
```
|
||||
|
||||
When using `then`, you will receive the response as follows:
|
||||
|
||||
```js
|
||||
axios.get('/user/12345')
|
||||
.then(function (response) {
|
||||
console.log(response.data);
|
||||
console.log(response.status);
|
||||
console.log(response.statusText);
|
||||
console.log(response.headers);
|
||||
console.log(response.config);
|
||||
});
|
||||
```
|
||||
|
||||
When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](#handling-errors) section.
|
||||
|
||||
## Config Defaults
|
||||
|
||||
You can specify config defaults that will be applied to every request.
|
||||
|
||||
### Global axios defaults
|
||||
|
||||
```js
|
||||
axios.defaults.baseURL = 'https://api.example.com';
|
||||
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
|
||||
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
|
||||
```
|
||||
|
||||
### Custom instance defaults
|
||||
|
||||
```js
|
||||
// Set config defaults when creating the instance
|
||||
const instance = axios.create({
|
||||
baseURL: 'https://api.example.com'
|
||||
});
|
||||
|
||||
// Alter defaults after instance has been created
|
||||
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
|
||||
```
|
||||
|
||||
### Config order of precedence
|
||||
|
||||
Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example.
|
||||
|
||||
```js
|
||||
// Create an instance using the config defaults provided by the library
|
||||
// At this point the timeout config value is `0` as is the default for the library
|
||||
const instance = axios.create();
|
||||
|
||||
// Override timeout default for the library
|
||||
// Now all requests using this instance will wait 2.5 seconds before timing out
|
||||
instance.defaults.timeout = 2500;
|
||||
|
||||
// Override timeout for this request as it's known to take a long time
|
||||
instance.get('/longRequest', {
|
||||
timeout: 5000
|
||||
});
|
||||
```
|
||||
|
||||
## Interceptors
|
||||
|
||||
You can intercept requests or responses before they are handled by `then` or `catch`.
|
||||
|
||||
```js
|
||||
// Add a request interceptor
|
||||
axios.interceptors.request.use(function (config) {
|
||||
// Do something before request is sent
|
||||
return config;
|
||||
}, function (error) {
|
||||
// Do something with request error
|
||||
return Promise.reject(error);
|
||||
});
|
||||
|
||||
// Add a response interceptor
|
||||
axios.interceptors.response.use(function (response) {
|
||||
// Any status code that lie within the range of 2xx cause this function to trigger
|
||||
// Do something with response data
|
||||
return response;
|
||||
}, function (error) {
|
||||
// Any status codes that falls outside the range of 2xx cause this function to trigger
|
||||
// Do something with response error
|
||||
return Promise.reject(error);
|
||||
});
|
||||
```
|
||||
|
||||
If you need to remove an interceptor later you can.
|
||||
|
||||
```js
|
||||
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
|
||||
axios.interceptors.request.eject(myInterceptor);
|
||||
```
|
||||
|
||||
You can add interceptors to a custom instance of axios.
|
||||
|
||||
```js
|
||||
const instance = axios.create();
|
||||
instance.interceptors.request.use(function () {/*...*/});
|
||||
```
|
||||
|
||||
## Handling Errors
|
||||
|
||||
```js
|
||||
axios.get('/user/12345')
|
||||
.catch(function (error) {
|
||||
if (error.response) {
|
||||
// The request was made and the server responded with a status code
|
||||
// that falls out of the range of 2xx
|
||||
console.log(error.response.data);
|
||||
console.log(error.response.status);
|
||||
console.log(error.response.headers);
|
||||
} else if (error.request) {
|
||||
// The request was made but no response was received
|
||||
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
|
||||
// http.ClientRequest in node.js
|
||||
console.log(error.request);
|
||||
} else {
|
||||
// Something happened in setting up the request that triggered an Error
|
||||
console.log('Error', error.message);
|
||||
}
|
||||
console.log(error.config);
|
||||
});
|
||||
```
|
||||
|
||||
Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error.
|
||||
|
||||
```js
|
||||
axios.get('/user/12345', {
|
||||
validateStatus: function (status) {
|
||||
return status < 500; // Reject only if the status code is greater than or equal to 500
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
Using `toJSON` you get an object with more information about the HTTP error.
|
||||
|
||||
```js
|
||||
axios.get('/user/12345')
|
||||
.catch(function (error) {
|
||||
console.log(error.toJSON());
|
||||
});
|
||||
```
|
||||
|
||||
## Cancellation
|
||||
|
||||
You can cancel a request using a *cancel token*.
|
||||
|
||||
> The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises).
|
||||
|
||||
You can create a cancel token using the `CancelToken.source` factory as shown below:
|
||||
|
||||
```js
|
||||
const CancelToken = axios.CancelToken;
|
||||
const source = CancelToken.source();
|
||||
|
||||
axios.get('/user/12345', {
|
||||
cancelToken: source.token
|
||||
}).catch(function (thrown) {
|
||||
if (axios.isCancel(thrown)) {
|
||||
console.log('Request canceled', thrown.message);
|
||||
} else {
|
||||
// handle error
|
||||
}
|
||||
});
|
||||
|
||||
axios.post('/user/12345', {
|
||||
name: 'new name'
|
||||
}, {
|
||||
cancelToken: source.token
|
||||
})
|
||||
|
||||
// cancel the request (the message parameter is optional)
|
||||
source.cancel('Operation canceled by the user.');
|
||||
```
|
||||
|
||||
You can also create a cancel token by passing an executor function to the `CancelToken` constructor:
|
||||
|
||||
```js
|
||||
const CancelToken = axios.CancelToken;
|
||||
let cancel;
|
||||
|
||||
axios.get('/user/12345', {
|
||||
cancelToken: new CancelToken(function executor(c) {
|
||||
// An executor function receives a cancel function as a parameter
|
||||
cancel = c;
|
||||
})
|
||||
});
|
||||
|
||||
// cancel the request
|
||||
cancel();
|
||||
```
|
||||
|
||||
> Note: you can cancel several requests with the same cancel token.
|
||||
|
||||
## Using application/x-www-form-urlencoded format
|
||||
|
||||
By default, axios serializes JavaScript objects to `JSON`. To send data in the `application/x-www-form-urlencoded` format instead, you can use one of the following options.
|
||||
|
||||
### Browser
|
||||
|
||||
In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows:
|
||||
|
||||
```js
|
||||
const params = new URLSearchParams();
|
||||
params.append('param1', 'value1');
|
||||
params.append('param2', 'value2');
|
||||
axios.post('/foo', params);
|
||||
```
|
||||
|
||||
> Note that `URLSearchParams` is not supported by all browsers (see [caniuse.com](http://www.caniuse.com/#feat=urlsearchparams)), but there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment).
|
||||
|
||||
Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library:
|
||||
|
||||
```js
|
||||
const qs = require('qs');
|
||||
axios.post('/foo', qs.stringify({ 'bar': 123 }));
|
||||
```
|
||||
|
||||
Or in another way (ES6),
|
||||
|
||||
```js
|
||||
import qs from 'qs';
|
||||
const data = { 'bar': 123 };
|
||||
const options = {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
data: qs.stringify(data),
|
||||
url,
|
||||
};
|
||||
axios(options);
|
||||
```
|
||||
|
||||
### Node.js
|
||||
|
||||
In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:
|
||||
|
||||
```js
|
||||
const querystring = require('querystring');
|
||||
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
|
||||
```
|
||||
|
||||
You can also use the [`qs`](https://github.com/ljharb/qs) library.
|
||||
|
||||
###### NOTE
|
||||
The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665).
|
||||
|
||||
## Semver
|
||||
|
||||
Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes.
|
||||
|
||||
## Promises
|
||||
|
||||
axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises).
|
||||
If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise).
|
||||
|
||||
## TypeScript
|
||||
axios includes [TypeScript](http://typescriptlang.org) definitions.
|
||||
```typescript
|
||||
import axios from 'axios';
|
||||
axios.get('/user?ID=12345');
|
||||
```
|
||||
|
||||
## Resources
|
||||
|
||||
* [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md)
|
||||
* [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md)
|
||||
* [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md)
|
||||
* [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md)
|
||||
* [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md)
|
||||
|
||||
## Credits
|
||||
|
||||
axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [Angular](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of Angular.
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
-162
@@ -1,162 +0,0 @@
|
||||
# Upgrade Guide
|
||||
|
||||
### 0.15.x -> 0.16.0
|
||||
|
||||
#### `Promise` Type Declarations
|
||||
|
||||
The `Promise` type declarations have been removed from the axios typings in favor of the built-in type declarations. If you use axios in a TypeScript project that targets `ES5`, please make sure to include the `es2015.promise` lib. Please see [this post](https://blog.mariusschulz.com/2016/11/25/typescript-2-0-built-in-type-declarations) for details.
|
||||
|
||||
### 0.13.x -> 0.14.0
|
||||
|
||||
#### TypeScript Definitions
|
||||
|
||||
The axios TypeScript definitions have been updated to match the axios API and use the ES2015 module syntax.
|
||||
|
||||
Please use the following `import` statement to import axios in TypeScript:
|
||||
|
||||
```typescript
|
||||
import axios from 'axios';
|
||||
|
||||
axios.get('/foo')
|
||||
.then(response => console.log(response))
|
||||
.catch(error => console.log(error));
|
||||
```
|
||||
|
||||
#### `agent` Config Option
|
||||
|
||||
The `agent` config option has been replaced with two new options: `httpAgent` and `httpsAgent`. Please use them instead.
|
||||
|
||||
```js
|
||||
{
|
||||
// Define a custom agent for HTTP
|
||||
httpAgent: new http.Agent({ keepAlive: true }),
|
||||
// Define a custom agent for HTTPS
|
||||
httpsAgent: new https.Agent({ keepAlive: true })
|
||||
}
|
||||
```
|
||||
|
||||
#### `progress` Config Option
|
||||
|
||||
The `progress` config option has been replaced with the `onUploadProgress` and `onDownloadProgress` options.
|
||||
|
||||
```js
|
||||
{
|
||||
// Define a handler for upload progress events
|
||||
onUploadProgress: function (progressEvent) {
|
||||
// ...
|
||||
},
|
||||
|
||||
// Define a handler for download progress events
|
||||
onDownloadProgress: function (progressEvent) {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 0.12.x -> 0.13.0
|
||||
|
||||
The `0.13.0` release contains several changes to custom adapters and error handling.
|
||||
|
||||
#### Error Handling
|
||||
|
||||
Previous to this release an error could either be a server response with bad status code or an actual `Error`. With this release Promise will always reject with an `Error`. In the case that a response was received, the `Error` will also include the response.
|
||||
|
||||
```js
|
||||
axios.get('/user/12345')
|
||||
.catch((error) => {
|
||||
console.log(error.message);
|
||||
console.log(error.code); // Not always specified
|
||||
console.log(error.config); // The config that was used to make the request
|
||||
console.log(error.response); // Only available if response was received from the server
|
||||
});
|
||||
```
|
||||
|
||||
#### Request Adapters
|
||||
|
||||
This release changes a few things about how request adapters work. Please take note if you are using your own custom adapter.
|
||||
|
||||
1. Response transformer is now called outside of adapter.
|
||||
2. Request adapter returns a `Promise`.
|
||||
|
||||
This means that you no longer need to invoke `transformData` on response data. You will also no longer receive `resolve` and `reject` as arguments in your adapter.
|
||||
|
||||
Previous code:
|
||||
|
||||
```js
|
||||
function myAdapter(resolve, reject, config) {
|
||||
var response = {
|
||||
data: transformData(
|
||||
responseData,
|
||||
responseHeaders,
|
||||
config.transformResponse
|
||||
),
|
||||
status: request.status,
|
||||
statusText: request.statusText,
|
||||
headers: responseHeaders
|
||||
};
|
||||
settle(resolve, reject, response);
|
||||
}
|
||||
```
|
||||
|
||||
New code:
|
||||
|
||||
```js
|
||||
function myAdapter(config) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
var response = {
|
||||
data: responseData,
|
||||
status: request.status,
|
||||
statusText: request.statusText,
|
||||
headers: responseHeaders
|
||||
};
|
||||
settle(resolve, reject, response);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
See the related commits for more details:
|
||||
- [Response transformers](https://github.com/axios/axios/commit/10eb23865101f9347570552c04e9d6211376e25e)
|
||||
- [Request adapter Promise](https://github.com/axios/axios/commit/157efd5615890301824e3121cc6c9d2f9b21f94a)
|
||||
|
||||
### 0.5.x -> 0.6.0
|
||||
|
||||
The `0.6.0` release contains mostly bug fixes, but there are a couple things to be aware of when upgrading.
|
||||
|
||||
#### ES6 Promise Polyfill
|
||||
|
||||
Up until the `0.6.0` release ES6 `Promise` was being polyfilled using [es6-promise](https://github.com/jakearchibald/es6-promise). With this release, the polyfill has been removed, and you will need to supply it yourself if your environment needs it.
|
||||
|
||||
```js
|
||||
require('es6-promise').polyfill();
|
||||
var axios = require('axios');
|
||||
```
|
||||
|
||||
This will polyfill the global environment, and only needs to be done once.
|
||||
|
||||
#### `axios.success`/`axios.error`
|
||||
|
||||
The `success`, and `error` aliases were deprectated in [0.4.0](https://github.com/axios/axios/blob/master/CHANGELOG.md#040-oct-03-2014). As of this release they have been removed entirely. Instead please use `axios.then`, and `axios.catch` respectively.
|
||||
|
||||
```js
|
||||
axios.get('some/url')
|
||||
.then(function (res) {
|
||||
/* ... */
|
||||
})
|
||||
.catch(function (err) {
|
||||
/* ... */
|
||||
});
|
||||
```
|
||||
|
||||
#### UMD
|
||||
|
||||
Previous versions of axios shipped with an AMD, CommonJS, and Global build. This has all been rolled into a single UMD build.
|
||||
|
||||
```js
|
||||
// AMD
|
||||
require(['bower_components/axios/dist/axios'], function (axios) {
|
||||
/* ... */
|
||||
});
|
||||
|
||||
// CommonJS
|
||||
var axios = require('axios/dist/axios');
|
||||
```
|
||||
-1715
File diff suppressed because it is too large
Load Diff
-1
File diff suppressed because one or more lines are too long
-3
File diff suppressed because one or more lines are too long
-1
File diff suppressed because one or more lines are too long
-157
@@ -1,157 +0,0 @@
|
||||
export interface AxiosTransformer {
|
||||
(data: any, headers?: any): any;
|
||||
}
|
||||
|
||||
export interface AxiosAdapter {
|
||||
(config: AxiosRequestConfig): AxiosPromise<any>;
|
||||
}
|
||||
|
||||
export interface AxiosBasicCredentials {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface AxiosProxyConfig {
|
||||
host: string;
|
||||
port: number;
|
||||
auth?: {
|
||||
username: string;
|
||||
password:string;
|
||||
};
|
||||
protocol?: string;
|
||||
}
|
||||
|
||||
export type Method =
|
||||
| 'get' | 'GET'
|
||||
| 'delete' | 'DELETE'
|
||||
| 'head' | 'HEAD'
|
||||
| 'options' | 'OPTIONS'
|
||||
| 'post' | 'POST'
|
||||
| 'put' | 'PUT'
|
||||
| 'patch' | 'PATCH'
|
||||
| 'link' | 'LINK'
|
||||
| 'unlink' | 'UNLINK'
|
||||
|
||||
export type ResponseType =
|
||||
| 'arraybuffer'
|
||||
| 'blob'
|
||||
| 'document'
|
||||
| 'json'
|
||||
| 'text'
|
||||
| 'stream'
|
||||
|
||||
export interface AxiosRequestConfig {
|
||||
url?: string;
|
||||
method?: Method;
|
||||
baseURL?: string;
|
||||
transformRequest?: AxiosTransformer | AxiosTransformer[];
|
||||
transformResponse?: AxiosTransformer | AxiosTransformer[];
|
||||
headers?: any;
|
||||
params?: any;
|
||||
paramsSerializer?: (params: any) => string;
|
||||
data?: any;
|
||||
timeout?: number;
|
||||
timeoutErrorMessage?: string;
|
||||
withCredentials?: boolean;
|
||||
adapter?: AxiosAdapter;
|
||||
auth?: AxiosBasicCredentials;
|
||||
responseType?: ResponseType;
|
||||
xsrfCookieName?: string;
|
||||
xsrfHeaderName?: string;
|
||||
onUploadProgress?: (progressEvent: any) => void;
|
||||
onDownloadProgress?: (progressEvent: any) => void;
|
||||
maxContentLength?: number;
|
||||
validateStatus?: (status: number) => boolean;
|
||||
maxRedirects?: number;
|
||||
socketPath?: string | null;
|
||||
httpAgent?: any;
|
||||
httpsAgent?: any;
|
||||
proxy?: AxiosProxyConfig | false;
|
||||
cancelToken?: CancelToken;
|
||||
}
|
||||
|
||||
export interface AxiosResponse<T = any> {
|
||||
data: T;
|
||||
status: number;
|
||||
statusText: string;
|
||||
headers: any;
|
||||
config: AxiosRequestConfig;
|
||||
request?: any;
|
||||
}
|
||||
|
||||
export interface AxiosError<T = any> extends Error {
|
||||
config: AxiosRequestConfig;
|
||||
code?: string;
|
||||
request?: any;
|
||||
response?: AxiosResponse<T>;
|
||||
isAxiosError: boolean;
|
||||
toJSON: () => object;
|
||||
}
|
||||
|
||||
export interface AxiosPromise<T = any> extends Promise<AxiosResponse<T>> {
|
||||
}
|
||||
|
||||
export interface CancelStatic {
|
||||
new (message?: string): Cancel;
|
||||
}
|
||||
|
||||
export interface Cancel {
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface Canceler {
|
||||
(message?: string): void;
|
||||
}
|
||||
|
||||
export interface CancelTokenStatic {
|
||||
new (executor: (cancel: Canceler) => void): CancelToken;
|
||||
source(): CancelTokenSource;
|
||||
}
|
||||
|
||||
export interface CancelToken {
|
||||
promise: Promise<Cancel>;
|
||||
reason?: Cancel;
|
||||
throwIfRequested(): void;
|
||||
}
|
||||
|
||||
export interface CancelTokenSource {
|
||||
token: CancelToken;
|
||||
cancel: Canceler;
|
||||
}
|
||||
|
||||
export interface AxiosInterceptorManager<V> {
|
||||
use(onFulfilled?: (value: V) => V | Promise<V>, onRejected?: (error: any) => any): number;
|
||||
eject(id: number): void;
|
||||
}
|
||||
|
||||
export interface AxiosInstance {
|
||||
(config: AxiosRequestConfig): AxiosPromise;
|
||||
(url: string, config?: AxiosRequestConfig): AxiosPromise;
|
||||
defaults: AxiosRequestConfig;
|
||||
interceptors: {
|
||||
request: AxiosInterceptorManager<AxiosRequestConfig>;
|
||||
response: AxiosInterceptorManager<AxiosResponse>;
|
||||
};
|
||||
getUri(config?: AxiosRequestConfig): string;
|
||||
request<T = any, R = AxiosResponse<T>> (config: AxiosRequestConfig): Promise<R>;
|
||||
get<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
|
||||
delete<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
|
||||
head<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
|
||||
options<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
|
||||
post<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
|
||||
put<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
|
||||
patch<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
|
||||
}
|
||||
|
||||
export interface AxiosStatic extends AxiosInstance {
|
||||
create(config?: AxiosRequestConfig): AxiosInstance;
|
||||
Cancel: CancelStatic;
|
||||
CancelToken: CancelTokenStatic;
|
||||
isCancel(value: any): boolean;
|
||||
all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
|
||||
spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
|
||||
}
|
||||
|
||||
declare const Axios: AxiosStatic;
|
||||
|
||||
export default Axios;
|
||||
-1
@@ -1 +0,0 @@
|
||||
module.exports = require('./lib/axios');
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
# axios // adapters
|
||||
|
||||
The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received.
|
||||
|
||||
## Example
|
||||
|
||||
```js
|
||||
var settle = require('./../core/settle');
|
||||
|
||||
module.exports = function myAdapter(config) {
|
||||
// At this point:
|
||||
// - config has been merged with defaults
|
||||
// - request transformers have already run
|
||||
// - request interceptors have already run
|
||||
|
||||
// Make the request using config provided
|
||||
// Upon response settle the Promise
|
||||
|
||||
return new Promise(function(resolve, reject) {
|
||||
|
||||
var response = {
|
||||
data: responseData,
|
||||
status: request.status,
|
||||
statusText: request.statusText,
|
||||
headers: responseHeaders,
|
||||
config: config,
|
||||
request: request
|
||||
};
|
||||
|
||||
settle(resolve, reject, response);
|
||||
|
||||
// From here:
|
||||
// - response transformers will run
|
||||
// - response interceptors will run
|
||||
});
|
||||
}
|
||||
```
|
||||
-279
@@ -1,279 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
var settle = require('./../core/settle');
|
||||
var buildFullPath = require('../core/buildFullPath');
|
||||
var buildURL = require('./../helpers/buildURL');
|
||||
var http = require('http');
|
||||
var https = require('https');
|
||||
var httpFollow = require('follow-redirects').http;
|
||||
var httpsFollow = require('follow-redirects').https;
|
||||
var url = require('url');
|
||||
var zlib = require('zlib');
|
||||
var pkg = require('./../../package.json');
|
||||
var createError = require('../core/createError');
|
||||
var enhanceError = require('../core/enhanceError');
|
||||
|
||||
var isHttps = /https:?/;
|
||||
|
||||
/*eslint consistent-return:0*/
|
||||
module.exports = function httpAdapter(config) {
|
||||
return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) {
|
||||
var resolve = function resolve(value) {
|
||||
resolvePromise(value);
|
||||
};
|
||||
var reject = function reject(value) {
|
||||
rejectPromise(value);
|
||||
};
|
||||
var data = config.data;
|
||||
var headers = config.headers;
|
||||
|
||||
// Set User-Agent (required by some servers)
|
||||
// Only set header if it hasn't been set in config
|
||||
// See https://github.com/axios/axios/issues/69
|
||||
if (!headers['User-Agent'] && !headers['user-agent']) {
|
||||
headers['User-Agent'] = 'axios/' + pkg.version;
|
||||
}
|
||||
|
||||
if (data && !utils.isStream(data)) {
|
||||
if (Buffer.isBuffer(data)) {
|
||||
// Nothing to do...
|
||||
} else if (utils.isArrayBuffer(data)) {
|
||||
data = Buffer.from(new Uint8Array(data));
|
||||
} else if (utils.isString(data)) {
|
||||
data = Buffer.from(data, 'utf-8');
|
||||
} else {
|
||||
return reject(createError(
|
||||
'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',
|
||||
config
|
||||
));
|
||||
}
|
||||
|
||||
// Add Content-Length header if data exists
|
||||
headers['Content-Length'] = data.length;
|
||||
}
|
||||
|
||||
// HTTP basic authentication
|
||||
var auth = undefined;
|
||||
if (config.auth) {
|
||||
var username = config.auth.username || '';
|
||||
var password = config.auth.password || '';
|
||||
auth = username + ':' + password;
|
||||
}
|
||||
|
||||
// Parse url
|
||||
var fullPath = buildFullPath(config.baseURL, config.url);
|
||||
var parsed = url.parse(fullPath);
|
||||
var protocol = parsed.protocol || 'http:';
|
||||
|
||||
if (!auth && parsed.auth) {
|
||||
var urlAuth = parsed.auth.split(':');
|
||||
var urlUsername = urlAuth[0] || '';
|
||||
var urlPassword = urlAuth[1] || '';
|
||||
auth = urlUsername + ':' + urlPassword;
|
||||
}
|
||||
|
||||
if (auth) {
|
||||
delete headers.Authorization;
|
||||
}
|
||||
|
||||
var isHttpsRequest = isHttps.test(protocol);
|
||||
var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
|
||||
|
||||
var options = {
|
||||
path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''),
|
||||
method: config.method.toUpperCase(),
|
||||
headers: headers,
|
||||
agent: agent,
|
||||
agents: { http: config.httpAgent, https: config.httpsAgent },
|
||||
auth: auth
|
||||
};
|
||||
|
||||
if (config.socketPath) {
|
||||
options.socketPath = config.socketPath;
|
||||
} else {
|
||||
options.hostname = parsed.hostname;
|
||||
options.port = parsed.port;
|
||||
}
|
||||
|
||||
var proxy = config.proxy;
|
||||
if (!proxy && proxy !== false) {
|
||||
var proxyEnv = protocol.slice(0, -1) + '_proxy';
|
||||
var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()];
|
||||
if (proxyUrl) {
|
||||
var parsedProxyUrl = url.parse(proxyUrl);
|
||||
var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY;
|
||||
var shouldProxy = true;
|
||||
|
||||
if (noProxyEnv) {
|
||||
var noProxy = noProxyEnv.split(',').map(function trim(s) {
|
||||
return s.trim();
|
||||
});
|
||||
|
||||
shouldProxy = !noProxy.some(function proxyMatch(proxyElement) {
|
||||
if (!proxyElement) {
|
||||
return false;
|
||||
}
|
||||
if (proxyElement === '*') {
|
||||
return true;
|
||||
}
|
||||
if (proxyElement[0] === '.' &&
|
||||
parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return parsed.hostname === proxyElement;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
if (shouldProxy) {
|
||||
proxy = {
|
||||
host: parsedProxyUrl.hostname,
|
||||
port: parsedProxyUrl.port
|
||||
};
|
||||
|
||||
if (parsedProxyUrl.auth) {
|
||||
var proxyUrlAuth = parsedProxyUrl.auth.split(':');
|
||||
proxy.auth = {
|
||||
username: proxyUrlAuth[0],
|
||||
password: proxyUrlAuth[1]
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (proxy) {
|
||||
options.hostname = proxy.host;
|
||||
options.host = proxy.host;
|
||||
options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : '');
|
||||
options.port = proxy.port;
|
||||
options.path = protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path;
|
||||
|
||||
// Basic proxy authorization
|
||||
if (proxy.auth) {
|
||||
var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64');
|
||||
options.headers['Proxy-Authorization'] = 'Basic ' + base64;
|
||||
}
|
||||
}
|
||||
|
||||
var transport;
|
||||
var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true);
|
||||
if (config.transport) {
|
||||
transport = config.transport;
|
||||
} else if (config.maxRedirects === 0) {
|
||||
transport = isHttpsProxy ? https : http;
|
||||
} else {
|
||||
if (config.maxRedirects) {
|
||||
options.maxRedirects = config.maxRedirects;
|
||||
}
|
||||
transport = isHttpsProxy ? httpsFollow : httpFollow;
|
||||
}
|
||||
|
||||
if (config.maxContentLength && config.maxContentLength > -1) {
|
||||
options.maxBodyLength = config.maxContentLength;
|
||||
}
|
||||
|
||||
// Create the request
|
||||
var req = transport.request(options, function handleResponse(res) {
|
||||
if (req.aborted) return;
|
||||
|
||||
// uncompress the response body transparently if required
|
||||
var stream = res;
|
||||
switch (res.headers['content-encoding']) {
|
||||
/*eslint default-case:0*/
|
||||
case 'gzip':
|
||||
case 'compress':
|
||||
case 'deflate':
|
||||
// add the unzipper to the body stream processing pipeline
|
||||
stream = (res.statusCode === 204) ? stream : stream.pipe(zlib.createUnzip());
|
||||
|
||||
// remove the content-encoding in order to not confuse downstream operations
|
||||
delete res.headers['content-encoding'];
|
||||
break;
|
||||
}
|
||||
|
||||
// return the last request in case of redirects
|
||||
var lastRequest = res.req || req;
|
||||
|
||||
var response = {
|
||||
status: res.statusCode,
|
||||
statusText: res.statusMessage,
|
||||
headers: res.headers,
|
||||
config: config,
|
||||
request: lastRequest
|
||||
};
|
||||
|
||||
if (config.responseType === 'stream') {
|
||||
response.data = stream;
|
||||
settle(resolve, reject, response);
|
||||
} else {
|
||||
var responseBuffer = [];
|
||||
stream.on('data', function handleStreamData(chunk) {
|
||||
responseBuffer.push(chunk);
|
||||
|
||||
// make sure the content length is not over the maxContentLength if specified
|
||||
if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) {
|
||||
stream.destroy();
|
||||
reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
|
||||
config, null, lastRequest));
|
||||
}
|
||||
});
|
||||
|
||||
stream.on('error', function handleStreamError(err) {
|
||||
if (req.aborted) return;
|
||||
reject(enhanceError(err, config, null, lastRequest));
|
||||
});
|
||||
|
||||
stream.on('end', function handleStreamEnd() {
|
||||
var responseData = Buffer.concat(responseBuffer);
|
||||
if (config.responseType !== 'arraybuffer') {
|
||||
responseData = responseData.toString(config.responseEncoding);
|
||||
}
|
||||
|
||||
response.data = responseData;
|
||||
settle(resolve, reject, response);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Handle errors
|
||||
req.on('error', function handleRequestError(err) {
|
||||
if (req.aborted) return;
|
||||
reject(enhanceError(err, config, null, req));
|
||||
});
|
||||
|
||||
// Handle request timeout
|
||||
if (config.timeout) {
|
||||
// Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
|
||||
// And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
|
||||
// At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.
|
||||
// And then these socket which be hang up will devoring CPU little by little.
|
||||
// ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
|
||||
req.setTimeout(config.timeout, function handleRequestTimeout() {
|
||||
req.abort();
|
||||
reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', req));
|
||||
});
|
||||
}
|
||||
|
||||
if (config.cancelToken) {
|
||||
// Handle cancellation
|
||||
config.cancelToken.promise.then(function onCanceled(cancel) {
|
||||
if (req.aborted) return;
|
||||
|
||||
req.abort();
|
||||
reject(cancel);
|
||||
});
|
||||
}
|
||||
|
||||
// Send the request
|
||||
if (utils.isStream(data)) {
|
||||
data.on('error', function handleStreamError(err) {
|
||||
reject(enhanceError(err, config, null, req));
|
||||
}).pipe(req);
|
||||
} else {
|
||||
req.end(data);
|
||||
}
|
||||
});
|
||||
};
|
||||
-180
@@ -1,180 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
var settle = require('./../core/settle');
|
||||
var buildURL = require('./../helpers/buildURL');
|
||||
var buildFullPath = require('../core/buildFullPath');
|
||||
var parseHeaders = require('./../helpers/parseHeaders');
|
||||
var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
|
||||
var createError = require('../core/createError');
|
||||
|
||||
module.exports = function xhrAdapter(config) {
|
||||
return new Promise(function dispatchXhrRequest(resolve, reject) {
|
||||
var requestData = config.data;
|
||||
var requestHeaders = config.headers;
|
||||
|
||||
if (utils.isFormData(requestData)) {
|
||||
delete requestHeaders['Content-Type']; // Let the browser set it
|
||||
}
|
||||
|
||||
var request = new XMLHttpRequest();
|
||||
|
||||
// HTTP basic authentication
|
||||
if (config.auth) {
|
||||
var username = config.auth.username || '';
|
||||
var password = config.auth.password || '';
|
||||
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
|
||||
}
|
||||
|
||||
var fullPath = buildFullPath(config.baseURL, config.url);
|
||||
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
|
||||
|
||||
// Set the request timeout in MS
|
||||
request.timeout = config.timeout;
|
||||
|
||||
// Listen for ready state
|
||||
request.onreadystatechange = function handleLoad() {
|
||||
if (!request || request.readyState !== 4) {
|
||||
return;
|
||||
}
|
||||
|
||||
// The request errored out and we didn't get a response, this will be
|
||||
// handled by onerror instead
|
||||
// With one exception: request that using file: protocol, most browsers
|
||||
// will return status as 0 even though it's a successful request
|
||||
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Prepare the response
|
||||
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
|
||||
var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
|
||||
var response = {
|
||||
data: responseData,
|
||||
status: request.status,
|
||||
statusText: request.statusText,
|
||||
headers: responseHeaders,
|
||||
config: config,
|
||||
request: request
|
||||
};
|
||||
|
||||
settle(resolve, reject, response);
|
||||
|
||||
// Clean up request
|
||||
request = null;
|
||||
};
|
||||
|
||||
// Handle browser request cancellation (as opposed to a manual cancellation)
|
||||
request.onabort = function handleAbort() {
|
||||
if (!request) {
|
||||
return;
|
||||
}
|
||||
|
||||
reject(createError('Request aborted', config, 'ECONNABORTED', request));
|
||||
|
||||
// Clean up request
|
||||
request = null;
|
||||
};
|
||||
|
||||
// Handle low level network errors
|
||||
request.onerror = function handleError() {
|
||||
// Real errors are hidden from us by the browser
|
||||
// onerror should only fire if it's a network error
|
||||
reject(createError('Network Error', config, null, request));
|
||||
|
||||
// Clean up request
|
||||
request = null;
|
||||
};
|
||||
|
||||
// Handle timeout
|
||||
request.ontimeout = function handleTimeout() {
|
||||
var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';
|
||||
if (config.timeoutErrorMessage) {
|
||||
timeoutErrorMessage = config.timeoutErrorMessage;
|
||||
}
|
||||
reject(createError(timeoutErrorMessage, config, 'ECONNABORTED',
|
||||
request));
|
||||
|
||||
// Clean up request
|
||||
request = null;
|
||||
};
|
||||
|
||||
// Add xsrf header
|
||||
// This is only done if running in a standard browser environment.
|
||||
// Specifically not if we're in a web worker, or react-native.
|
||||
if (utils.isStandardBrowserEnv()) {
|
||||
var cookies = require('./../helpers/cookies');
|
||||
|
||||
// Add xsrf header
|
||||
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
|
||||
cookies.read(config.xsrfCookieName) :
|
||||
undefined;
|
||||
|
||||
if (xsrfValue) {
|
||||
requestHeaders[config.xsrfHeaderName] = xsrfValue;
|
||||
}
|
||||
}
|
||||
|
||||
// Add headers to the request
|
||||
if ('setRequestHeader' in request) {
|
||||
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
|
||||
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
|
||||
// Remove Content-Type if data is undefined
|
||||
delete requestHeaders[key];
|
||||
} else {
|
||||
// Otherwise add header to the request
|
||||
request.setRequestHeader(key, val);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Add withCredentials to request if needed
|
||||
if (!utils.isUndefined(config.withCredentials)) {
|
||||
request.withCredentials = !!config.withCredentials;
|
||||
}
|
||||
|
||||
// Add responseType to request if needed
|
||||
if (config.responseType) {
|
||||
try {
|
||||
request.responseType = config.responseType;
|
||||
} catch (e) {
|
||||
// Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.
|
||||
// But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.
|
||||
if (config.responseType !== 'json') {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle progress if needed
|
||||
if (typeof config.onDownloadProgress === 'function') {
|
||||
request.addEventListener('progress', config.onDownloadProgress);
|
||||
}
|
||||
|
||||
// Not all browsers support upload events
|
||||
if (typeof config.onUploadProgress === 'function' && request.upload) {
|
||||
request.upload.addEventListener('progress', config.onUploadProgress);
|
||||
}
|
||||
|
||||
if (config.cancelToken) {
|
||||
// Handle cancellation
|
||||
config.cancelToken.promise.then(function onCanceled(cancel) {
|
||||
if (!request) {
|
||||
return;
|
||||
}
|
||||
|
||||
request.abort();
|
||||
reject(cancel);
|
||||
// Clean up request
|
||||
request = null;
|
||||
});
|
||||
}
|
||||
|
||||
if (requestData === undefined) {
|
||||
requestData = null;
|
||||
}
|
||||
|
||||
// Send the request
|
||||
request.send(requestData);
|
||||
});
|
||||
};
|
||||
-53
@@ -1,53 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./utils');
|
||||
var bind = require('./helpers/bind');
|
||||
var Axios = require('./core/Axios');
|
||||
var mergeConfig = require('./core/mergeConfig');
|
||||
var defaults = require('./defaults');
|
||||
|
||||
/**
|
||||
* Create an instance of Axios
|
||||
*
|
||||
* @param {Object} defaultConfig The default config for the instance
|
||||
* @return {Axios} A new instance of Axios
|
||||
*/
|
||||
function createInstance(defaultConfig) {
|
||||
var context = new Axios(defaultConfig);
|
||||
var instance = bind(Axios.prototype.request, context);
|
||||
|
||||
// Copy axios.prototype to instance
|
||||
utils.extend(instance, Axios.prototype, context);
|
||||
|
||||
// Copy context to instance
|
||||
utils.extend(instance, context);
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
// Create the default instance to be exported
|
||||
var axios = createInstance(defaults);
|
||||
|
||||
// Expose Axios class to allow class inheritance
|
||||
axios.Axios = Axios;
|
||||
|
||||
// Factory for creating new instances
|
||||
axios.create = function create(instanceConfig) {
|
||||
return createInstance(mergeConfig(axios.defaults, instanceConfig));
|
||||
};
|
||||
|
||||
// Expose Cancel & CancelToken
|
||||
axios.Cancel = require('./cancel/Cancel');
|
||||
axios.CancelToken = require('./cancel/CancelToken');
|
||||
axios.isCancel = require('./cancel/isCancel');
|
||||
|
||||
// Expose all/spread
|
||||
axios.all = function all(promises) {
|
||||
return Promise.all(promises);
|
||||
};
|
||||
axios.spread = require('./helpers/spread');
|
||||
|
||||
module.exports = axios;
|
||||
|
||||
// Allow use of default import syntax in TypeScript
|
||||
module.exports.default = axios;
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* A `Cancel` is an object that is thrown when an operation is canceled.
|
||||
*
|
||||
* @class
|
||||
* @param {string=} message The message.
|
||||
*/
|
||||
function Cancel(message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
Cancel.prototype.toString = function toString() {
|
||||
return 'Cancel' + (this.message ? ': ' + this.message : '');
|
||||
};
|
||||
|
||||
Cancel.prototype.__CANCEL__ = true;
|
||||
|
||||
module.exports = Cancel;
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var Cancel = require('./Cancel');
|
||||
|
||||
/**
|
||||
* A `CancelToken` is an object that can be used to request cancellation of an operation.
|
||||
*
|
||||
* @class
|
||||
* @param {Function} executor The executor function.
|
||||
*/
|
||||
function CancelToken(executor) {
|
||||
if (typeof executor !== 'function') {
|
||||
throw new TypeError('executor must be a function.');
|
||||
}
|
||||
|
||||
var resolvePromise;
|
||||
this.promise = new Promise(function promiseExecutor(resolve) {
|
||||
resolvePromise = resolve;
|
||||
});
|
||||
|
||||
var token = this;
|
||||
executor(function cancel(message) {
|
||||
if (token.reason) {
|
||||
// Cancellation has already been requested
|
||||
return;
|
||||
}
|
||||
|
||||
token.reason = new Cancel(message);
|
||||
resolvePromise(token.reason);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws a `Cancel` if cancellation has been requested.
|
||||
*/
|
||||
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
|
||||
if (this.reason) {
|
||||
throw this.reason;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns an object that contains a new `CancelToken` and a function that, when called,
|
||||
* cancels the `CancelToken`.
|
||||
*/
|
||||
CancelToken.source = function source() {
|
||||
var cancel;
|
||||
var token = new CancelToken(function executor(c) {
|
||||
cancel = c;
|
||||
});
|
||||
return {
|
||||
token: token,
|
||||
cancel: cancel
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = CancelToken;
|
||||
-5
@@ -1,5 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = function isCancel(value) {
|
||||
return !!(value && value.__CANCEL__);
|
||||
};
|
||||
-94
@@ -1,94 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
var buildURL = require('../helpers/buildURL');
|
||||
var InterceptorManager = require('./InterceptorManager');
|
||||
var dispatchRequest = require('./dispatchRequest');
|
||||
var mergeConfig = require('./mergeConfig');
|
||||
|
||||
/**
|
||||
* Create a new instance of Axios
|
||||
*
|
||||
* @param {Object} instanceConfig The default config for the instance
|
||||
*/
|
||||
function Axios(instanceConfig) {
|
||||
this.defaults = instanceConfig;
|
||||
this.interceptors = {
|
||||
request: new InterceptorManager(),
|
||||
response: new InterceptorManager()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch a request
|
||||
*
|
||||
* @param {Object} config The config specific for this request (merged with this.defaults)
|
||||
*/
|
||||
Axios.prototype.request = function request(config) {
|
||||
/*eslint no-param-reassign:0*/
|
||||
// Allow for axios('example/url'[, config]) a la fetch API
|
||||
if (typeof config === 'string') {
|
||||
config = arguments[1] || {};
|
||||
config.url = arguments[0];
|
||||
} else {
|
||||
config = config || {};
|
||||
}
|
||||
|
||||
config = mergeConfig(this.defaults, config);
|
||||
|
||||
// Set config.method
|
||||
if (config.method) {
|
||||
config.method = config.method.toLowerCase();
|
||||
} else if (this.defaults.method) {
|
||||
config.method = this.defaults.method.toLowerCase();
|
||||
} else {
|
||||
config.method = 'get';
|
||||
}
|
||||
|
||||
// Hook up interceptors middleware
|
||||
var chain = [dispatchRequest, undefined];
|
||||
var promise = Promise.resolve(config);
|
||||
|
||||
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
|
||||
chain.unshift(interceptor.fulfilled, interceptor.rejected);
|
||||
});
|
||||
|
||||
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
|
||||
chain.push(interceptor.fulfilled, interceptor.rejected);
|
||||
});
|
||||
|
||||
while (chain.length) {
|
||||
promise = promise.then(chain.shift(), chain.shift());
|
||||
}
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
Axios.prototype.getUri = function getUri(config) {
|
||||
config = mergeConfig(this.defaults, config);
|
||||
return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
|
||||
};
|
||||
|
||||
// Provide aliases for supported request methods
|
||||
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
|
||||
/*eslint func-names:0*/
|
||||
Axios.prototype[method] = function(url, config) {
|
||||
return this.request(utils.merge(config || {}, {
|
||||
method: method,
|
||||
url: url
|
||||
}));
|
||||
};
|
||||
});
|
||||
|
||||
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
|
||||
/*eslint func-names:0*/
|
||||
Axios.prototype[method] = function(url, data, config) {
|
||||
return this.request(utils.merge(config || {}, {
|
||||
method: method,
|
||||
url: url,
|
||||
data: data
|
||||
}));
|
||||
};
|
||||
});
|
||||
|
||||
module.exports = Axios;
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
|
||||
function InterceptorManager() {
|
||||
this.handlers = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new interceptor to the stack
|
||||
*
|
||||
* @param {Function} fulfilled The function to handle `then` for a `Promise`
|
||||
* @param {Function} rejected The function to handle `reject` for a `Promise`
|
||||
*
|
||||
* @return {Number} An ID used to remove interceptor later
|
||||
*/
|
||||
InterceptorManager.prototype.use = function use(fulfilled, rejected) {
|
||||
this.handlers.push({
|
||||
fulfilled: fulfilled,
|
||||
rejected: rejected
|
||||
});
|
||||
return this.handlers.length - 1;
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove an interceptor from the stack
|
||||
*
|
||||
* @param {Number} id The ID that was returned by `use`
|
||||
*/
|
||||
InterceptorManager.prototype.eject = function eject(id) {
|
||||
if (this.handlers[id]) {
|
||||
this.handlers[id] = null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Iterate over all the registered interceptors
|
||||
*
|
||||
* This method is particularly useful for skipping over any
|
||||
* interceptors that may have become `null` calling `eject`.
|
||||
*
|
||||
* @param {Function} fn The function to call for each interceptor
|
||||
*/
|
||||
InterceptorManager.prototype.forEach = function forEach(fn) {
|
||||
utils.forEach(this.handlers, function forEachHandler(h) {
|
||||
if (h !== null) {
|
||||
fn(h);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = InterceptorManager;
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
# axios // core
|
||||
|
||||
The modules found in `core/` should be modules that are specific to the domain logic of axios. These modules would most likely not make sense to be consumed outside of the axios module, as their logic is too specific. Some examples of core modules are:
|
||||
|
||||
- Dispatching requests
|
||||
- Managing interceptors
|
||||
- Handling config
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var isAbsoluteURL = require('../helpers/isAbsoluteURL');
|
||||
var combineURLs = require('../helpers/combineURLs');
|
||||
|
||||
/**
|
||||
* Creates a new URL by combining the baseURL with the requestedURL,
|
||||
* only when the requestedURL is not already an absolute URL.
|
||||
* If the requestURL is absolute, this function returns the requestedURL untouched.
|
||||
*
|
||||
* @param {string} baseURL The base URL
|
||||
* @param {string} requestedURL Absolute or relative URL to combine
|
||||
* @returns {string} The combined full path
|
||||
*/
|
||||
module.exports = function buildFullPath(baseURL, requestedURL) {
|
||||
if (baseURL && !isAbsoluteURL(requestedURL)) {
|
||||
return combineURLs(baseURL, requestedURL);
|
||||
}
|
||||
return requestedURL;
|
||||
};
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var enhanceError = require('./enhanceError');
|
||||
|
||||
/**
|
||||
* Create an Error with the specified message, config, error code, request and response.
|
||||
*
|
||||
* @param {string} message The error message.
|
||||
* @param {Object} config The config.
|
||||
* @param {string} [code] The error code (for example, 'ECONNABORTED').
|
||||
* @param {Object} [request] The request.
|
||||
* @param {Object} [response] The response.
|
||||
* @returns {Error} The created error.
|
||||
*/
|
||||
module.exports = function createError(message, config, code, request, response) {
|
||||
var error = new Error(message);
|
||||
return enhanceError(error, config, code, request, response);
|
||||
};
|
||||
-79
@@ -1,79 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
var transformData = require('./transformData');
|
||||
var isCancel = require('../cancel/isCancel');
|
||||
var defaults = require('../defaults');
|
||||
|
||||
/**
|
||||
* Throws a `Cancel` if cancellation has been requested.
|
||||
*/
|
||||
function throwIfCancellationRequested(config) {
|
||||
if (config.cancelToken) {
|
||||
config.cancelToken.throwIfRequested();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch a request to the server using the configured adapter.
|
||||
*
|
||||
* @param {object} config The config that is to be used for the request
|
||||
* @returns {Promise} The Promise to be fulfilled
|
||||
*/
|
||||
module.exports = function dispatchRequest(config) {
|
||||
throwIfCancellationRequested(config);
|
||||
|
||||
// Ensure headers exist
|
||||
config.headers = config.headers || {};
|
||||
|
||||
// Transform request data
|
||||
config.data = transformData(
|
||||
config.data,
|
||||
config.headers,
|
||||
config.transformRequest
|
||||
);
|
||||
|
||||
// Flatten headers
|
||||
config.headers = utils.merge(
|
||||
config.headers.common || {},
|
||||
config.headers[config.method] || {},
|
||||
config.headers
|
||||
);
|
||||
|
||||
utils.forEach(
|
||||
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
|
||||
function cleanHeaderConfig(method) {
|
||||
delete config.headers[method];
|
||||
}
|
||||
);
|
||||
|
||||
var adapter = config.adapter || defaults.adapter;
|
||||
|
||||
return adapter(config).then(function onAdapterResolution(response) {
|
||||
throwIfCancellationRequested(config);
|
||||
|
||||
// Transform response data
|
||||
response.data = transformData(
|
||||
response.data,
|
||||
response.headers,
|
||||
config.transformResponse
|
||||
);
|
||||
|
||||
return response;
|
||||
}, function onAdapterRejection(reason) {
|
||||
if (!isCancel(reason)) {
|
||||
throwIfCancellationRequested(config);
|
||||
|
||||
// Transform response data
|
||||
if (reason && reason.response) {
|
||||
reason.response.data = transformData(
|
||||
reason.response.data,
|
||||
reason.response.headers,
|
||||
config.transformResponse
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.reject(reason);
|
||||
});
|
||||
};
|
||||
-42
@@ -1,42 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Update an Error with the specified config, error code, and response.
|
||||
*
|
||||
* @param {Error} error The error to update.
|
||||
* @param {Object} config The config.
|
||||
* @param {string} [code] The error code (for example, 'ECONNABORTED').
|
||||
* @param {Object} [request] The request.
|
||||
* @param {Object} [response] The response.
|
||||
* @returns {Error} The error.
|
||||
*/
|
||||
module.exports = function enhanceError(error, config, code, request, response) {
|
||||
error.config = config;
|
||||
if (code) {
|
||||
error.code = code;
|
||||
}
|
||||
|
||||
error.request = request;
|
||||
error.response = response;
|
||||
error.isAxiosError = true;
|
||||
|
||||
error.toJSON = function() {
|
||||
return {
|
||||
// Standard
|
||||
message: this.message,
|
||||
name: this.name,
|
||||
// Microsoft
|
||||
description: this.description,
|
||||
number: this.number,
|
||||
// Mozilla
|
||||
fileName: this.fileName,
|
||||
lineNumber: this.lineNumber,
|
||||
columnNumber: this.columnNumber,
|
||||
stack: this.stack,
|
||||
// Axios
|
||||
config: this.config,
|
||||
code: this.code
|
||||
};
|
||||
};
|
||||
return error;
|
||||
};
|
||||
-73
@@ -1,73 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('../utils');
|
||||
|
||||
/**
|
||||
* Config-specific merge-function which creates a new config-object
|
||||
* by merging two configuration objects together.
|
||||
*
|
||||
* @param {Object} config1
|
||||
* @param {Object} config2
|
||||
* @returns {Object} New object resulting from merging config2 to config1
|
||||
*/
|
||||
module.exports = function mergeConfig(config1, config2) {
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
config2 = config2 || {};
|
||||
var config = {};
|
||||
|
||||
var valueFromConfig2Keys = ['url', 'method', 'params', 'data'];
|
||||
var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy'];
|
||||
var defaultToConfig2Keys = [
|
||||
'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer',
|
||||
'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
|
||||
'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress',
|
||||
'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent',
|
||||
'httpsAgent', 'cancelToken', 'socketPath'
|
||||
];
|
||||
|
||||
utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
|
||||
if (typeof config2[prop] !== 'undefined') {
|
||||
config[prop] = config2[prop];
|
||||
}
|
||||
});
|
||||
|
||||
utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) {
|
||||
if (utils.isObject(config2[prop])) {
|
||||
config[prop] = utils.deepMerge(config1[prop], config2[prop]);
|
||||
} else if (typeof config2[prop] !== 'undefined') {
|
||||
config[prop] = config2[prop];
|
||||
} else if (utils.isObject(config1[prop])) {
|
||||
config[prop] = utils.deepMerge(config1[prop]);
|
||||
} else if (typeof config1[prop] !== 'undefined') {
|
||||
config[prop] = config1[prop];
|
||||
}
|
||||
});
|
||||
|
||||
utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
|
||||
if (typeof config2[prop] !== 'undefined') {
|
||||
config[prop] = config2[prop];
|
||||
} else if (typeof config1[prop] !== 'undefined') {
|
||||
config[prop] = config1[prop];
|
||||
}
|
||||
});
|
||||
|
||||
var axiosKeys = valueFromConfig2Keys
|
||||
.concat(mergeDeepPropertiesKeys)
|
||||
.concat(defaultToConfig2Keys);
|
||||
|
||||
var otherKeys = Object
|
||||
.keys(config2)
|
||||
.filter(function filterAxiosKeys(key) {
|
||||
return axiosKeys.indexOf(key) === -1;
|
||||
});
|
||||
|
||||
utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) {
|
||||
if (typeof config2[prop] !== 'undefined') {
|
||||
config[prop] = config2[prop];
|
||||
} else if (typeof config1[prop] !== 'undefined') {
|
||||
config[prop] = config1[prop];
|
||||
}
|
||||
});
|
||||
|
||||
return config;
|
||||
};
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var createError = require('./createError');
|
||||
|
||||
/**
|
||||
* Resolve or reject a Promise based on response status.
|
||||
*
|
||||
* @param {Function} resolve A function that resolves the promise.
|
||||
* @param {Function} reject A function that rejects the promise.
|
||||
* @param {object} response The response.
|
||||
*/
|
||||
module.exports = function settle(resolve, reject, response) {
|
||||
var validateStatus = response.config.validateStatus;
|
||||
if (!validateStatus || validateStatus(response.status)) {
|
||||
resolve(response);
|
||||
} else {
|
||||
reject(createError(
|
||||
'Request failed with status code ' + response.status,
|
||||
response.config,
|
||||
null,
|
||||
response.request,
|
||||
response
|
||||
));
|
||||
}
|
||||
};
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
|
||||
/**
|
||||
* Transform the data for a request or a response
|
||||
*
|
||||
* @param {Object|String} data The data to be transformed
|
||||
* @param {Array} headers The headers for the request or response
|
||||
* @param {Array|Function} fns A single function or Array of functions
|
||||
* @returns {*} The resulting transformed data
|
||||
*/
|
||||
module.exports = function transformData(data, headers, fns) {
|
||||
/*eslint no-param-reassign:0*/
|
||||
utils.forEach(fns, function transform(fn) {
|
||||
data = fn(data, headers);
|
||||
});
|
||||
|
||||
return data;
|
||||
};
|
||||
-97
@@ -1,97 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./utils');
|
||||
var normalizeHeaderName = require('./helpers/normalizeHeaderName');
|
||||
|
||||
var DEFAULT_CONTENT_TYPE = {
|
||||
'Content-Type': 'application/x-www-form-urlencoded'
|
||||
};
|
||||
|
||||
function setContentTypeIfUnset(headers, value) {
|
||||
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
|
||||
headers['Content-Type'] = value;
|
||||
}
|
||||
}
|
||||
|
||||
function getDefaultAdapter() {
|
||||
var adapter;
|
||||
if (typeof XMLHttpRequest !== 'undefined') {
|
||||
// For browsers use XHR adapter
|
||||
adapter = require('./adapters/xhr');
|
||||
} else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
|
||||
// For node use HTTP adapter
|
||||
adapter = require('./adapters/http');
|
||||
}
|
||||
return adapter;
|
||||
}
|
||||
|
||||
var defaults = {
|
||||
adapter: getDefaultAdapter(),
|
||||
|
||||
transformRequest: [function transformRequest(data, headers) {
|
||||
normalizeHeaderName(headers, 'Accept');
|
||||
normalizeHeaderName(headers, 'Content-Type');
|
||||
if (utils.isFormData(data) ||
|
||||
utils.isArrayBuffer(data) ||
|
||||
utils.isBuffer(data) ||
|
||||
utils.isStream(data) ||
|
||||
utils.isFile(data) ||
|
||||
utils.isBlob(data)
|
||||
) {
|
||||
return data;
|
||||
}
|
||||
if (utils.isArrayBufferView(data)) {
|
||||
return data.buffer;
|
||||
}
|
||||
if (utils.isURLSearchParams(data)) {
|
||||
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
|
||||
return data.toString();
|
||||
}
|
||||
if (utils.isObject(data)) {
|
||||
setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
|
||||
return JSON.stringify(data);
|
||||
}
|
||||
return data;
|
||||
}],
|
||||
|
||||
transformResponse: [function transformResponse(data) {
|
||||
/*eslint no-param-reassign:0*/
|
||||
if (typeof data === 'string') {
|
||||
try {
|
||||
data = JSON.parse(data);
|
||||
} catch (e) { /* Ignore */ }
|
||||
}
|
||||
return data;
|
||||
}],
|
||||
|
||||
/**
|
||||
* A timeout in milliseconds to abort a request. If set to 0 (default) a
|
||||
* timeout is not created.
|
||||
*/
|
||||
timeout: 0,
|
||||
|
||||
xsrfCookieName: 'XSRF-TOKEN',
|
||||
xsrfHeaderName: 'X-XSRF-TOKEN',
|
||||
|
||||
maxContentLength: -1,
|
||||
|
||||
validateStatus: function validateStatus(status) {
|
||||
return status >= 200 && status < 300;
|
||||
}
|
||||
};
|
||||
|
||||
defaults.headers = {
|
||||
common: {
|
||||
'Accept': 'application/json, text/plain, */*'
|
||||
}
|
||||
};
|
||||
|
||||
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
|
||||
defaults.headers[method] = {};
|
||||
});
|
||||
|
||||
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
|
||||
defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
|
||||
});
|
||||
|
||||
module.exports = defaults;
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
# axios // helpers
|
||||
|
||||
The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like:
|
||||
|
||||
- Browser polyfills
|
||||
- Managing cookies
|
||||
- Parsing HTTP headers
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = function bind(fn, thisArg) {
|
||||
return function wrap() {
|
||||
var args = new Array(arguments.length);
|
||||
for (var i = 0; i < args.length; i++) {
|
||||
args[i] = arguments[i];
|
||||
}
|
||||
return fn.apply(thisArg, args);
|
||||
};
|
||||
};
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
|
||||
function encode(val) {
|
||||
return encodeURIComponent(val).
|
||||
replace(/%40/gi, '@').
|
||||
replace(/%3A/gi, ':').
|
||||
replace(/%24/g, '$').
|
||||
replace(/%2C/gi, ',').
|
||||
replace(/%20/g, '+').
|
||||
replace(/%5B/gi, '[').
|
||||
replace(/%5D/gi, ']');
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a URL by appending params to the end
|
||||
*
|
||||
* @param {string} url The base of the url (e.g., http://www.google.com)
|
||||
* @param {object} [params] The params to be appended
|
||||
* @returns {string} The formatted url
|
||||
*/
|
||||
module.exports = function buildURL(url, params, paramsSerializer) {
|
||||
/*eslint no-param-reassign:0*/
|
||||
if (!params) {
|
||||
return url;
|
||||
}
|
||||
|
||||
var serializedParams;
|
||||
if (paramsSerializer) {
|
||||
serializedParams = paramsSerializer(params);
|
||||
} else if (utils.isURLSearchParams(params)) {
|
||||
serializedParams = params.toString();
|
||||
} else {
|
||||
var parts = [];
|
||||
|
||||
utils.forEach(params, function serialize(val, key) {
|
||||
if (val === null || typeof val === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (utils.isArray(val)) {
|
||||
key = key + '[]';
|
||||
} else {
|
||||
val = [val];
|
||||
}
|
||||
|
||||
utils.forEach(val, function parseValue(v) {
|
||||
if (utils.isDate(v)) {
|
||||
v = v.toISOString();
|
||||
} else if (utils.isObject(v)) {
|
||||
v = JSON.stringify(v);
|
||||
}
|
||||
parts.push(encode(key) + '=' + encode(v));
|
||||
});
|
||||
});
|
||||
|
||||
serializedParams = parts.join('&');
|
||||
}
|
||||
|
||||
if (serializedParams) {
|
||||
var hashmarkIndex = url.indexOf('#');
|
||||
if (hashmarkIndex !== -1) {
|
||||
url = url.slice(0, hashmarkIndex);
|
||||
}
|
||||
|
||||
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
|
||||
}
|
||||
|
||||
return url;
|
||||
};
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Creates a new URL by combining the specified URLs
|
||||
*
|
||||
* @param {string} baseURL The base URL
|
||||
* @param {string} relativeURL The relative URL
|
||||
* @returns {string} The combined URL
|
||||
*/
|
||||
module.exports = function combineURLs(baseURL, relativeURL) {
|
||||
return relativeURL
|
||||
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
|
||||
: baseURL;
|
||||
};
|
||||
-53
@@ -1,53 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
|
||||
module.exports = (
|
||||
utils.isStandardBrowserEnv() ?
|
||||
|
||||
// Standard browser envs support document.cookie
|
||||
(function standardBrowserEnv() {
|
||||
return {
|
||||
write: function write(name, value, expires, path, domain, secure) {
|
||||
var cookie = [];
|
||||
cookie.push(name + '=' + encodeURIComponent(value));
|
||||
|
||||
if (utils.isNumber(expires)) {
|
||||
cookie.push('expires=' + new Date(expires).toGMTString());
|
||||
}
|
||||
|
||||
if (utils.isString(path)) {
|
||||
cookie.push('path=' + path);
|
||||
}
|
||||
|
||||
if (utils.isString(domain)) {
|
||||
cookie.push('domain=' + domain);
|
||||
}
|
||||
|
||||
if (secure === true) {
|
||||
cookie.push('secure');
|
||||
}
|
||||
|
||||
document.cookie = cookie.join('; ');
|
||||
},
|
||||
|
||||
read: function read(name) {
|
||||
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
|
||||
return (match ? decodeURIComponent(match[3]) : null);
|
||||
},
|
||||
|
||||
remove: function remove(name) {
|
||||
this.write(name, '', Date.now() - 86400000);
|
||||
}
|
||||
};
|
||||
})() :
|
||||
|
||||
// Non standard browser env (web workers, react-native) lack needed support.
|
||||
(function nonStandardBrowserEnv() {
|
||||
return {
|
||||
write: function write() {},
|
||||
read: function read() { return null; },
|
||||
remove: function remove() {}
|
||||
};
|
||||
})()
|
||||
);
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/*eslint no-console:0*/
|
||||
|
||||
/**
|
||||
* Supply a warning to the developer that a method they are using
|
||||
* has been deprecated.
|
||||
*
|
||||
* @param {string} method The name of the deprecated method
|
||||
* @param {string} [instead] The alternate method to use if applicable
|
||||
* @param {string} [docs] The documentation URL to get further details
|
||||
*/
|
||||
module.exports = function deprecatedMethod(method, instead, docs) {
|
||||
try {
|
||||
console.warn(
|
||||
'DEPRECATED method `' + method + '`.' +
|
||||
(instead ? ' Use `' + instead + '` instead.' : '') +
|
||||
' This method will be removed in a future release.');
|
||||
|
||||
if (docs) {
|
||||
console.warn('For more information about usage see ' + docs);
|
||||
}
|
||||
} catch (e) { /* Ignore */ }
|
||||
};
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Determines whether the specified URL is absolute
|
||||
*
|
||||
* @param {string} url The URL to test
|
||||
* @returns {boolean} True if the specified URL is absolute, otherwise false
|
||||
*/
|
||||
module.exports = function isAbsoluteURL(url) {
|
||||
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
|
||||
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
|
||||
// by any combination of letters, digits, plus, period, or hyphen.
|
||||
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
|
||||
};
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
|
||||
module.exports = (
|
||||
utils.isStandardBrowserEnv() ?
|
||||
|
||||
// Standard browser envs have full support of the APIs needed to test
|
||||
// whether the request URL is of the same origin as current location.
|
||||
(function standardBrowserEnv() {
|
||||
var msie = /(msie|trident)/i.test(navigator.userAgent);
|
||||
var urlParsingNode = document.createElement('a');
|
||||
var originURL;
|
||||
|
||||
/**
|
||||
* Parse a URL to discover it's components
|
||||
*
|
||||
* @param {String} url The URL to be parsed
|
||||
* @returns {Object}
|
||||
*/
|
||||
function resolveURL(url) {
|
||||
var href = url;
|
||||
|
||||
if (msie) {
|
||||
// IE needs attribute set twice to normalize properties
|
||||
urlParsingNode.setAttribute('href', href);
|
||||
href = urlParsingNode.href;
|
||||
}
|
||||
|
||||
urlParsingNode.setAttribute('href', href);
|
||||
|
||||
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
|
||||
return {
|
||||
href: urlParsingNode.href,
|
||||
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
|
||||
host: urlParsingNode.host,
|
||||
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
|
||||
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
|
||||
hostname: urlParsingNode.hostname,
|
||||
port: urlParsingNode.port,
|
||||
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
|
||||
urlParsingNode.pathname :
|
||||
'/' + urlParsingNode.pathname
|
||||
};
|
||||
}
|
||||
|
||||
originURL = resolveURL(window.location.href);
|
||||
|
||||
/**
|
||||
* Determine if a URL shares the same origin as the current location
|
||||
*
|
||||
* @param {String} requestURL The URL to test
|
||||
* @returns {boolean} True if URL shares the same origin, otherwise false
|
||||
*/
|
||||
return function isURLSameOrigin(requestURL) {
|
||||
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
|
||||
return (parsed.protocol === originURL.protocol &&
|
||||
parsed.host === originURL.host);
|
||||
};
|
||||
})() :
|
||||
|
||||
// Non standard browser envs (web workers, react-native) lack needed support.
|
||||
(function nonStandardBrowserEnv() {
|
||||
return function isURLSameOrigin() {
|
||||
return true;
|
||||
};
|
||||
})()
|
||||
);
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('../utils');
|
||||
|
||||
module.exports = function normalizeHeaderName(headers, normalizedName) {
|
||||
utils.forEach(headers, function processHeader(value, name) {
|
||||
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
|
||||
headers[normalizedName] = value;
|
||||
delete headers[name];
|
||||
}
|
||||
});
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user