Socket
Socket
Sign inDemoInstall

superagent

Package Overview
Dependencies
Maintainers
1
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 0.9.7 to 0.9.8

lib/client.js

1347

build/build.js

@@ -0,1 +1,2 @@

;(function(){
/**

@@ -26,3 +27,3 @@ * Require the given path.

mod.client = mod.component = true;
mod.call(mod.exports, mod, mod.exports, require.relative(path));
mod.call(this, mod, mod.exports, require.relative(path));
}

@@ -71,3 +72,3 @@

|| require.modules[orig] && orig
|| null;
|| require.aliases[index];
};

@@ -87,4 +88,3 @@

// foo
if ('.' != path[0]) return path;
if ('.' != path.charAt(0)) return path;

@@ -143,2 +143,14 @@ curr = curr.split('/');

/**
* lastIndexOf helper.
*/
function lastIndexOf(arr, obj){
var i = arr.length;
while (i--) {
if (arr[i] === obj) return i;
}
return -1;
}
/**
* The relative require() itself.

@@ -150,4 +162,2 @@ */

path = fn.resolve(path);
var alias = require.aliases[path + '/index.js'];
if (alias) path = alias;
return require(path, parent, orig);

@@ -164,5 +174,5 @@ }

// directory
if ('.' != path[0]) {
if ('.' != path.charAt(0)) {
var segs = parent.split('/');
var i = segs.lastIndexOf('deps') + 1;
var i = lastIndexOf(segs, 'deps') + 1;
if (!i) i = 0;

@@ -334,772 +344,763 @@ path = segs.slice(0, i + 1).join('/') + '/deps/' + path;

});
require.register("superagent/index.js", function(module, exports, require){
if (typeof window != 'undefined') {
module.exports = require('./lib/superagent');
} else if (process.env.SUPERAGENT_COV) {
module.exports = require('./lib-cov/node');
} else {
module.exports = require('./lib/node');
}
require.register("superagent/lib/client.js", function(module, exports, require){
});
require.register("superagent/lib/superagent.js", function(module, exports, require){
/**
* Module dependencies.
*/
/*!
* superagent
* Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
var Emitter = require('emitter');
/**
* Root reference for iframes.
*/
;(function(){
var root = 'undefined' == typeof window
? this
: window;
var Emitter = 'undefined' == typeof exports
? EventEmitter
: require('emitter');
/**
* Noop.
*/
/**
* Noop.
*/
function noop(){};
function noop(){};
/**
* Determine XHR.
*/
/**
* Determine XHR.
*/
function getXHR() {
if (window.XMLHttpRequest
&& ('file:' != window.location.protocol || !window.ActiveXObject)) {
return new XMLHttpRequest;
} else {
try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
}
return false;
function getXHR() {
if (root.XMLHttpRequest
&& ('file:' != root.location.protocol || !root.ActiveXObject)) {
return new XMLHttpRequest;
} else {
try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
}
return false;
}
/**
* Removes leading and trailing whitespace, added to support IE.
*
* @param {String} s
* @return {String}
* @api private
*/
/**
* Removes leading and trailing whitespace, added to support IE.
*
* @param {String} s
* @return {String}
* @api private
*/
var trim = ''.trim
? function(s) { return s.trim(); }
: function(s) { return s.replace(/(^\s*|\s*$)/g, ''); };
var trim = ''.trim
? function(s) { return s.trim(); }
: function(s) { return s.replace(/(^\s*|\s*$)/g, ''); };
/**
* Check if `obj` is an object.
*
* @param {Object} obj
* @return {Boolean}
* @api private
*/
/**
* Check if `obj` is an object.
*
* @param {Object} obj
* @return {Boolean}
* @api private
*/
function isObject(obj) {
return obj === Object(obj);
}
function isObject(obj) {
return obj === Object(obj);
}
/**
* Serialize the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api private
*/
/**
* Serialize the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api private
*/
function serialize(obj) {
if (!isObject(obj)) return obj;
var pairs = [];
for (var key in obj) {
pairs.push(encodeURIComponent(key)
+ '=' + encodeURIComponent(obj[key]));
}
return pairs.join('&');
function serialize(obj) {
if (!isObject(obj)) return obj;
var pairs = [];
for (var key in obj) {
pairs.push(encodeURIComponent(key)
+ '=' + encodeURIComponent(obj[key]));
}
return pairs.join('&');
}
/**
* Expose serialization method.
*/
/**
* Expose serialization method.
*/
request.serializeObject = serialize;
request.serializeObject = serialize;
/**
* Parse the given x-www-form-urlencoded `str`.
*
* @param {String} str
* @return {Object}
* @api private
*/
/**
* Parse the given x-www-form-urlencoded `str`.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parseString(str) {
var obj = {};
var pairs = str.split('&');
var parts;
var pair;
function parseString(str) {
var obj = {};
var pairs = str.split('&');
var parts;
var pair;
for (var i = 0, len = pairs.length; i < len; ++i) {
pair = pairs[i];
parts = pair.split('=');
obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
}
return obj;
for (var i = 0, len = pairs.length; i < len; ++i) {
pair = pairs[i];
parts = pair.split('=');
obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
}
/**
* Expose parser.
*/
return obj;
}
request.parseString = parseString;
/**
* Expose parser.
*/
/**
* Default MIME type map.
*
* superagent.types.xml = 'application/xml';
*
*/
request.parseString = parseString;
request.types = {
html: 'text/html',
json: 'application/json',
urlencoded: 'application/x-www-form-urlencoded',
'form': 'application/x-www-form-urlencoded',
'form-data': 'application/x-www-form-urlencoded'
};
/**
* Default MIME type map.
*
* superagent.types.xml = 'application/xml';
*
*/
/**
* Default serialization map.
*
* superagent.serialize['application/xml'] = function(obj){
* return 'generated xml here';
* };
*
*/
request.types = {
html: 'text/html',
json: 'application/json',
urlencoded: 'application/x-www-form-urlencoded',
'form': 'application/x-www-form-urlencoded',
'form-data': 'application/x-www-form-urlencoded'
};
request.serialize = {
'application/x-www-form-urlencoded': serialize,
'application/json': JSON.stringify
};
/**
* Default serialization map.
*
* superagent.serialize['application/xml'] = function(obj){
* return 'generated xml here';
* };
*
*/
/**
* Default parsers.
*
* superagent.parse['application/xml'] = function(str){
* return { object parsed from str };
* };
*
*/
request.serialize = {
'application/x-www-form-urlencoded': serialize,
'application/json': JSON.stringify
};
request.parse = {
'application/x-www-form-urlencoded': parseString,
'application/json': JSON.parse
};
/**
* Default parsers.
*
* superagent.parse['application/xml'] = function(str){
* return { object parsed from str };
* };
*
*/
/**
* Parse the given header `str` into
* an object containing the mapped fields.
*
* @param {String} str
* @return {Object}
* @api private
*/
request.parse = {
'application/x-www-form-urlencoded': parseString,
'application/json': JSON.parse
};
function parseHeader(str) {
var lines = str.split(/\r?\n/);
var fields = {};
var index;
var line;
var field;
var val;
/**
* Parse the given header `str` into
* an object containing the mapped fields.
*
* @param {String} str
* @return {Object}
* @api private
*/
lines.pop(); // trailing CRLF
function parseHeader(str) {
var lines = str.split(/\r?\n/);
var fields = {};
var index;
var line;
var field;
var val;
for (var i = 0, len = lines.length; i < len; ++i) {
line = lines[i];
index = line.indexOf(':');
field = line.slice(0, index).toLowerCase();
val = trim(line.slice(index + 1));
fields[field] = val;
}
lines.pop(); // trailing CRLF
return fields;
for (var i = 0, len = lines.length; i < len; ++i) {
line = lines[i];
index = line.indexOf(':');
field = line.slice(0, index).toLowerCase();
val = trim(line.slice(index + 1));
fields[field] = val;
}
/**
* Return the mime type for the given `str`.
*
* @param {String} str
* @return {String}
* @api private
*/
return fields;
}
function type(str){
return str.split(/ *; */).shift();
};
/**
* Return the mime type for the given `str`.
*
* @param {String} str
* @return {String}
* @api private
*/
/**
* Return header field parameters.
*
* @param {String} str
* @return {Object}
* @api private
*/
function type(str){
return str.split(/ *; */).shift();
};
function params(str){
return str.split(/ *; */).reduce(function(obj, str){
var parts = str.split(/ *= */)
, key = parts.shift()
, val = parts.shift();
/**
* Return header field parameters.
*
* @param {String} str
* @return {Object}
* @api private
*/
if (key && val) obj[key] = val;
return obj;
}, {});
};
function params(str){
return str.split(/ *; */).reduce(function(obj, str){
var parts = str.split(/ *= */)
, key = parts.shift()
, val = parts.shift();
/**
* Initialize a new `Response` with the given `xhr`.
*
* - set flags (.ok, .error, etc)
* - parse header
*
* Examples:
*
* Aliasing `superagent` as `request` is nice:
*
* request = superagent;
*
* We can use the promise-like API, or pass callbacks:
*
* request.get('/').end(function(res){});
* request.get('/', function(res){});
*
* Sending data can be chained:
*
* request
* .post('/user')
* .send({ name: 'tj' })
* .end(function(res){});
*
* Or passed to `.send()`:
*
* request
* .post('/user')
* .send({ name: 'tj' }, function(res){});
*
* Or passed to `.post()`:
*
* request
* .post('/user', { name: 'tj' })
* .end(function(res){});
*
* Or further reduced to a single call for simple cases:
*
* request
* .post('/user', { name: 'tj' }, function(res){});
*
* @param {XMLHTTPRequest} xhr
* @param {Object} options
* @api private
*/
if (key && val) obj[key] = val;
return obj;
}, {});
};
function Response(xhr, options) {
options = options || {};
this.xhr = xhr;
this.text = xhr.responseText;
this.setStatusProperties(xhr.status);
this.header = parseHeader(xhr.getAllResponseHeaders());
this.setHeaderProperties(this.header);
this.body = this.parseBody(this.text);
}
/**
* Initialize a new `Response` with the given `xhr`.
*
* - set flags (.ok, .error, etc)
* - parse header
*
* Examples:
*
* Aliasing `superagent` as `request` is nice:
*
* request = superagent;
*
* We can use the promise-like API, or pass callbacks:
*
* request.get('/').end(function(res){});
* request.get('/', function(res){});
*
* Sending data can be chained:
*
* request
* .post('/user')
* .send({ name: 'tj' })
* .end(function(res){});
*
* Or passed to `.send()`:
*
* request
* .post('/user')
* .send({ name: 'tj' }, function(res){});
*
* Or passed to `.post()`:
*
* request
* .post('/user', { name: 'tj' })
* .end(function(res){});
*
* Or further reduced to a single call for simple cases:
*
* request
* .post('/user', { name: 'tj' }, function(res){});
*
* @param {XMLHTTPRequest} xhr
* @param {Object} options
* @api private
*/
/**
* Set header related properties:
*
* - `.type` the content type without params
*
* A response of "Content-Type: text/plain; charset=utf-8"
* will provide you with a `.type` of "text/plain".
*
* @param {Object} header
* @api private
*/
function Response(xhr, options) {
options = options || {};
this.xhr = xhr;
this.text = xhr.responseText;
this.setStatusProperties(xhr.status);
this.header = parseHeader(xhr.getAllResponseHeaders());
this.setHeaderProperties(this.header);
this.body = this.parseBody(this.text);
}
Response.prototype.setHeaderProperties = function(header){
// content-type
var ct = this.header['content-type'] || '';
this.type = type(ct);
/**
* Set header related properties:
*
* - `.type` the content type without params
*
* A response of "Content-Type: text/plain; charset=utf-8"
* will provide you with a `.type` of "text/plain".
*
* @param {Object} header
* @api private
*/
// params
var obj = params(ct);
for (var key in obj) this[key] = obj[key];
};
Response.prototype.setHeaderProperties = function(header){
// content-type
var ct = this.header['content-type'] || '';
this.type = type(ct);
/**
* Parse the given body `str`.
*
* Used for auto-parsing of bodies. Parsers
* are defined on the `superagent.parse` object.
*
* @param {String} str
* @return {Mixed}
* @api private
*/
// params
var obj = params(ct);
for (var key in obj) this[key] = obj[key];
};
Response.prototype.parseBody = function(str){
var parse = request.parse[this.type];
return parse
? parse(str)
: null;
};
/**
* Parse the given body `str`.
*
* Used for auto-parsing of bodies. Parsers
* are defined on the `superagent.parse` object.
*
* @param {String} str
* @return {Mixed}
* @api private
*/
/**
* Set flags such as `.ok` based on `status`.
*
* For example a 2xx response will give you a `.ok` of __true__
* whereas 5xx will be __false__ and `.error` will be __true__. The
* `.clientError` and `.serverError` are also available to be more
* specific, and `.statusType` is the class of error ranging from 1..5
* sometimes useful for mapping respond colors etc.
*
* "sugar" properties are also defined for common cases. Currently providing:
*
* - .noContent
* - .badRequest
* - .unauthorized
* - .notAcceptable
* - .notFound
*
* @param {Number} status
* @api private
*/
Response.prototype.parseBody = function(str){
var parse = request.parse[this.type];
return parse
? parse(str)
: null;
};
Response.prototype.setStatusProperties = function(status){
var type = status / 100 | 0;
/**
* Set flags such as `.ok` based on `status`.
*
* For example a 2xx response will give you a `.ok` of __true__
* whereas 5xx will be __false__ and `.error` will be __true__. The
* `.clientError` and `.serverError` are also available to be more
* specific, and `.statusType` is the class of error ranging from 1..5
* sometimes useful for mapping respond colors etc.
*
* "sugar" properties are also defined for common cases. Currently providing:
*
* - .noContent
* - .badRequest
* - .unauthorized
* - .notAcceptable
* - .notFound
*
* @param {Number} status
* @api private
*/
// status / class
this.status = status;
this.statusType = type;
Response.prototype.setStatusProperties = function(status){
var type = status / 100 | 0;
// basics
this.info = 1 == type;
this.ok = 2 == type;
this.clientError = 4 == type;
this.serverError = 5 == type;
this.error = 4 == type || 5 == type;
// status / class
this.status = status;
this.statusType = type;
// sugar
this.accepted = 202 == status;
this.noContent = 204 == status || 1223 == status;
this.badRequest = 400 == status;
this.unauthorized = 401 == status;
this.notAcceptable = 406 == status;
this.notFound = 404 == status;
this.forbidden = 403 == status;
};
// basics
this.info = 1 == type;
this.ok = 2 == type;
this.clientError = 4 == type;
this.serverError = 5 == type;
this.error = 4 == type || 5 == type;
/**
* Expose `Response`.
*/
// sugar
this.accepted = 202 == status;
this.noContent = 204 == status || 1223 == status;
this.badRequest = 400 == status;
this.unauthorized = 401 == status;
this.notAcceptable = 406 == status;
this.notFound = 404 == status;
this.forbidden = 403 == status;
};
request.Response = Response;
/**
* Expose `Response`.
*/
/**
* Initialize a new `Request` with the given `method` and `url`.
*
* @param {String} method
* @param {String} url
* @api public
*/
function Request(method, url) {
var self = this;
Emitter.call(this);
this.method = method;
this.url = url;
this.header = {};
this.set('X-Requested-With', 'XMLHttpRequest');
this.on('end', function(){
self.callback(new Response(self.xhr));
});
}
request.Response = Response;
/**
* Inherit from `Emitter.prototype`.
*/
/**
* Initialize a new `Request` with the given `method` and `url`.
*
* @param {String} method
* @param {String} url
* @api public
*/
Request.prototype = new Emitter;
Request.prototype.constructor = Request;
function Request(method, url) {
var self = this;
Emitter.call(this);
this.method = method;
this.url = url;
this.header = {};
this.set('X-Requested-With', 'XMLHttpRequest');
this.on('end', function(){
self.callback(new Response(self.xhr));
});
}
/**
* Abort the request.
*
* @return {Request}
* @api public
*/
/**
* Inherit from `Emitter.prototype`.
*/
Request.prototype.abort = function(){
if (this.aborted) return;
this.xhr.abort();
this.emit('abort');
this.aborted = true;
return this;
};
Request.prototype = new Emitter;
Request.prototype.constructor = Request;
/**
* Set header `field` to `val`, or multiple fields with one object.
*
* Examples:
*
* req.get('/')
* .set('Accept', 'application/json')
* .set('X-API-Key', 'foobar')
* .end(callback);
*
* req.get('/')
* .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
* .end(callback);
*
* @param {String|Object} field
* @param {String} val
* @return {Request} for chaining
* @api public
*/
/**
* Abort the request.
*
* @return {Request}
* @api public
*/
Request.prototype.set = function(field, val){
if (isObject(field)) {
for (var key in field) {
this.set(key, field[key]);
}
return this;
Request.prototype.abort = function(){
if (this.aborted) return;
this.xhr.abort();
this.emit('abort');
this.aborted = true;
return this;
};
/**
* Set header `field` to `val`, or multiple fields with one object.
*
* Examples:
*
* req.get('/')
* .set('Accept', 'application/json')
* .set('X-API-Key', 'foobar')
* .end(callback);
*
* req.get('/')
* .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
* .end(callback);
*
* @param {String|Object} field
* @param {String} val
* @return {Request} for chaining
* @api public
*/
Request.prototype.set = function(field, val){
if (isObject(field)) {
for (var key in field) {
this.set(key, field[key]);
}
this.header[field.toLowerCase()] = val;
return this;
};
}
this.header[field.toLowerCase()] = val;
return this;
};
/**
* Set Content-Type to `type`, mapping values from `request.types`.
*
* Examples:
*
* superagent.types.xml = 'application/xml';
*
* request.post('/')
* .type('xml')
* .send(xmlstring)
* .end(callback);
*
* request.post('/')
* .type('application/xml')
* .send(xmlstring)
* .end(callback);
*
* @param {String} type
* @return {Request} for chaining
* @api public
*/
/**
* Set Content-Type to `type`, mapping values from `request.types`.
*
* Examples:
*
* superagent.types.xml = 'application/xml';
*
* request.post('/')
* .type('xml')
* .send(xmlstring)
* .end(callback);
*
* request.post('/')
* .type('application/xml')
* .send(xmlstring)
* .end(callback);
*
* @param {String} type
* @return {Request} for chaining
* @api public
*/
Request.prototype.type = function(type){
this.set('Content-Type', request.types[type] || type);
return this;
};
Request.prototype.type = function(type){
this.set('Content-Type', request.types[type] || type);
return this;
};
/**
* Add `obj` to the query-string, later formatted
* in `.end()`.
*
* @param {Object} obj
* @return {Request} for chaining
* @api public
*/
/**
* Add `obj` to the query-string, later formatted
* in `.end()`.
*
* @param {Object} obj
* @return {Request} for chaining
* @api public
*/
Request.prototype.query = function(obj){
this._query = this._query || {};
for (var key in obj) {
this._query[key] = obj[key];
}
return this;
};
Request.prototype.query = function(obj){
this._query = this._query || {};
for (var key in obj) {
this._query[key] = obj[key];
}
return this;
};
/**
* Send `data`, defaulting the `.type()` to "json" when
* an object is given.
*
* Examples:
*
* // querystring
* request.get('/search')
* .end(callback)
*
* // multiple data "writes"
* request.get('/search')
* .send({ search: 'query' })
* .send({ range: '1..5' })
* .send({ order: 'desc' })
* .end(callback)
*
* // manual json
* request.post('/user')
* .type('json')
* .send('{"name":"tj"})
* .end(callback)
*
* // auto json
* request.post('/user')
* .send({ name: 'tj' })
* .end(callback)
*
* // manual x-www-form-urlencoded
* request.post('/user')
* .type('form')
* .send('name=tj')
* .end(callback)
*
* // auto x-www-form-urlencoded
* request.post('/user')
* .type('form')
* .send({ name: 'tj' })
* .end(callback)
*
* // defaults to x-www-form-urlencoded
* request.post('/user')
* .send('name=tobi')
* .send('species=ferret')
* .end(callback)
*
* @param {String|Object} data
* @return {Request} for chaining
* @api public
*/
/**
* Send `data`, defaulting the `.type()` to "json" when
* an object is given.
*
* Examples:
*
* // querystring
* request.get('/search')
* .end(callback)
*
* // multiple data "writes"
* request.get('/search')
* .send({ search: 'query' })
* .send({ range: '1..5' })
* .send({ order: 'desc' })
* .end(callback)
*
* // manual json
* request.post('/user')
* .type('json')
* .send('{"name":"tj"})
* .end(callback)
*
* // auto json
* request.post('/user')
* .send({ name: 'tj' })
* .end(callback)
*
* // manual x-www-form-urlencoded
* request.post('/user')
* .type('form')
* .send('name=tj')
* .end(callback)
*
* // auto x-www-form-urlencoded
* request.post('/user')
* .type('form')
* .send({ name: 'tj' })
* .end(callback)
*
* // defaults to x-www-form-urlencoded
* request.post('/user')
* .send('name=tobi')
* .send('species=ferret')
* .end(callback)
*
* @param {String|Object} data
* @return {Request} for chaining
* @api public
*/
Request.prototype.send = function(data){
var obj = isObject(data);
var type = this.header['content-type'];
Request.prototype.send = function(data){
var obj = isObject(data);
var type = this.header['content-type'];
// merge
if (obj && isObject(this._data)) {
for (var key in data) {
this._data[key] = data[key];
}
} else if ('string' == typeof data) {
if (!type) this.type('form');
type = this.header['content-type'];
if ('application/x-www-form-urlencoded' == type) {
this._data = this._data
? this._data + '&' + data
: data;
} else {
this._data = (this._data || '') + data;
}
// merge
if (obj && isObject(this._data)) {
for (var key in data) {
this._data[key] = data[key];
}
} else if ('string' == typeof data) {
if (!type) this.type('form');
type = this.header['content-type'];
if ('application/x-www-form-urlencoded' == type) {
this._data = this._data
? this._data + '&' + data
: data;
} else {
this._data = data;
this._data = (this._data || '') + data;
}
} else {
this._data = data;
}
if (!obj) return this;
if (!type) this.type('json');
return this;
};
if (!obj) return this;
if (!type) this.type('json');
return this;
};
/**
* Initiate request, invoking callback `fn(res)`
* with an instanceof `Response`.
*
* @param {Function} fn
* @return {Request} for chaining
* @api public
*/
/**
* Initiate request, invoking callback `fn(res)`
* with an instanceof `Response`.
*
* @param {Function} fn
* @return {Request} for chaining
* @api public
*/
Request.prototype.end = function(fn){
var self = this;
var xhr = this.xhr = getXHR();
var query = this._query;
var data = this._data;
Request.prototype.end = function(fn){
var self = this;
var xhr = this.xhr = getXHR();
var query = this._query;
var data = this._data;
// store callback
this.callback = fn || noop;
// store callback
this.callback = fn || noop;
// state change
xhr.onreadystatechange = function(){
if (4 == xhr.readyState) self.emit('end');
};
// state change
xhr.onreadystatechange = function(){
if (4 == xhr.readyState) self.emit('end');
};
// querystring
if (query) {
query = request.serializeObject(query);
this.url += ~this.url.indexOf('?')
? '&' + query
: '?' + query;
}
// querystring
if (query) {
query = request.serializeObject(query);
this.url += ~this.url.indexOf('?')
? '&' + query
: '?' + query;
}
// initiate request
xhr.open(this.method, this.url, true);
// initiate request
xhr.open(this.method, this.url, true);
// body
if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data) {
// serialize stuff
var serialize = request.serialize[this.header['content-type']];
if (serialize) data = serialize(data);
}
// body
if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data) {
// serialize stuff
var serialize = request.serialize[this.header['content-type']];
if (serialize) data = serialize(data);
}
// set header fields
for (var field in this.header) {
xhr.setRequestHeader(field, this.header[field]);
}
// set header fields
for (var field in this.header) {
xhr.setRequestHeader(field, this.header[field]);
}
// send stuff
xhr.send(data);
return this;
};
/**
* Expose `Request`.
*/
request.Request = Request;
// send stuff
xhr.send(data);
return this;
};
/**
* Issue a request:
*
* Examples:
*
* request('GET', '/users').end(callback)
* request('/users').end(callback)
* request('/users', callback)
*
* @param {String} method
* @param {String|Function} url or callback
* @return {Request}
* @api public
*/
/**
* Expose `Request`.
*/
function request(method, url) {
// callback
if ('function' == typeof url) {
return new Request('GET', method).end(url);
}
request.Request = Request;
// url first
if (1 == arguments.length) {
return new Request('GET', method);
}
/**
* Issue a request:
*
* Examples:
*
* request('GET', '/users').end(callback)
* request('/users').end(callback)
* request('/users', callback)
*
* @param {String} method
* @param {String|Function} url or callback
* @return {Request}
* @api public
*/
return new Request(method, url);
function request(method, url) {
// callback
if ('function' == typeof url) {
return new Request('GET', method).end(url);
}
/**
* GET `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} data
* @param {Function} fn
* @return {Request}
* @api public
*/
// url first
if (1 == arguments.length) {
return new Request('GET', method);
}
request.get = function(url, data, fn){
var req = request('GET', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.query(data);
if (fn) req.end(fn);
return req;
};
return new Request(method, url);
}
/**
* GET `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} data
* @param {Function} fn
* @return {Request}
* @api public
*/
/**
* GET `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} data
* @param {Function} fn
* @return {Request}
* @api public
*/
request.head = function(url, data, fn){
var req = request('HEAD', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
request.get = function(url, data, fn){
var req = request('GET', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.query(data);
if (fn) req.end(fn);
return req;
};
/**
* DELETE `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Function} fn
* @return {Request}
* @api public
*/
/**
* GET `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} data
* @param {Function} fn
* @return {Request}
* @api public
*/
request.del = function(url, fn){
var req = request('DELETE', url);
if (fn) req.end(fn);
return req;
};
request.head = function(url, data, fn){
var req = request('HEAD', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* PATCH `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} data
* @param {Function} fn
* @return {Request}
* @api public
*/
/**
* DELETE `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Function} fn
* @return {Request}
* @api public
*/
request.patch = function(url, data, fn){
var req = request('PATCH', url);
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
request.del = function(url, fn){
var req = request('DELETE', url);
if (fn) req.end(fn);
return req;
};
/**
* POST `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} data
* @param {Function} fn
* @return {Request}
* @api public
*/
/**
* PATCH `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} data
* @param {Function} fn
* @return {Request}
* @api public
*/
request.post = function(url, data, fn){
var req = request('POST', url);
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
request.patch = function(url, data, fn){
var req = request('PATCH', url);
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* PUT `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} data
* @param {Function} fn
* @return {Request}
* @api public
*/
/**
* POST `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} data
* @param {Function} fn
* @return {Request}
* @api public
*/
request.put = function(url, data, fn){
var req = request('PUT', url);
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
request.post = function(url, data, fn){
var req = request('POST', url);
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
// expose
/**
* PUT `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} data
* @param {Function} fn
* @return {Request}
* @api public
*/
if ('undefined' == typeof exports) {
window.request = window.superagent = request;
} else {
module.exports = request;
}
request.put = function(url, data, fn){
var req = request('PUT', url);
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
})();
/**
* Expose `request`.
*/
module.exports = request;
});
require.alias("component-emitter/index.js", "superagent/deps/emitter/index.js");
require.alias("superagent/lib/client.js", "superagent/index.js");
window.superagent = require("superagent");
})();

@@ -6,7 +6,16 @@ {

"version": "0.9.6",
"keywords": ["http", "ajax", "request", "agent"],
"scripts": ["index.js", "lib/superagent.js"],
"keywords": [
"http",
"ajax",
"request",
"agent"
],
"scripts": [
"lib/client.js"
],
"main": "lib/client.js",
"dependencies": {
"component/emitter": "0.0.6"
}
}
},
"license": "MIT"
}
0.9.8 / 2012-11-03
==================
* add emission of error from `Request#callback()`
* add a better fix for nodes weird socket hang up error
* add PUT/POST/PATCH data support to client short-hand functions
* add .license property to component.json
* change client portion to build using component(1)
* fix GET body support [guille]
0.9.7 / 2012-10-19

@@ -3,0 +13,0 @@ ==================

@@ -520,4 +520,11 @@

req.on('drain', function(){ self.emit('drain'); });
req.on('error', function(err){ self.emit('error', err); });
req.on('error', function(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;
self.emit('error', err);
});
// auth

@@ -548,17 +555,13 @@ if (url.auth) {

Request.prototype.callback = function(err, res){
if (this._finished) return;
var fn = this._callback;
// flag as finished so we dont
// get double-callbacks
// flag as finished so that
// timeouts may be ignored
this._finished = true;
// ignore errors, at this point
// they dont matter anymore
this.on('error', noop);
// invoke callback
if (2 == fn.length) return fn(err, res);
fn(res); // TODO: emit error
if (err) return this.emit('error', err);
fn(res);
};

@@ -589,5 +592,7 @@

this._timer = setTimeout(function(){
if (self._finished) return;
var err = new Error('timeout of ' + timeout + 'ms exceeded');
err.timeout = timeout;
self.callback(err);
self._aborted = true;
req.abort();

@@ -598,18 +603,13 @@ }, timeout);

// body
switch (method) {
case 'GET':
case 'HEAD':
break;
default:
if (req._headerSent) break;
// serialize stuff
if ('string' != typeof data) {
var serialize = exports.serialize[req.getHeader('Content-Type')];
if (serialize) data = serialize(data);
}
if ('HEAD' != method && !req._headerSent) {
// serialize stuff
if ('string' != typeof data) {
var serialize = exports.serialize[req.getHeader('Content-Type')];
if (serialize) data = serialize(data);
}
// content-length
if (data && !req.getHeader('Content-Length')) {
this.set('Content-Length', Buffer.byteLength(data));
}
// content-length
if (data && !req.getHeader('Content-Length')) {
this.set('Content-Length', Buffer.byteLength(data));
}
}

@@ -620,3 +620,4 @@

var max = self._maxRedirects
, type = (res.headers['content-type'] || '').split(';')[0].split('/')
, mime = utils.type(res.headers['content-type'] || '')
, type = mime.split('/')
, subtype = type[1]

@@ -660,14 +661,15 @@ , type = type[0]

// and messed up thing from hell
var text = 'text' == type || 'json' == subtype || 'x-www-form-urlencoded' == subtype;
var text = isText(mime);
if (null == buffer && text) buffer = true;
// parser
var parse = 'text' == type
? exports.parse.text
: exports.parse[mime];
// buffered response
if (buffer) {
var parse = 'text' == type
? exports.parse.text
: exports.parse[utils.type(res.headers['content-type'] || '')];
if (buffer) parse = parse || exports.parse.text;
// default for buffering
parse = parse || exports.parse.text;
// parse
if (parse) {
parse(res, function(err, obj){

@@ -802,2 +804,20 @@ // TODO: handle error

/**
* Check if `mime` is text and should be buffered.
*
* @param {String} mime
* @return {Boolean}
* @api public
*/
function isText(mime) {
var parts = mime.split('/');
var type = parts[0];
var subtype = parts[1];
return 'text' == type
|| 'json' == subtype
|| 'x-www-form-urlencoded' == subtype;
}
/**
* Check if we should follow the redirect `code`.

@@ -804,0 +824,0 @@ *

{
"name": "superagent",
"version": "0.9.7",
"version": "0.9.8",
"description": "elegant & feature rich browser / node HTTP with a fluent API",

@@ -23,3 +23,3 @@ "keywords": [

"mime": "1.2.5",
"emitter-component": "0.0.5",
"emitter-component": "0.0.6",
"methods": "0.0.1",

@@ -35,6 +35,6 @@ "cookiejar": "1.3.0"

"scripts": {
"superagent": "lib/superagent.js"
"superagent": "lib/client.js"
}
},
"main": "index",
"main": "lib/node",
"engines": {

@@ -41,0 +41,0 @@ "node": "*"

var request = require('./');
console = { log: print }
request
.get('http://othstatic.propertycdn.com/clean/js/load.v5.6.4.js')
.set('Accept-Encoding', 'gzip')
.end(function(res){
console.log(res.header['content-encoding']);
res.on('data', function(chunk){
console.log(chunk.toString());
}).on('end', function(){
console.log('end');
});
})
// function socket() {
// var input = ['foo', 'bar', 'baz', null];
// var output = [];
//
// for (var i = 0, len = input.length; i < len; ++i) {
// out = yield input[i];
// if (out) output.push(out), --i;
// }
//
// yield output.join(' ');
// }
//
// var sock = socket();
// var chunk;
//
// while (chunk = sock.next()) {
// sock.send(chunk.toUpperCase());
// sock.send(chunk.toUpperCase());
// sock.send(chunk.toUpperCase());
// }
//
// console.log(sock.next());
// generators vs symetric vs asym vs shallow?
function fiber(fn) {
var g = fn();
g.next();
g.next();
}
function sleep(ms) {
setTimeout(function(){
yield
}, ms);
}
fiber(function(){
console.log('foo');
yield sleep(1000)
console.log('bar');
yield sleep(2000)
console.log('bar');
})
// fiber(function(){
// var body = yield get('https://google.com');
// console.log(body);
//
// yield sleep(5);
//
// var body = yield get('https://google.com');
// console.log(body);
// })

Sorry, the diff of this file is not supported yet

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