Socket
Socket
Sign inDemoInstall

superagent

Package Overview
Dependencies
Maintainers
10
Versions
173
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

superagent - npm Package Compare versions

Comparing version 3.7.0 to 3.8.0-alpha.1

lib/agent-base.js

21

docs/index.md

@@ -446,4 +446,6 @@

## Preserving cookies
## Agents for global state
### Saving cookies
In Node SuperAgent does not save cookies by default, but you can use the `.agent()` method to create a copy of SuperAgent that saves cookies. Each copy has a separate cookie jar.

@@ -458,4 +460,15 @@

In browsers cookies are managed automatically by the browser, and there is no `.agent()` method.
In browsers cookies are managed automatically by the browser, so the `.agent()` does not isolate cookies.
### Default options for multiple requests
Regular request methods (`.use()`, `.set()`, `.auth()`) called on the agent will be used as defaults for all requests made by that agent.
const agent = request.agent()
.use(plugin)
.auth(shared);
await agent.get('/with-plugin-and-auth');
await agent.get('/also-with-plugin-and-auth');
## Piping data

@@ -472,3 +485,3 @@

stream.pipe(req);
Note that when you pipe to a request, superagent sends the piped data with [chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding), which isn't supported by all servers (for instance, Python WSGI servers).

@@ -562,3 +575,3 @@

Note that a 4xx or 5xx response with super agent **are** considered an error by default. For example if you get a 500 or 403 response, this status information will be available via `err.status`. Errors from such responses also contain an `err.response` field with all of the properties mentioned in "[Response properties](#response-properties)". The library behaves in this way to handle the common case of wanting success responses and treating HTTP error status codes as errors while still allowing for custom logic around specific error conditions.
Note that **superagent considers 4xx and 5xx responses (as well as unhandled 3xx responses) errors by default**. For example, if you get a `304 Not modified`, `403 Forbidden` or `500 Internal server error` response, this status information will be available via `err.status`. Errors from such responses also contain an `err.response` field with all of the properties mentioned in "[Response properties](#response-properties)". The library behaves in this way to handle the common case of wanting success responses and treating HTTP error status codes as errors while still allowing for custom logic around specific error conditions.

@@ -565,0 +578,0 @@ Network failures, timeouts, and other errors that produce no response will contain no `err.status` or `err.response` fields.

101

lib/client.js

@@ -19,2 +19,3 @@ /**

var ResponseBase = require('./response-base');
var Agent = require('./agent-base');
var shouldRetry = require('./should-retry');

@@ -127,5 +128,5 @@

request.serializeObject = serialize;
request.serializeObject = serialize;
/**
/**
* Parse the given x-www-form-urlencoded `str`.

@@ -189,8 +190,8 @@ *

request.serialize = {
'application/x-www-form-urlencoded': serialize,
'application/json': JSON.stringify
};
request.serialize = {
'application/x-www-form-urlencoded': serialize,
'application/json': JSON.stringify,
};
/**
/**
* Default parsers.

@@ -206,3 +207,3 @@ *

'application/x-www-form-urlencoded': parseString,
'application/json': JSON.parse
'application/json': JSON.parse,
};

@@ -310,3 +311,3 @@

if (status === 1223) {
status = 204;
status = 204;
}

@@ -343,5 +344,5 @@ this._setStatusProperties(status);

Response.prototype._parseBody = function(str){
Response.prototype._parseBody = function(str) {
var parse = request.parse[this.type];
if(this.req._parser) {
if (this.req._parser) {
return this.req._parser(this, str);

@@ -517,4 +518,6 @@ }

Request.prototype.auth = function(user, pass, options){
if (typeof pass === 'object' && pass !== null) { // pass is optional and can substitute for options
if (1 === arguments.length) pass = '';
if (typeof pass === 'object' && pass !== null) { // pass is optional and can be replaced with options
options = pass;
pass = '';
}

@@ -524,20 +527,13 @@ if (!options) {

type: 'function' === typeof btoa ? 'basic' : 'auto',
}
};
}
switch (options.type) {
case 'basic':
this.set('Authorization', 'Basic ' + btoa(user + ':' + pass));
break;
var encoder = function(string) {
if ('function' === typeof btoa) {
return btoa(string);
}
throw new Error('Cannot use basic auth, btoa is not a function');
};
case 'auto':
this.username = user;
this.password = pass;
break;
case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' })
this.set('Authorization', 'Bearer ' + user);
break;
}
return this;
return this._auth(user, pass, options, encoder);
};

@@ -693,3 +689,3 @@

var self = this;
var xhr = this.xhr = request.getXHR();
var xhr = (this.xhr = request.getXHR());
var data = this._formData || this._data;

@@ -728,3 +724,3 @@

self.emit('progress', e);
}
};
if (this.hasListeners('progress')) {

@@ -790,2 +786,19 @@ try {

request.agent = function() {
return new Agent();
};
["GET", "POST", "OPTIONS", "PATCH", "PUT", "DELETE"].forEach(function(method) {
Agent.prototype[method.toLowerCase()] = function(url, fn) {
var req = new request.Request(method, url);
this._setDefaults(req);
if (fn) {
req.end(fn);
}
return req;
};
});
Agent.prototype.del = Agent.prototype['delete'];
/**

@@ -801,5 +814,5 @@ * GET `url` with optional callback `fn(res)`.

request.get = function(url, data, fn){
request.get = function(url, data, fn) {
var req = request('GET', url);
if ('function' == typeof data) fn = data, data = null;
if ('function' == typeof data) (fn = data), (data = null);
if (data) req.query(data);

@@ -820,5 +833,5 @@ if (fn) req.end(fn);

request.head = function(url, data, fn){
request.head = function(url, data, fn) {
var req = request('HEAD', url);
if ('function' == typeof data) fn = data, data = null;
if ('function' == typeof data) (fn = data), (data = null);
if (data) req.query(data);

@@ -839,5 +852,5 @@ if (fn) req.end(fn);

request.options = function(url, data, fn){
request.options = function(url, data, fn) {
var req = request('OPTIONS', url);
if ('function' == typeof data) fn = data, data = null;
if ('function' == typeof data) (fn = data), (data = null);
if (data) req.send(data);

@@ -858,9 +871,9 @@ if (fn) req.end(fn);

function del(url, data, fn){
function del(url, data, fn) {
var req = request('DELETE', url);
if ('function' == typeof data) fn = data, data = null;
if ('function' == typeof data) (fn = data), (data = null);
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
}

@@ -880,5 +893,5 @@ request['del'] = del;

request.patch = function(url, data, fn){
request.patch = function(url, data, fn) {
var req = request('PATCH', url);
if ('function' == typeof data) fn = data, data = null;
if ('function' == typeof data) (fn = data), (data = null);
if (data) req.send(data);

@@ -899,5 +912,5 @@ if (fn) req.end(fn);

request.post = function(url, data, fn){
request.post = function(url, data, fn) {
var req = request('POST', url);
if ('function' == typeof data) fn = data, data = null;
if ('function' == typeof data) (fn = data), (data = null);
if (data) req.send(data);

@@ -918,5 +931,5 @@ if (fn) req.end(fn);

request.put = function(url, data, fn){
request.put = function(url, data, fn) {
var req = request('PUT', url);
if ('function' == typeof data) fn = data, data = null;
if ('function' == typeof data) (fn = data), (data = null);
if (data) req.send(data);

@@ -923,0 +936,0 @@ if (fn) req.end(fn);

@@ -7,7 +7,8 @@ 'use strict';

var CookieJar = require('cookiejar').CookieJar;
var CookieAccess = require('cookiejar').CookieAccessInfo;
var parse = require('url').parse;
var request = require('../..');
var methods = require('methods');
const CookieJar = require('cookiejar').CookieJar;
const CookieAccess = require('cookiejar').CookieAccessInfo;
const parse = require('url').parse;
const request = require('../..');
const AgentBase = require('../agent-base');
let methods = require('methods');

@@ -27,12 +28,18 @@ /**

function Agent(options) {
if (!(this instanceof Agent)) return new Agent(options);
if (!(this instanceof Agent)) {
return new Agent(options);
}
AgentBase.call(this);
this.jar = new CookieJar();
if (options) {
this._ca = options.ca;
this._key = options.key;
this._pfx = options.pfx;
this._cert = options.cert;
if (options.ca) {this.ca(options.ca);}
if (options.key) {this.key(options.key);}
if (options.pfx) {this.pfx(options.pfx);}
if (options.cert) {this.cert(options.cert);}
}
this.jar = new CookieJar;
}
Agent.prototype = Object.create(AgentBase.prototype);
/**

@@ -46,4 +53,4 @@ * Save the cookies in the given `res` to

Agent.prototype._saveCookies = function(res){
var cookies = res.headers['set-cookie'];
Agent.prototype._saveCookies = function(res) {
const cookies = res.headers['set-cookie'];
if (cookies) this.jar.setCookies(cookies);

@@ -59,29 +66,18 @@ };

Agent.prototype._attachCookies = function(req){
var url = parse(req.url);
var access = CookieAccess(url.hostname, url.pathname, 'https:' == url.protocol);
var cookies = this.jar.getCookies(access).toValueString();
Agent.prototype._attachCookies = function(req) {
const url = parse(req.url);
const access = CookieAccess(
url.hostname,
url.pathname,
'https:' == url.protocol
);
const cookies = this.jar.getCookies(access).toValueString();
req.cookies = cookies;
};
// generate HTTP verb methods
if (methods.indexOf('del') == -1) {
// create a copy so we don't cause conflicts with
// other packages using the methods package and
// npm 3.x
methods = methods.slice(0);
methods.push('del');
}
methods.forEach(function(method){
var name = method;
method = 'del' == method ? 'delete' : method;
methods.forEach(name => {
const method = name.toUpperCase();
Agent.prototype[name] = function(url, fn) {
const req = new request.Request(method, url);
method = method.toUpperCase();
Agent.prototype[name] = function(url, fn){
var req = new request.Request(method, url);
req.ca(this._ca);
req.key(this._key);
req.pfx(this._pfx);
req.cert(this._cert);
req.on('response', this._saveCookies.bind(this));

@@ -91,6 +87,11 @@ req.on('redirect', this._saveCookies.bind(this));

this._attachCookies(req);
this._setDefaults(req);
fn && req.end(fn);
if (fn) {
req.end(fn);
}
return req;
};
});
Agent.prototype.del = Agent.prototype['delete'];

@@ -7,26 +7,26 @@ 'use strict';

var debug = require('debug')('superagent');
var formidable = require('formidable');
var FormData = require('form-data');
var Response = require('./response');
var parse = require('url').parse;
var format = require('url').format;
var resolve = require('url').resolve;
var methods = require('methods');
var Stream = require('stream');
var utils = require('../utils');
var unzip = require('./unzip').unzip;
var extend = require('extend');
var mime = require('mime');
var https = require('https');
var http = require('http');
var fs = require('fs');
var qs = require('qs');
var zlib = require('zlib');
var util = require('util');
var pkg = require('../../package.json');
var RequestBase = require('../request-base');
var shouldRetry = require('../should-retry');
const debug = require('debug')('superagent');
const formidable = require('formidable');
const FormData = require('form-data');
const Response = require('./response');
const parse = require('url').parse;
const format = require('url').format;
const resolve = require('url').resolve;
let methods = require('methods');
const Stream = require('stream');
const utils = require('../utils');
const unzip = require('./unzip').unzip;
const extend = require('extend');
const mime = require('mime');
const https = require('https');
const http = require('http');
const fs = require('fs');
const qs = require('qs');
const zlib = require('zlib');
const util = require('util');
const pkg = require('../../package.json');
const RequestBase = require('../request-base');
const shouldRetry = require('../should-retry');
var request = exports = module.exports = function(method, url) {
function request(method, url) {
// callback

@@ -44,2 +44,3 @@ if ('function' == typeof url) {

}
exports = module.exports = request;

@@ -84,3 +85,3 @@ /**

'http:': http,
'https:': https
'https:': https,
};

@@ -99,3 +100,3 @@

'application/x-www-form-urlencoded': qs.stringify,
'application/json': JSON.stringify
'application/json': JSON.stringify,
};

@@ -121,3 +122,3 @@

function _initHeaders(req) {
var ua = 'node-superagent/' + pkg.version;
const ua = `node-superagent/${pkg.version}`;
req._header = { // coerces header names to lowercase

@@ -197,3 +198,3 @@ 'user-agent': ua

var o = options || {};
let o = options || {};
if ('string' == typeof options) {

@@ -219,6 +220,5 @@ o = { filename: options };

this._formData = new FormData();
var that = this;
this._formData.on('error', function(err) {
that.emit('error', err);
that.abort();
this._formData.on('error', err => {
this.emit('error', err);
this.abort();
});

@@ -269,6 +269,7 @@ }

Request.prototype.type = function(type){
return this.set('Content-Type', ~type.indexOf('/')
? type
: mime.lookup(type));
Request.prototype.type = function(type) {
return this.set(
'Content-Type',
~type.indexOf('/') ? type : mime.lookup(type)
);
};

@@ -335,3 +336,3 @@

Request.prototype.write = function(data, encoding){
var req = this.request();
const req = this.request();
if (!this._streamRequest) {

@@ -360,21 +361,28 @@ this._streamRequest = true;

Request.prototype._pipeContinue = function(stream, options){
var self = this;
this.req.once('response', function(res){
this.req.once('response', res => {
// redirect
var redirect = isRedirect(res.statusCode);
if (redirect && self._redirects++ != self._maxRedirects) {
return self._redirect(res)._pipeContinue(stream, options);
const redirect = isRedirect(res.statusCode);
if (redirect && this._redirects++ != this._maxRedirects) {
return this._redirect(res)._pipeContinue(stream, options);
}
self.res = res;
self._emitResponse();
if (self._aborted) return;
this.res = res;
this._emitResponse();
if (this._aborted) return;
if (self._shouldUnzip(res)) {
res.pipe(zlib.createUnzip()).pipe(stream, options);
if (this._shouldUnzip(res)) {
const unzipObj = zlib.createUnzip();
unzipObj.on('error', err => {
if (err && err.code === 'Z_BUF_ERROR') { // unexpected end of file is ignored by browsers and curl
stream.emit('end');
return;
}
stream.emit('error', err);
});
res.pipe(unzipObj).pipe(stream, options);
} else {
res.pipe(stream, options);
}
res.once('end', function(){
self.emit('end');
res.once('end', () => {
this.emit('end');
});

@@ -407,3 +415,3 @@ });

Request.prototype._redirect = function(res){
var url = res.headers.location;
let url = res.headers.location;
if (!url) {

@@ -422,5 +430,5 @@ return this.callback(new Error('No location header for redirect'), res);

var headers = this.req._headers;
let headers = this.req._headers;
var shouldStripCookie = parse(url).host !== parse(this.url).host;
const shouldStripCookie = parse(url).host !== parse(this.url).host;

@@ -461,3 +469,3 @@ // implementation of 302 following defacto standard

// remove all add header except User-Agent
_initHeaders(this)
_initHeaders(this);

@@ -495,15 +503,15 @@ // redirect

if (1 === arguments.length) pass = '';
if (2 === arguments.length && typeof pass === 'object') options = pass;
if (typeof pass === 'object' && pass !== null) { // pass is optional and can be replaced with options
options = pass;
pass = '';
}
if (!options) {
options = { type: 'basic' };
}
switch (options.type) {
case 'bearer':
return this.set('Authorization', 'Bearer ' + user);
default: // 'basic'
if (!~user.indexOf(':')) user = user + ':';
var str = new Buffer(user + pass).toString('base64');
return this.set('Authorization', 'Basic ' + str);
}
var encoder = function(string) {
return new Buffer(string).toString('base64');
};
return this._auth(user, pass, options, encoder);
};

@@ -545,4 +553,4 @@

Request.prototype.pfx = function(cert){
if(typeof cert === 'object' && !Buffer.isBuffer(cert)){
Request.prototype.pfx = function(cert) {
if (typeof cert === 'object' && !Buffer.isBuffer(cert)) {
this._pfx = cert.pfx;

@@ -579,7 +587,9 @@ this._passphrase = cert.passphrase;

var self = this;
var options = {};
const options = {};
try {
var query = qs.stringify(this.qs, { indices: false, strictNullHandling: true });
const query = qs.stringify(this.qs, {
indices: false,
strictNullHandling: true,
});
if (query) {

@@ -594,7 +604,7 @@ this.qs = {};

var url = this.url;
var retries = this._retries;
let url = this.url;
const retries = this._retries;
// default to http://
if (0 != url.indexOf('http')) url = 'http://' + url;
if (0 != url.indexOf('http')) url = `http://${url}`;
url = parse(url);

@@ -605,6 +615,6 @@

// get the protocol
url.protocol = url.protocol.split('+')[0] + ':';
url.protocol = `${url.protocol.split('+')[0]}:`;
// get the socket, path
var unixParts = url.path.match(/^([^/]+)(.+)$/);
const unixParts = url.path.match(/^([^/]+)(.+)$/);
options.socketPath = unixParts[1].replace(/%2F/g, '/');

@@ -627,6 +637,6 @@ url.path = unixParts[2];

// initiate request
var mod = exports.protocols[url.protocol];
const mod = exports.protocols[url.protocol];
// request
var req = this.req = mod.request(options);
const req = (this.req = mod.request(options));

@@ -643,16 +653,16 @@ // set tcp no delay

// expose events
req.once('drain', function(){ self.emit('drain'); });
req.once('drain', () => { this.emit('drain'); });
req.once('error', function(err){
req.once('error', err => {
// flag abortion here for out timeouts
// because node will emit a faux-error "socket hang up"
// when request is aborted before a connection is made
if (self._aborted) return;
if (this._aborted) return;
// if not the same, we are in the **old** (cancelled) request,
// so need to continue (same as for above)
if (self._retries !== retries) return;
if (this._retries !== retries) return;
// if we've received a response then we don't want to let
// an error in the request blow up the response
if (self.response) return;
self.callback(err);
if (this.response) return;
this.callback(err);
});

@@ -662,5 +672,8 @@

if (url.auth) {
var auth = url.auth.split(':');
const auth = url.auth.split(':');
this.auth(auth[0], auth[1]);
}
if (this.username && this.password) {
this.auth(this.username, this.password);
}

@@ -670,3 +683,3 @@ // add cookies

for (var key in this.header) {
for (const key in this.header) {
if (this.header.hasOwnProperty(key))

@@ -695,3 +708,3 @@ req.setHeader(key, this.header[key]);

// Avoid the error which is emitted from 'socket hang up' to cause the fn undefined error on JS runtime.
var fn = this._callback || noop;
const fn = this._callback || noop;
this.clearTimeout();

@@ -707,3 +720,3 @@ if (this.called) return console.warn('superagent: double callback bug');

var msg = 'Unsuccessful HTTP response';
let msg = 'Unsuccessful HTTP response';
if (res) {

@@ -751,15 +764,15 @@ msg = http.STATUS_CODES[res.status] || msg;

Request.prototype._emitResponse = function(body, files){
var response = new Response(this);
this.response = response;
response.redirects = this._redirectList;
if (undefined !== body) {
response.body = body;
}
response.files = files;
this.emit('response', response);
return response;
Request.prototype._emitResponse = function(body, files) {
const response = new Response(this);
this.response = response;
response.redirects = this._redirectList;
if (undefined !== body) {
response.body = body;
}
response.files = files;
this.emit('response', response);
return response;
};
Request.prototype.end = function(fn){
Request.prototype.end = function(fn) {
this.request();

@@ -769,3 +782,5 @@ debug('%s %s', this.method, this.url);

if (this._endCalled) {
console.warn("Warning: .end() was called twice. This is not supported in superagent");
console.warn(
'Warning: .end() was called twice. This is not supported in superagent'
);
}

@@ -781,7 +796,6 @@ this._endCalled = true;

Request.prototype._end = function() {
var self = this;
var data = this._data;
var req = this.req;
var buffer = this._buffer;
var method = this.method;
let data = this._data;
const req = this.req;
let buffer = this._buffer;
const method = this.method;

@@ -794,6 +808,6 @@ this._setTimeouts();

if ('string' != typeof data) {
var contentType = req.getHeader('Content-Type')
let contentType = req.getHeader('Content-Type');
// Parse out just the content type from the header (ignore the charset)
if (contentType) contentType = contentType.split(';')[0]
var serialize = exports.serialize[contentType];
if (contentType) contentType = contentType.split(';')[0];
let serialize = exports.serialize[contentType];
if (!serialize && isJSON(contentType)) {

@@ -812,31 +826,31 @@ serialize = exports.serialize['application/json'];

// response
req.once('response', function(res){
debug('%s %s -> %s', self.method, self.url, res.statusCode);
req.once('response', res => {
debug('%s %s -> %s', this.method, this.url, res.statusCode);
if (self._responseTimeoutTimer) {
clearTimeout(self._responseTimeoutTimer);
if (this._responseTimeoutTimer) {
clearTimeout(this._responseTimeoutTimer);
}
if (self.piped) {
if (this.piped) {
return;
}
var max = self._maxRedirects;
var mime = utils.type(res.headers['content-type'] || '') || 'text/plain';
var type = mime.split('/')[0];
var multipart = 'multipart' == type;
var redirect = isRedirect(res.statusCode);
var parser = self._parser;
var responseType = self._responseType;
const max = this._maxRedirects;
const mime = utils.type(res.headers['content-type'] || '') || 'text/plain';
const type = mime.split('/')[0];
const multipart = 'multipart' == type;
const redirect = isRedirect(res.statusCode);
let parser = this._parser;
const responseType = this._responseType;
self.res = res;
this.res = res;
// redirect
if (redirect && self._redirects++ != max) {
return self._redirect(res);
if (redirect && this._redirects++ != max) {
return this._redirect(res);
}
if ('HEAD' == self.method) {
self.emit('end');
self.callback(null, self._emitResponse());
if ('HEAD' == this.method) {
this.emit('end');
this.callback(null, this._emitResponse());
return;

@@ -846,3 +860,3 @@ }

// zlib support
if (self._shouldUnzip(res)) {
if (this._shouldUnzip(res)) {
unzip(req, res);

@@ -856,3 +870,3 @@ }

} else if (multipart) {
var form = new formidable.IncomingForm();
const form = new formidable.IncomingForm();
parser = form.parse.bind(form);

@@ -879,11 +893,11 @@ buffer = true;

// by default only buffer text/*, json and messed up thing from hell
if (undefined === buffer && isText(mime) || isJSON(mime)) {
if ((undefined === buffer && isText(mime)) || isJSON(mime)) {
buffer = true;
}
var parserHandlesEnd = false;
let parserHandlesEnd = false;
if (buffer) {
// Protectiona against zip bombs and other nuisance
let responseBytesLeft = self._maxResponseSize || 200000000;
res.on('data', function(buf) {
let responseBytesLeft = this._maxResponseSize || 200000000;
res.on('data', buf => {
responseBytesLeft -= buf.byteLength || buf.length;

@@ -909,4 +923,4 @@ if (responseBytesLeft < 0) {

parser(res, function(err, obj, files) {
if (self.timedout) {
parser(res, (err, obj, files) => {
if (this.timedout) {
// Timeout has already handled all callbacks

@@ -918,13 +932,13 @@ return;

// even if it doesn't parse.
if (err && !self._aborted) {
return self.callback(err);
if (err && !this._aborted) {
return this.callback(err);
}
if (parserHandlesEnd) {
self.emit('end');
self.callback(null, self._emitResponse(obj, files));
this.emit('end');
this.callback(null, this._emitResponse(obj, files));
}
});
} catch (err) {
self.callback(err);
this.callback(err);
return;

@@ -934,13 +948,13 @@ }

self.res = res;
this.res = res;
// unbuffered
if (!buffer) {
debug('unbuffered %s %s', self.method, self.url);
self.callback(null, self._emitResponse());
if (multipart) return // allow multipart to handle end event
res.once('end', function(){
debug('end %s %s', self.method, self.url);
self.emit('end');
})
debug('unbuffered %s %s', this.method, this.url);
this.callback(null, this._emitResponse());
if (multipart) return; // allow multipart to handle end event
res.once('end', () => {
debug('end %s %s', this.method, this.url);
this.emit('end');
});
return;

@@ -950,12 +964,13 @@ }

// terminating events
res.once('error', function(err){
res.once('error', err => {
parserHandlesEnd = false;
self.callback(err, null);
this.callback(err, null);
});
if (!parserHandlesEnd) res.once('end', function(){
debug('end %s %s', self.method, self.url);
// TODO: unless buffering emit earlier to stream
self.emit('end');
self.callback(null, self._emitResponse());
});
if (!parserHandlesEnd)
res.once('end', () => {
debug('end %s %s', this.method, this.url);
// TODO: unless buffering emit earlier to stream
this.emit('end');
this.callback(null, this._emitResponse());
});
});

@@ -966,8 +981,8 @@

// if a FormData instance got created, then we send that as the request body
var formData = this._formData;
const formData = this._formData;
if (formData) {
// set headers
var headers = formData.getHeaders();
for (var i in headers) {
const headers = formData.getHeaders();
for (const i in headers) {
debug('setting FormData header: "%s: %s"', i, headers[i]);

@@ -978,3 +993,3 @@ req.setHeader(i, headers[i]);

// attempt to get "Content-Length" header
formData.getLength(function(err, length) {
formData.getLength((err, length) => {
// TODO: Add chunked encoding when no length (if err)

@@ -987,15 +1002,15 @@

var getProgressMonitor = function () {
var lengthComputable = true;
var total = req.getHeader('Content-Length');
var loaded = 0;
const getProgressMonitor = () => {
const lengthComputable = true;
const total = req.getHeader('Content-Length');
let loaded = 0;
var progress = new Stream.Transform();
progress._transform = function (chunk, encoding, cb) {
const progress = new Stream.Transform();
progress._transform = (chunk, encoding, cb) => {
loaded += chunk.length;
self.emit('progress', {
this.emit('progress', {
direction: 'upload',
lengthComputable: lengthComputable,
loaded: loaded,
total: total
lengthComputable,
loaded,
total,
});

@@ -1018,3 +1033,3 @@ cb(null, chunk);

*/
Request.prototype._shouldUnzip = function(res){
Request.prototype._shouldUnzip = res => {
if (res.statusCode === 204 || res.statusCode === 304) {

@@ -1043,10 +1058,10 @@ // These aren't supposed to have any body

}
methods.forEach(function(method){
var name = method;
methods.forEach(method => {
const name = method;
method = 'del' == method ? 'delete' : method;
method = method.toUpperCase();
request[name] = function(url, data, fn){
var req = request(method, url);
if ('function' == typeof data) fn = data, data = null;
request[name] = (url, data, fn) => {
const req = request(method, url);
if ('function' == typeof data) (fn = data), (data = null);
if (data) {

@@ -1073,12 +1088,11 @@ if (method === 'GET' || method === 'HEAD') {

function isText(mime) {
var parts = mime.split('/');
var type = parts[0];
var subtype = parts[1];
const parts = mime.split('/');
const type = parts[0];
const subtype = parts[1];
return 'text' == type
|| 'x-www-form-urlencoded' == subtype;
return 'text' == type || 'x-www-form-urlencoded' == subtype;
}
function isImageOrVideo(mime) {
var type = mime.split('/')[0];
const type = mime.split('/')[0];

@@ -1085,0 +1099,0 @@ return 'image' == type || 'video' == type;

'use strict';
module.exports = function(res, fn){
var data = []; // Binary data needs binary storage
module.exports = (res, fn) => {
const data = []; // Binary data needs binary storage
res.on('data', function(chunk){
data.push(chunk);
res.on('data', chunk => {
data.push(chunk);
});
res.on('end', function () {
fn(null, Buffer.concat(data));
res.on('end', () => {
fn(null, Buffer.concat(data));
});
};

@@ -7,5 +7,5 @@ 'use strict';

var binary = require('./image');
const binary = require('./image');
exports['application/octet-stream'] = binary;
exports['application/pdf'] = binary;
exports.image = binary;

@@ -6,4 +6,6 @@ 'use strict';

res.setEncoding('utf8');
res.on('data', function(chunk){ res.text += chunk;});
res.on('end', function(){
res.on('data', chunk => {
res.text += chunk;
});
res.on('end', () => {
try {

@@ -10,0 +12,0 @@ var body = res.text && JSON.parse(res.text);

@@ -6,4 +6,6 @@ 'use strict';

res.setEncoding('utf8');
res.on('data', function(chunk){ res.text += chunk; });
res.on('data', chunk => {
res.text += chunk;
});
res.on('end', fn);
};

@@ -7,3 +7,3 @@ 'use strict';

var qs = require('qs');
const qs = require('qs');

@@ -13,4 +13,6 @@ module.exports = function(res, fn){

res.setEncoding('ascii');
res.on('data', function(chunk){ res.text += chunk; });
res.on('end', function(){
res.on('data', chunk => {
res.text += chunk;
});
res.on('end', () => {
try {

@@ -17,0 +19,0 @@ fn(null, qs.parse(res.text));

@@ -7,5 +7,5 @@ 'use strict';

var util = require('util');
var Stream = require('stream');
var ResponseBase = require('../response-base');
const util = require('util');
const Stream = require('stream');
const ResponseBase = require('../response-base');

@@ -34,3 +34,3 @@ /**

Stream.call(this);
var res = this.res = req.res;
const res = (this.res = req.res);
this.request = req;

@@ -59,3 +59,2 @@ this.req = req.req;

/**

@@ -92,9 +91,9 @@ * Implements methods of a `ReadableStream`

Response.prototype.toError = function(){
var req = this.req;
var method = req.method;
var path = req.path;
Response.prototype.toError = function() {
const req = this.req;
const method = req.method;
const path = req.path;
var msg = 'cannot ' + method + ' ' + path + ' (' + this.status + ')';
var err = new Error(msg);
const msg = `cannot ${method} ${path} (${this.status})`;
const err = new Error(msg);
err.status = this.status;

@@ -121,3 +120,3 @@ err.text = this.text;

Response.prototype.toJSON = function(){
Response.prototype.toJSON = function() {
return {

@@ -127,4 +126,4 @@ req: this.request.toJSON(),

status: this.status,
text: this.text
text: this.text,
};
};

@@ -7,5 +7,5 @@ 'use strict';

var StringDecoder = require('string_decoder').StringDecoder;
var Stream = require('stream');
var zlib = require('zlib');
const StringDecoder = require('string_decoder').StringDecoder;
const Stream = require('stream');
const zlib = require('zlib');

@@ -20,6 +20,6 @@ /**

exports.unzip = function(req, res){
var unzip = zlib.createUnzip();
var stream = new Stream;
var decoder;
exports.unzip = (req, res) => {
const unzip = zlib.createUnzip();
const stream = new Stream();
let decoder;

@@ -29,4 +29,5 @@ // make node responseOnEnd() happy

unzip.on('error', function(err){
if (err && err.code === 'Z_BUF_ERROR') { // unexpected end of file is ignored by browsers and curl
unzip.on('error', err => {
if (err && err.code === 'Z_BUF_ERROR') {
// unexpected end of file is ignored by browsers and curl
stream.emit('end');

@@ -42,3 +43,3 @@ return;

// override `setEncoding` to capture encoding
res.setEncoding = function(type){
res.setEncoding = type => {
decoder = new StringDecoder(type);

@@ -48,5 +49,5 @@ };

// decode upon decompressing with captured encoding
unzip.on('data', function(buf){
unzip.on('data', buf => {
if (decoder) {
var str = decoder.write(buf);
const str = decoder.write(buf);
if (str.length) stream.emit('data', str);

@@ -58,3 +59,3 @@ } else {

unzip.on('end', function(){
unzip.on('end', () => {
stream.emit('end');

@@ -64,4 +65,4 @@ });

// override `on` to capture data listeners
var _on = res.on;
res.on = function(type, fn){
const _on = res.on;
res.on = function(type, fn) {
if ('data' == type || 'end' == type) {

@@ -68,0 +69,0 @@ stream.on(type, fn);

@@ -195,5 +195,6 @@ 'use strict';

}
this._fullfilledPromise = new Promise(function(innerResolve, innerReject){
self.end(function(err, res){
if (err) innerReject(err); else innerResolve(res);
this._fullfilledPromise = new Promise(function(innerResolve, innerReject) {
self.end(function(err, res) {
if (err) innerReject(err);
else innerResolve(res);
});

@@ -203,3 +204,3 @@ });

return this._fullfilledPromise.then(resolve, reject);
}
};

@@ -217,3 +218,3 @@ RequestBase.prototype.catch = function(cb) {

return this;
}
};

@@ -238,3 +239,2 @@ RequestBase.prototype.ok = function(cb) {

/**

@@ -338,5 +338,4 @@ * Get request header `field`.

RequestBase.prototype.field = function(name, val) {
// name should be either a string or an object.
if (null === name || undefined === name) {
if (null === name || undefined === name) {
throw new Error('.field(name, val) name can not be empty');

@@ -392,2 +391,20 @@ }

RequestBase.prototype._auth = function(user, pass, options, base64Encoder) {
switch (options.type) {
case 'basic':
this.set('Authorization', 'Basic ' + base64Encoder(user + ':' + pass));
break;
case 'auto':
this.username = user;
this.password = pass;
break;
case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' })
this.set('Authorization', 'Bearer ' + user);
break;
}
return this;
};
/**

@@ -404,5 +421,5 @@ * Enable transmission of cookies with x-domain requests.

RequestBase.prototype.withCredentials = function(on){
RequestBase.prototype.withCredentials = function(on) {
// This is browser-only functionality. Node side is no-op.
if(on==undefined) on = true;
if (on == undefined) on = true;
this._withCredentials = on;

@@ -449,3 +466,3 @@ return this;

RequestBase.prototype.toJSON = function(){
RequestBase.prototype.toJSON = function() {
return {

@@ -455,7 +472,6 @@ method: this.method,

data: this._data,
headers: this._header
headers: this._header,
};
};
/**

@@ -548,3 +564,2 @@ * Send `data` as the request body, defaulting the `.type()` to "json" when

/**

@@ -647,2 +662,2 @@ * Sort `querystring` by the sort function

}
}
};

@@ -48,4 +48,4 @@ 'use strict';

ResponseBase.prototype.get = function(field){
return this.header[field.toLowerCase()];
ResponseBase.prototype.get = function(field) {
return this.header[field.toLowerCase()];
};

@@ -52,0 +52,0 @@

{
"name": "superagent",
"version": "3.7.0",
"version": "3.8.0-alpha.1",
"description": "elegant & feature rich browser / node HTTP with a fluent API",

@@ -5,0 +5,0 @@ "scripts": {

(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.superagent = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
function Agent() {
this._defaults = [];
}
["use", "on", "once", "set", "query", "type", "accept", "auth", "withCredentials", "sortQuery", "retry", "ok", "redirects",
"timeout", "buffer", "serialize", "parse", "ca", "key", "pfx", "cert"].forEach(function(fn) {
/** Default setting for all requests from this agent */
Agent.prototype[fn] = function(/*varargs*/) {
this._defaults.push({fn:fn, arguments:arguments});
return this;
}
});
Agent.prototype._setDefaults = function(req) {
this._defaults.forEach(function(def) {
req[def.fn].apply(req, def.arguments);
});
};
module.exports = Agent;
},{}],2:[function(require,module,exports){
'use strict';

@@ -18,3 +40,3 @@

},{}],2:[function(require,module,exports){
},{}],3:[function(require,module,exports){
'use strict';

@@ -214,5 +236,6 @@

}
this._fullfilledPromise = new Promise(function(innerResolve, innerReject){
self.end(function(err, res){
if (err) innerReject(err); else innerResolve(res);
this._fullfilledPromise = new Promise(function(innerResolve, innerReject) {
self.end(function(err, res) {
if (err) innerReject(err);
else innerResolve(res);
});

@@ -222,3 +245,3 @@ });

return this._fullfilledPromise.then(resolve, reject);
}
};

@@ -236,3 +259,3 @@ RequestBase.prototype.catch = function(cb) {

return this;
}
};

@@ -257,3 +280,2 @@ RequestBase.prototype.ok = function(cb) {

/**

@@ -357,5 +379,4 @@ * Get request header `field`.

RequestBase.prototype.field = function(name, val) {
// name should be either a string or an object.
if (null === name || undefined === name) {
if (null === name || undefined === name) {
throw new Error('.field(name, val) name can not be empty');

@@ -411,2 +432,20 @@ }

RequestBase.prototype._auth = function(user, pass, options, base64Encoder) {
switch (options.type) {
case 'basic':
this.set('Authorization', 'Basic ' + base64Encoder(user + ':' + pass));
break;
case 'auto':
this.username = user;
this.password = pass;
break;
case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' })
this.set('Authorization', 'Bearer ' + user);
break;
}
return this;
};
/**

@@ -423,5 +462,5 @@ * Enable transmission of cookies with x-domain requests.

RequestBase.prototype.withCredentials = function(on){
RequestBase.prototype.withCredentials = function(on) {
// This is browser-only functionality. Node side is no-op.
if(on==undefined) on = true;
if (on == undefined) on = true;
this._withCredentials = on;

@@ -468,3 +507,3 @@ return this;

RequestBase.prototype.toJSON = function(){
RequestBase.prototype.toJSON = function() {
return {

@@ -474,7 +513,6 @@ method: this.method,

data: this._data,
headers: this._header
headers: this._header,
};
};
/**

@@ -567,3 +605,2 @@ * Send `data` as the request body, defaulting the `.type()` to "json" when

/**

@@ -666,5 +703,5 @@ * Sort `querystring` by the sort function

}
}
};
},{"./is-object":1}],3:[function(require,module,exports){
},{"./is-object":2}],4:[function(require,module,exports){
'use strict';

@@ -717,4 +754,4 @@

ResponseBase.prototype.get = function(field){
return this.header[field.toLowerCase()];
ResponseBase.prototype.get = function(field) {
return this.header[field.toLowerCase()];
};

@@ -806,3 +843,3 @@

},{"./utils":5}],4:[function(require,module,exports){
},{"./utils":6}],5:[function(require,module,exports){
'use strict';

@@ -834,3 +871,3 @@

},{}],5:[function(require,module,exports){
},{}],6:[function(require,module,exports){
'use strict';

@@ -906,3 +943,3 @@

},{}],6:[function(require,module,exports){
},{}],7:[function(require,module,exports){

@@ -1072,3 +1109,3 @@ /**

},{}],7:[function(require,module,exports){
},{}],8:[function(require,module,exports){
/**

@@ -1092,2 +1129,3 @@ * Root reference for iframes.

var ResponseBase = require('./response-base');
var Agent = require('./agent-base');
var shouldRetry = require('./should-retry');

@@ -1200,5 +1238,5 @@

request.serializeObject = serialize;
request.serializeObject = serialize;
/**
/**
* Parse the given x-www-form-urlencoded `str`.

@@ -1262,8 +1300,8 @@ *

request.serialize = {
'application/x-www-form-urlencoded': serialize,
'application/json': JSON.stringify
};
request.serialize = {
'application/x-www-form-urlencoded': serialize,
'application/json': JSON.stringify,
};
/**
/**
* Default parsers.

@@ -1279,3 +1317,3 @@ *

'application/x-www-form-urlencoded': parseString,
'application/json': JSON.parse
'application/json': JSON.parse,
};

@@ -1383,3 +1421,3 @@

if (status === 1223) {
status = 204;
status = 204;
}

@@ -1416,5 +1454,5 @@ this._setStatusProperties(status);

Response.prototype._parseBody = function(str){
Response.prototype._parseBody = function(str) {
var parse = request.parse[this.type];
if(this.req._parser) {
if (this.req._parser) {
return this.req._parser(this, str);

@@ -1590,4 +1628,6 @@ }

Request.prototype.auth = function(user, pass, options){
if (typeof pass === 'object' && pass !== null) { // pass is optional and can substitute for options
if (1 === arguments.length) pass = '';
if (typeof pass === 'object' && pass !== null) { // pass is optional and can be replaced with options
options = pass;
pass = '';
}

@@ -1597,20 +1637,13 @@ if (!options) {

type: 'function' === typeof btoa ? 'basic' : 'auto',
}
};
}
switch (options.type) {
case 'basic':
this.set('Authorization', 'Basic ' + btoa(user + ':' + pass));
break;
var encoder = function(string) {
if ('function' === typeof btoa) {
return btoa(string);
}
throw new Error('Cannot use basic auth, btoa is not a function');
};
case 'auto':
this.username = user;
this.password = pass;
break;
case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' })
this.set('Authorization', 'Bearer ' + user);
break;
}
return this;
return this._auth(user, pass, options, encoder);
};

@@ -1766,3 +1799,3 @@

var self = this;
var xhr = this.xhr = request.getXHR();
var xhr = (this.xhr = request.getXHR());
var data = this._formData || this._data;

@@ -1801,3 +1834,3 @@

self.emit('progress', e);
}
};
if (this.hasListeners('progress')) {

@@ -1863,2 +1896,19 @@ try {

request.agent = function() {
return new Agent();
};
["GET", "POST", "OPTIONS", "PATCH", "PUT", "DELETE"].forEach(function(method) {
Agent.prototype[method.toLowerCase()] = function(url, fn) {
var req = new request.Request(method, url);
this._setDefaults(req);
if (fn) {
req.end(fn);
}
return req;
};
});
Agent.prototype.del = Agent.prototype['delete'];
/**

@@ -1874,5 +1924,5 @@ * GET `url` with optional callback `fn(res)`.

request.get = function(url, data, fn){
request.get = function(url, data, fn) {
var req = request('GET', url);
if ('function' == typeof data) fn = data, data = null;
if ('function' == typeof data) (fn = data), (data = null);
if (data) req.query(data);

@@ -1893,5 +1943,5 @@ if (fn) req.end(fn);

request.head = function(url, data, fn){
request.head = function(url, data, fn) {
var req = request('HEAD', url);
if ('function' == typeof data) fn = data, data = null;
if ('function' == typeof data) (fn = data), (data = null);
if (data) req.query(data);

@@ -1912,5 +1962,5 @@ if (fn) req.end(fn);

request.options = function(url, data, fn){
request.options = function(url, data, fn) {
var req = request('OPTIONS', url);
if ('function' == typeof data) fn = data, data = null;
if ('function' == typeof data) (fn = data), (data = null);
if (data) req.send(data);

@@ -1931,9 +1981,9 @@ if (fn) req.end(fn);

function del(url, data, fn){
function del(url, data, fn) {
var req = request('DELETE', url);
if ('function' == typeof data) fn = data, data = null;
if ('function' == typeof data) (fn = data), (data = null);
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
}

@@ -1953,5 +2003,5 @@ request['del'] = del;

request.patch = function(url, data, fn){
request.patch = function(url, data, fn) {
var req = request('PATCH', url);
if ('function' == typeof data) fn = data, data = null;
if ('function' == typeof data) (fn = data), (data = null);
if (data) req.send(data);

@@ -1972,5 +2022,5 @@ if (fn) req.end(fn);

request.post = function(url, data, fn){
request.post = function(url, data, fn) {
var req = request('POST', url);
if ('function' == typeof data) fn = data, data = null;
if ('function' == typeof data) (fn = data), (data = null);
if (data) req.send(data);

@@ -1991,5 +2041,5 @@ if (fn) req.end(fn);

request.put = function(url, data, fn){
request.put = function(url, data, fn) {
var req = request('PUT', url);
if ('function' == typeof data) fn = data, data = null;
if ('function' == typeof data) (fn = data), (data = null);
if (data) req.send(data);

@@ -2000,3 +2050,3 @@ if (fn) req.end(fn);

},{"./is-object":1,"./request-base":2,"./response-base":3,"./should-retry":4,"component-emitter":6}]},{},[7])(7)
},{"./agent-base":1,"./is-object":2,"./request-base":3,"./response-base":4,"./should-retry":5,"component-emitter":7}]},{},[8])(8)
});
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc