stratumn-sdk
Advanced tools
Comparing version 1.4.0 to 1.5.0
@@ -1,2229 +0,813 @@ | ||
(function webpackUniversalModuleDefinition(root, factory) { | ||
if(typeof exports === 'object' && typeof module === 'object') | ||
module.exports = factory(); | ||
else if(typeof define === 'function' && define.amd) | ||
define([], factory); | ||
else if(typeof exports === 'object') | ||
exports["StratumnSDK"] = factory(); | ||
else | ||
root["StratumnSDK"] = factory(); | ||
})(this, function() { | ||
return /******/ (function(modules) { // webpackBootstrap | ||
/******/ // The module cache | ||
/******/ var installedModules = {}; | ||
(function (global, factory) { | ||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : | ||
typeof define === 'function' && define.amd ? define(['exports'], factory) : | ||
(factory((global.StratumnSDK = global.StratumnSDK || {}))); | ||
}(this, (function (exports) { 'use strict'; | ||
/******/ // The require function | ||
/******/ function __webpack_require__(moduleId) { | ||
function deprecated(oldFunc, newFunc) { | ||
if (!newFunc) { | ||
console.warn("WARNING: " + oldFunc + " is deprecated."); | ||
} else { | ||
console.warn("WARNING: " + oldFunc + " is deprecated. Please use " + newFunc + " instead."); | ||
} | ||
} | ||
/******/ // Check if module is in cache | ||
/******/ if(installedModules[moduleId]) | ||
/******/ return installedModules[moduleId].exports; | ||
/** | ||
* Makes a query string. | ||
* @param {object} obj - an object of keys | ||
* @returns {string} a query string | ||
*/ | ||
function makeQueryString(obj) { | ||
var parts = Object.keys(obj).reduce(function (curr, key) { | ||
var val = Array.isArray(obj[key]) ? obj[key].join('+') : obj[key]; | ||
curr.push(encodeURIComponent(key) + '=' + encodeURIComponent(val)); | ||
return curr; | ||
}, []); | ||
/******/ // Create a new module (and put it into the cache) | ||
/******/ var module = installedModules[moduleId] = { | ||
/******/ exports: {}, | ||
/******/ id: moduleId, | ||
/******/ loaded: false | ||
/******/ }; | ||
if (parts.length) { | ||
return '?' + parts.join('&'); | ||
} | ||
/******/ // Execute the module function | ||
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); | ||
return ''; | ||
} | ||
/******/ // Flag the module as loaded | ||
/******/ module.loaded = true; | ||
function interopDefault(ex) { | ||
return ex && typeof ex === 'object' && 'default' in ex ? ex['default'] : ex; | ||
} | ||
/******/ // Return the exports of the module | ||
/******/ return module.exports; | ||
/******/ } | ||
function createCommonjsModule(fn, module) { | ||
return module = { exports: {} }, fn(module, module.exports), module.exports; | ||
} | ||
var jsonrequest = createCommonjsModule(function (module) { | ||
'use strict'; | ||
/******/ // expose the modules object (__webpack_modules__) | ||
/******/ __webpack_require__.m = modules; | ||
module.exports = { | ||
processRequest: function(req) { | ||
var | ||
contentType = req.header('Content-Type'), | ||
hasJsonContentType = contentType && | ||
contentType.indexOf('application/json') !== -1; | ||
/******/ // expose the module cache | ||
/******/ __webpack_require__.c = installedModules; | ||
if (contentType != null && !hasJsonContentType) { | ||
return; | ||
} | ||
/******/ // __webpack_public_path__ | ||
/******/ __webpack_require__.p = ""; | ||
if (req.body) { | ||
if (!contentType) { | ||
req.header('Content-Type', 'application/json'); | ||
} | ||
/******/ // Load entry module and return exports | ||
/******/ return __webpack_require__(0); | ||
/******/ }) | ||
/************************************************************************/ | ||
/******/ ([ | ||
/* 0 */ | ||
/***/ function(module, exports, __webpack_require__) { | ||
req.body = JSON.stringify(req.body); | ||
} | ||
} | ||
}; | ||
}); | ||
'use strict'; | ||
var jsonrequest$1 = interopDefault(jsonrequest); | ||
var processRequest$1 = jsonrequest.processRequest; | ||
var _getAgent = __webpack_require__(1); | ||
var require$$1 = Object.freeze({ | ||
default: jsonrequest$1, | ||
processRequest: processRequest$1 | ||
}); | ||
var _getAgent2 = _interopRequireDefault(_getAgent); | ||
var jsonresponse = createCommonjsModule(function (module) { | ||
'use strict'; | ||
var _fromSegment = __webpack_require__(17); | ||
module.exports = { | ||
processRequest: function(req) { | ||
var accept = req.header('Accept'); | ||
if (accept == null) { | ||
req.header('Accept', 'application/json'); | ||
} | ||
}, | ||
processResponse: function(res) { | ||
// Check to see if the contentype is "something/json" or | ||
// "something/somethingelse+json" | ||
if (res.contentType && /^.*\/(?:.*\+)?json(;|$)/i.test(res.contentType)) { | ||
var raw = typeof res.body === 'string' ? res.body : res.text; | ||
if (raw) { | ||
res.body = JSON.parse(raw); | ||
} | ||
} | ||
} | ||
}; | ||
}); | ||
var _fromSegment2 = _interopRequireDefault(_fromSegment); | ||
var jsonresponse$1 = interopDefault(jsonresponse); | ||
var processRequest$2 = jsonresponse.processRequest; | ||
var processResponse$1 = jsonresponse.processResponse; | ||
var _getApplication = __webpack_require__(18); | ||
var require$$0 = Object.freeze({ | ||
default: jsonresponse$1, | ||
processRequest: processRequest$2, | ||
processResponse: processResponse$1 | ||
}); | ||
var _getApplication2 = _interopRequireDefault(_getApplication); | ||
var json = createCommonjsModule(function (module) { | ||
'use strict'; | ||
var _loadLink = __webpack_require__(20); | ||
var jsonrequest = interopDefault(require$$1), | ||
jsonresponse = interopDefault(require$$0); | ||
var _loadLink2 = _interopRequireDefault(_loadLink); | ||
module.exports = { | ||
processRequest: function(req) { | ||
jsonrequest.processRequest.call(this, req); | ||
jsonresponse.processRequest.call(this, req); | ||
}, | ||
processResponse: function(res) { | ||
jsonresponse.processResponse.call(this, res); | ||
} | ||
}; | ||
}); | ||
var _config = __webpack_require__(19); | ||
var json$1 = interopDefault(json); | ||
var _config2 = _interopRequireDefault(_config); | ||
var cleanurl = createCommonjsModule(function (module) { | ||
'use strict'; | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
module.exports = { | ||
processRequest: function(req) { | ||
req.url = req.url.replace(/[^%]+/g, function(s) { | ||
return encodeURI(s); | ||
}); | ||
} | ||
}; | ||
}); | ||
module.exports = { | ||
getAgent: _getAgent2.default, | ||
fromSegment: _fromSegment2.default, | ||
var cleanurl$1 = interopDefault(cleanurl); | ||
var processRequest$3 = cleanurl.processRequest; | ||
// Deprecated. | ||
getApplication: _getApplication2.default, | ||
loadLink: _loadLink2.default, | ||
config: _config2.default | ||
}; | ||
var require$$7 = Object.freeze({ | ||
default: cleanurl$1, | ||
processRequest: processRequest$3 | ||
}); | ||
// Deprecated. | ||
var xhrBrowser = createCommonjsModule(function (module) { | ||
module.exports = window.XMLHttpRequest; | ||
}); | ||
/***/ }, | ||
/* 1 */ | ||
/***/ function(module, exports, __webpack_require__) { | ||
var xhrBrowser$1 = interopDefault(xhrBrowser); | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.default = getAgent; | ||
var require$$6 = Object.freeze({ | ||
default: xhrBrowser$1 | ||
}); | ||
var _superagent = __webpack_require__(2); | ||
var delay = createCommonjsModule(function (module) { | ||
'use strict'; | ||
var _superagent2 = _interopRequireDefault(_superagent); | ||
// Wrap a function in a `setTimeout` call. This is used to guarantee async | ||
// behavior, which can avoid unexpected errors. | ||
var _createMap = __webpack_require__(7); | ||
module.exports = function(fn) { | ||
return function() { | ||
var | ||
args = Array.prototype.slice.call(arguments, 0), | ||
newFunc = function() { | ||
return fn.apply(null, args); | ||
}; | ||
setTimeout(newFunc, 0); | ||
}; | ||
}; | ||
}); | ||
var _createMap2 = _interopRequireDefault(_createMap); | ||
var delay$1 = interopDefault(delay); | ||
var _getSegment = __webpack_require__(13); | ||
var _getSegment2 = _interopRequireDefault(_getSegment); | ||
var require$$5 = Object.freeze({ | ||
default: delay$1 | ||
}); | ||
var _findSegments = __webpack_require__(11); | ||
var request$1 = createCommonjsModule(function (module) { | ||
'use strict'; | ||
var _findSegments2 = _interopRequireDefault(_findSegments); | ||
function Request(optsOrUrl) { | ||
var opts = typeof optsOrUrl === 'string' ? {url: optsOrUrl} : optsOrUrl || {}; | ||
this.method = opts.method ? opts.method.toUpperCase() : 'GET'; | ||
this.url = opts.url; | ||
this.headers = opts.headers || {}; | ||
this.body = opts.body; | ||
this.timeout = opts.timeout || 0; | ||
this.errorOn404 = opts.errorOn404 != null ? opts.errorOn404 : true; | ||
this.onload = opts.onload; | ||
this.onerror = opts.onerror; | ||
} | ||
var _getMapIds = __webpack_require__(14); | ||
Request.prototype.abort = function() { | ||
if (this.aborted) return; | ||
this.aborted = true; | ||
this.xhr.abort(); | ||
return this; | ||
}; | ||
var _getMapIds2 = _interopRequireDefault(_getMapIds); | ||
Request.prototype.header = function(name, value) { | ||
var k; | ||
for (k in this.headers) { | ||
if (this.headers.hasOwnProperty(k)) { | ||
if (name.toLowerCase() === k.toLowerCase()) { | ||
if (arguments.length === 1) { | ||
return this.headers[k]; | ||
} | ||
var _getBranches = __webpack_require__(10); | ||
delete this.headers[k]; | ||
break; | ||
} | ||
} | ||
} | ||
if (value != null) { | ||
this.headers[name] = value; | ||
return value; | ||
} | ||
}; | ||
var _getBranches2 = _interopRequireDefault(_getBranches); | ||
var _getLink = __webpack_require__(15); | ||
module.exports = Request; | ||
}); | ||
var _getLink2 = _interopRequireDefault(_getLink); | ||
var request$2 = interopDefault(request$1); | ||
var _getMap = __webpack_require__(16); | ||
var _getMap2 = _interopRequireDefault(_getMap); | ||
var require$$1$1 = Object.freeze({ | ||
default: request$2 | ||
}); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
var index$1 = createCommonjsModule(function (module) { | ||
module.exports = extend | ||
function getAgent(url) { | ||
return new Promise(function (resolve, reject) { | ||
_superagent2.default.get(url).end(function (err, res) { | ||
if (err) { | ||
/*eslint-disable*/ | ||
err.message = res && res.body.error ? res.body.error : err.message; | ||
err.status = res && res.statusCode; | ||
/*eslint-enable*/ | ||
reject(err); | ||
return; | ||
} | ||
function extend() { | ||
var target = {} | ||
var agent = res.body; | ||
for (var i = 0; i < arguments.length; i++) { | ||
var source = arguments[i] | ||
agent.url = url; | ||
agent.createMap = _createMap2.default.bind(null, agent); | ||
agent.getSegment = _getSegment2.default.bind(null, agent); | ||
agent.findSegments = _findSegments2.default.bind(null, agent); | ||
agent.getMapIds = _getMapIds2.default.bind(null, agent); | ||
for (var key in source) { | ||
if (source.hasOwnProperty(key)) { | ||
target[key] = source[key] | ||
} | ||
} | ||
} | ||
// Deprecated. | ||
agent.getBranches = _getBranches2.default.bind(null, agent); | ||
agent.getLink = _getLink2.default.bind(null, agent); | ||
agent.getMap = _getMap2.default.bind(null, agent); | ||
return target | ||
} | ||
}); | ||
resolve(agent); | ||
}); | ||
}); | ||
} | ||
var index$2 = interopDefault(index$1); | ||
// Deprecated. | ||
/***/ }, | ||
/* 2 */ | ||
/***/ function(module, exports, __webpack_require__) { | ||
var require$$0$2 = Object.freeze({ | ||
default: index$2 | ||
}); | ||
/** | ||
* Root reference for iframes. | ||
*/ | ||
var extractResponseProps = createCommonjsModule(function (module) { | ||
'use strict'; | ||
var root; | ||
if (typeof window !== 'undefined') { // Browser window | ||
root = window; | ||
} else if (typeof self !== 'undefined') { // Web Worker | ||
root = self; | ||
} else { // Other environments | ||
console.warn("Using browser-only version of superagent in non-browser environment"); | ||
root = this; | ||
} | ||
var extend = interopDefault(require$$0$2); | ||
var Emitter = __webpack_require__(3); | ||
var requestBase = __webpack_require__(4); | ||
var isObject = __webpack_require__(5); | ||
module.exports = function(req) { | ||
var xhr = req.xhr; | ||
var props = {request: req, xhr: xhr}; | ||
/** | ||
* Noop. | ||
*/ | ||
// Try to create the response from the request. If the request was aborted, | ||
// accesssing properties of the XHR may throw an error, so we wrap in a | ||
// try/catch. | ||
try { | ||
var lines, i, m, headers = {}; | ||
if (xhr.getAllResponseHeaders) { | ||
lines = xhr.getAllResponseHeaders().split('\n'); | ||
for (i = 0; i < lines.length; i++) { | ||
if ((m = lines[i].match(/\s*([^\s]+):\s+([^\s]+)/))) { | ||
headers[m[1]] = m[2]; | ||
} | ||
} | ||
} | ||
function noop(){}; | ||
props = extend(props, { | ||
status: xhr.status, | ||
contentType: xhr.contentType || (xhr.getResponseHeader && xhr.getResponseHeader('Content-Type')), | ||
headers: headers, | ||
text: xhr.responseText, | ||
body: xhr.response || xhr.responseText | ||
}); | ||
} catch (err) {} | ||
/** | ||
* Expose `request`. | ||
*/ | ||
return props; | ||
}; | ||
}); | ||
var request = module.exports = __webpack_require__(6).bind(null, Request); | ||
var extractResponseProps$1 = interopDefault(extractResponseProps); | ||
/** | ||
* Determine XHR. | ||
*/ | ||
request.getXHR = function () { | ||
if (root.XMLHttpRequest | ||
&& (!root.location || '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) {} | ||
} | ||
throw Error("Browser-only verison of superagent could not find XHR"); | ||
}; | ||
var require$$0$1 = Object.freeze({ | ||
default: extractResponseProps$1 | ||
}); | ||
/** | ||
* Removes leading and trailing whitespace, added to support IE. | ||
* | ||
* @param {String} s | ||
* @return {String} | ||
* @api private | ||
*/ | ||
var response = createCommonjsModule(function (module) { | ||
'use strict'; | ||
var trim = ''.trim | ||
? function(s) { return s.trim(); } | ||
: function(s) { return s.replace(/(^\s*|\s*$)/g, ''); }; | ||
var Request = interopDefault(require$$1$1); | ||
var extractResponseProps = interopDefault(require$$0$1); | ||
/** | ||
* Serialize the given `obj`. | ||
* | ||
* @param {Object} obj | ||
* @return {String} | ||
* @api private | ||
*/ | ||
function Response(props) { | ||
this.request = props.request; | ||
this.xhr = props.xhr; | ||
this.headers = props.headers || {}; | ||
this.status = props.status || 0; | ||
this.text = props.text; | ||
this.body = props.body; | ||
this.contentType = props.contentType; | ||
this.isHttpError = props.status >= 400; | ||
} | ||
function serialize(obj) { | ||
if (!isObject(obj)) return obj; | ||
var pairs = []; | ||
for (var key in obj) { | ||
if (null != obj[key]) { | ||
pushEncodedKeyValuePair(pairs, key, obj[key]); | ||
} | ||
} | ||
return pairs.join('&'); | ||
} | ||
Response.prototype.header = Request.prototype.header; | ||
/** | ||
* Helps 'serialize' with serializing arrays. | ||
* Mutates the pairs array. | ||
* | ||
* @param {Array} pairs | ||
* @param {String} key | ||
* @param {Mixed} val | ||
*/ | ||
Response.fromRequest = function(req) { | ||
return new Response(extractResponseProps(req)); | ||
}; | ||
function pushEncodedKeyValuePair(pairs, key, val) { | ||
if (Array.isArray(val)) { | ||
return val.forEach(function(v) { | ||
pushEncodedKeyValuePair(pairs, key, v); | ||
}); | ||
} else if (isObject(val)) { | ||
for(var subkey in val) { | ||
pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]); | ||
} | ||
return; | ||
} | ||
pairs.push(encodeURIComponent(key) | ||
+ '=' + encodeURIComponent(val)); | ||
} | ||
/** | ||
* Expose serialization method. | ||
*/ | ||
module.exports = Response; | ||
}); | ||
request.serializeObject = serialize; | ||
var response$1 = interopDefault(response); | ||
/** | ||
* 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 pair; | ||
var pos; | ||
var require$$2 = Object.freeze({ | ||
default: response$1 | ||
}); | ||
for (var i = 0, len = pairs.length; i < len; ++i) { | ||
pair = pairs[i]; | ||
pos = pair.indexOf('='); | ||
if (pos == -1) { | ||
obj[decodeURIComponent(pair)] = ''; | ||
} else { | ||
obj[decodeURIComponent(pair.slice(0, pos))] = | ||
decodeURIComponent(pair.slice(pos + 1)); | ||
} | ||
} | ||
var error = createCommonjsModule(function (module) { | ||
'use strict'; | ||
return obj; | ||
} | ||
var Response = interopDefault(require$$2); | ||
var extractResponseProps = interopDefault(require$$0$1); | ||
var extend = interopDefault(require$$0$2); | ||
/** | ||
* Expose parser. | ||
*/ | ||
function RequestError(message, props) { | ||
var err = new Error(message); | ||
err.name = 'RequestError'; | ||
this.name = err.name; | ||
this.message = err.message; | ||
if (err.stack) { | ||
this.stack = err.stack; | ||
} | ||
request.parseString = parseString; | ||
this.toString = function() { | ||
return this.message; | ||
}; | ||
/** | ||
* Default MIME type map. | ||
* | ||
* superagent.types.xml = 'application/xml'; | ||
* | ||
*/ | ||
for (var k in props) { | ||
if (props.hasOwnProperty(k)) { | ||
this[k] = props[k]; | ||
} | ||
} | ||
} | ||
request.types = { | ||
html: 'text/html', | ||
json: 'application/json', | ||
xml: 'application/xml', | ||
urlencoded: 'application/x-www-form-urlencoded', | ||
'form': 'application/x-www-form-urlencoded', | ||
'form-data': 'application/x-www-form-urlencoded' | ||
}; | ||
RequestError.prototype = extend(Error.prototype); | ||
RequestError.prototype.constructor = RequestError; | ||
/** | ||
* Default serialization map. | ||
* | ||
* superagent.serialize['application/xml'] = function(obj){ | ||
* return 'generated xml here'; | ||
* }; | ||
* | ||
*/ | ||
RequestError.create = function(message, req, props) { | ||
var err = new RequestError(message, props); | ||
Response.call(err, extractResponseProps(req)); | ||
return err; | ||
}; | ||
request.serialize = { | ||
'application/x-www-form-urlencoded': serialize, | ||
'application/json': JSON.stringify | ||
}; | ||
module.exports = RequestError; | ||
}); | ||
/** | ||
* Default parsers. | ||
* | ||
* superagent.parse['application/xml'] = function(str){ | ||
* return { object parsed from str }; | ||
* }; | ||
* | ||
*/ | ||
var error$1 = interopDefault(error); | ||
request.parse = { | ||
'application/x-www-form-urlencoded': parseString, | ||
'application/json': JSON.parse | ||
}; | ||
/** | ||
* Parse the given header `str` into | ||
* an object containing the mapped fields. | ||
* | ||
* @param {String} str | ||
* @return {Object} | ||
* @api private | ||
*/ | ||
var require$$4 = Object.freeze({ | ||
default: error$1 | ||
}); | ||
function parseHeader(str) { | ||
var lines = str.split(/\r?\n/); | ||
var fields = {}; | ||
var index; | ||
var line; | ||
var field; | ||
var val; | ||
var once = createCommonjsModule(function (module) { | ||
'use strict'; | ||
lines.pop(); // trailing CRLF | ||
// A "once" utility. | ||
module.exports = function(fn) { | ||
var result, called = false; | ||
return function() { | ||
if (!called) { | ||
called = true; | ||
result = fn.apply(this, arguments); | ||
} | ||
return result; | ||
}; | ||
}; | ||
}); | ||
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; | ||
} | ||
var once$1 = interopDefault(once); | ||
return fields; | ||
} | ||
/** | ||
* Check if `mime` is json or has +json structured syntax suffix. | ||
* | ||
* @param {String} mime | ||
* @return {Boolean} | ||
* @api private | ||
*/ | ||
var require$$0$3 = Object.freeze({ | ||
default: once$1 | ||
}); | ||
function isJSON(mime) { | ||
return /[\/+]json\b/.test(mime); | ||
} | ||
var index = createCommonjsModule(function (module) { | ||
'use strict'; | ||
/** | ||
* Return the mime type for the given `str`. | ||
* | ||
* @param {String} str | ||
* @return {String} | ||
* @api private | ||
*/ | ||
var | ||
cleanURL = interopDefault(require$$7), | ||
XHR = interopDefault(require$$6), | ||
delay = interopDefault(require$$5), | ||
RequestError = interopDefault(require$$4), | ||
Response = interopDefault(require$$2), | ||
Request = interopDefault(require$$1$1), | ||
extend = interopDefault(require$$0$2), | ||
once = interopDefault(require$$0$3); | ||
function type(str){ | ||
return str.split(/ *; */).shift(); | ||
}; | ||
var i, | ||
createError = RequestError.create; | ||
/** | ||
* Return header field parameters. | ||
* | ||
* @param {String} str | ||
* @return {Object} | ||
* @api private | ||
*/ | ||
function factory(defaults, plugins) { | ||
defaults = defaults || {}; | ||
plugins = plugins || []; | ||
function params(str){ | ||
return str.split(/ *; */).reduce(function(obj, str){ | ||
var parts = str.split(/ *= */), | ||
key = parts.shift(), | ||
val = parts.shift(); | ||
function http(req, cb) { | ||
var xhr, plugin, done, k, timeoutId, supportsLoadAndErrorEvents; | ||
if (key && val) obj[key] = val; | ||
return obj; | ||
}, {}); | ||
}; | ||
req = new Request(extend(defaults, req)); | ||
/** | ||
* 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 | ||
*/ | ||
for (i = 0; i < plugins.length; i++) { | ||
plugin = plugins[i]; | ||
if (plugin.processRequest) { | ||
plugin.processRequest(req); | ||
} | ||
} | ||
function Response(req, options) { | ||
options = options || {}; | ||
this.req = req; | ||
this.xhr = this.req.xhr; | ||
// responseText is accessible only if responseType is '' or 'text' and on older browsers | ||
this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined') | ||
? this.xhr.responseText | ||
: null; | ||
this.statusText = this.req.xhr.statusText; | ||
this._setStatusProperties(this.xhr.status); | ||
this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); | ||
// getAllResponseHeaders sometimes falsely returns "" for CORS requests, but | ||
// getResponseHeader still works. so we get content-type even if getting | ||
// other headers fails. | ||
this.header['content-type'] = this.xhr.getResponseHeader('content-type'); | ||
this._setHeaderProperties(this.header); | ||
this.body = this.req.method != 'HEAD' | ||
? this._parseBody(this.text ? this.text : this.xhr.response) | ||
: null; | ||
} | ||
// Give the plugins a chance to create the XHR object | ||
for (i = 0; i < plugins.length; i++) { | ||
plugin = plugins[i]; | ||
if (plugin.createXHR) { | ||
xhr = plugin.createXHR(req); | ||
break; // First come, first serve | ||
} | ||
} | ||
xhr = xhr || new XHR(); | ||
/** | ||
* Get case-insensitive `field` value. | ||
* | ||
* @param {String} field | ||
* @return {String} | ||
* @api public | ||
*/ | ||
req.xhr = xhr; | ||
Response.prototype.get = function(field){ | ||
return this.header[field.toLowerCase()]; | ||
}; | ||
// Use a single completion callback. This can be called with or without | ||
// an error. If no error is passed, the request will be examined to see | ||
// if it was successful. | ||
done = once(delay(function(rawError) { | ||
clearTimeout(timeoutId); | ||
xhr.onload = xhr.onerror = xhr.onabort = xhr.onreadystatechange = xhr.ontimeout = xhr.onprogress = null; | ||
/** | ||
* 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 | ||
*/ | ||
var err = getError(req, rawError); | ||
Response.prototype._setHeaderProperties = function(header){ | ||
// content-type | ||
var ct = this.header['content-type'] || ''; | ||
this.type = type(ct); | ||
var res = err || Response.fromRequest(req); | ||
for (i = 0; i < plugins.length; i++) { | ||
plugin = plugins[i]; | ||
if (plugin.processResponse) { | ||
plugin.processResponse(res); | ||
} | ||
} | ||
// params | ||
var obj = params(ct); | ||
for (var key in obj) this[key] = obj[key]; | ||
}; | ||
// Invoke callbacks | ||
if (err && req.onerror) req.onerror(err); | ||
if (!err && req.onload) req.onload(res); | ||
if (cb) cb(err, err ? undefined : res); | ||
/** | ||
* 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 | ||
*/ | ||
})); | ||
Response.prototype._parseBody = function(str){ | ||
var parse = request.parse[this.type]; | ||
if (!parse && isJSON(this.type)) { | ||
parse = request.parse['application/json']; | ||
} | ||
return parse && str && (str.length || str instanceof Object) | ||
? parse(str) | ||
: null; | ||
}; | ||
supportsLoadAndErrorEvents = ('onload' in xhr) && ('onerror' in xhr); | ||
xhr.onload = function() { done(); }; | ||
xhr.onerror = done; | ||
xhr.onabort = function() { done(); }; | ||
/** | ||
* 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 | ||
*/ | ||
// We'd rather use `onload`, `onerror`, and `onabort` since they're the | ||
// only way to reliably detect successes and failures but, if they | ||
// aren't available, we fall back to using `onreadystatechange`. | ||
xhr.onreadystatechange = function() { | ||
if (xhr.readyState !== 4) return; | ||
Response.prototype._setStatusProperties = function(status){ | ||
// handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request | ||
if (status === 1223) { | ||
status = 204; | ||
} | ||
if (req.aborted) return done(); | ||
var type = status / 100 | 0; | ||
if (!supportsLoadAndErrorEvents) { | ||
// Assume a status of 0 is an error. This could be a false | ||
// positive, but there's no way to tell when using | ||
// `onreadystatechange` ): | ||
// See matthewwithanm/react-inlinesvg#10. | ||
// status / class | ||
this.status = this.statusCode = status; | ||
this.statusType = type; | ||
// Some browsers don't like you reading XHR properties when the | ||
// XHR has been aborted. In case we've gotten here as a result | ||
// of that (either our calling `about()` in the timeout handler | ||
// or the user calling it directly even though they shouldn't), | ||
// be careful about accessing it. | ||
var status; | ||
try { | ||
status = xhr.status; | ||
} catch (err) {} | ||
var err = status === 0 ? new Error('Internal XHR Error') : null; | ||
return done(err); | ||
} | ||
}; | ||
// basics | ||
this.info = 1 == type; | ||
this.ok = 2 == type; | ||
this.clientError = 4 == type; | ||
this.serverError = 5 == type; | ||
this.error = (4 == type || 5 == type) | ||
? this.toError() | ||
: false; | ||
// IE sometimes fails if you don't specify every handler. | ||
// See http://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment | ||
xhr.ontimeout = function() { /* noop */ }; | ||
xhr.onprogress = function() { /* noop */ }; | ||
// sugar | ||
this.accepted = 202 == status; | ||
this.noContent = 204 == status; | ||
this.badRequest = 400 == status; | ||
this.unauthorized = 401 == status; | ||
this.notAcceptable = 406 == status; | ||
this.notFound = 404 == status; | ||
this.forbidden = 403 == status; | ||
}; | ||
xhr.open(req.method, req.url); | ||
/** | ||
* Return an `Error` representative of this response. | ||
* | ||
* @return {Error} | ||
* @api public | ||
*/ | ||
if (req.timeout) { | ||
// If we use the normal XHR timeout mechanism (`xhr.timeout` and | ||
// `xhr.ontimeout`), `onreadystatechange` will be triggered before | ||
// `ontimeout`. There's no way to recognize that it was triggered by | ||
// a timeout, and we'd be unable to dispatch the right error. | ||
timeoutId = setTimeout(function() { | ||
req.timedOut = true; | ||
done(); | ||
try { | ||
xhr.abort(); | ||
} catch (err) {} | ||
}, req.timeout); | ||
} | ||
Response.prototype.toError = function(){ | ||
var req = this.req; | ||
var method = req.method; | ||
var url = req.url; | ||
for (k in req.headers) { | ||
if (req.headers.hasOwnProperty(k)) { | ||
xhr.setRequestHeader(k, req.headers[k]); | ||
} | ||
} | ||
var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')'; | ||
var err = new Error(msg); | ||
err.status = this.status; | ||
err.method = method; | ||
err.url = url; | ||
xhr.send(req.body); | ||
return err; | ||
}; | ||
return req; | ||
} | ||
/** | ||
* Expose `Response`. | ||
*/ | ||
var method, | ||
methods = ['get', 'post', 'put', 'head', 'patch', 'delete'], | ||
verb = function(method) { | ||
return function(req, cb) { | ||
req = new Request(req); | ||
req.method = method; | ||
return http(req, cb); | ||
}; | ||
}; | ||
for (i = 0; i < methods.length; i++) { | ||
method = methods[i]; | ||
http[method] = verb(method); | ||
} | ||
request.Response = Response; | ||
http.plugins = function() { | ||
return plugins; | ||
}; | ||
/** | ||
* Initialize a new `Request` with the given `method` and `url`. | ||
* | ||
* @param {String} method | ||
* @param {String} url | ||
* @api public | ||
*/ | ||
http.defaults = function(newValues) { | ||
if (newValues) { | ||
return factory(extend(defaults, newValues), plugins); | ||
} | ||
return defaults; | ||
}; | ||
function Request(method, url) { | ||
var self = this; | ||
this._query = this._query || []; | ||
this.method = method; | ||
this.url = url; | ||
this.header = {}; // preserves header name case | ||
this._header = {}; // coerces header names to lowercase | ||
this.on('end', function(){ | ||
var err = null; | ||
var res = null; | ||
http.use = function() { | ||
var newPlugins = Array.prototype.slice.call(arguments, 0); | ||
return factory(defaults, plugins.concat(newPlugins)); | ||
}; | ||
try { | ||
res = new Response(self); | ||
} catch(e) { | ||
err = new Error('Parser is unable to parse the response'); | ||
err.parse = true; | ||
err.original = e; | ||
// issue #675: return the raw response if the response parsing fails | ||
err.rawResponse = self.xhr && self.xhr.responseText ? self.xhr.responseText : null; | ||
// issue #876: return the http status code if the response parsing fails | ||
err.statusCode = self.xhr && self.xhr.status ? self.xhr.status : null; | ||
return self.callback(err); | ||
} | ||
http.bare = function() { | ||
return factory(); | ||
}; | ||
self.emit('response', res); | ||
http.Request = Request; | ||
http.Response = Response; | ||
http.RequestError = RequestError; | ||
var new_err; | ||
try { | ||
if (res.status < 200 || res.status >= 300) { | ||
new_err = new Error(res.statusText || 'Unsuccessful HTTP response'); | ||
new_err.original = err; | ||
new_err.response = res; | ||
new_err.status = res.status; | ||
} | ||
} catch(e) { | ||
new_err = e; // #985 touching res may cause INVALID_STATE_ERR on old Android | ||
} | ||
return http; | ||
} | ||
// #1000 don't catch errors from the callback to avoid double calling it | ||
if (new_err) { | ||
self.callback(new_err, res); | ||
} else { | ||
self.callback(null, res); | ||
} | ||
}); | ||
} | ||
module.exports = factory({}, [cleanURL]); | ||
/** | ||
* Mixin `Emitter` and `requestBase`. | ||
*/ | ||
/** | ||
* Analyze the request to see if it represents an error. If so, return it! An | ||
* original error object can be passed as a hint. | ||
*/ | ||
function getError(req, err) { | ||
if (req.aborted) return createError('Request aborted', req, {name: 'Abort'}); | ||
Emitter(Request.prototype); | ||
for (var key in requestBase) { | ||
Request.prototype[key] = requestBase[key]; | ||
} | ||
if (req.timedOut) return createError('Request timeout', req, {name: 'Timeout'}); | ||
/** | ||
* 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 | ||
*/ | ||
var xhr = req.xhr; | ||
var type = Math.floor(xhr.status / 100); | ||
Request.prototype.type = function(type){ | ||
this.set('Content-Type', request.types[type] || type); | ||
return this; | ||
}; | ||
var kind; | ||
switch (type) { | ||
case 0: | ||
case 2: | ||
// These don't represent errors unless the function was passed an | ||
// error object explicitly. | ||
if (!err) return; | ||
return createError(err.message, req); | ||
case 4: | ||
// Sometimes 4XX statuses aren't errors. | ||
if (xhr.status === 404 && !req.errorOn404) return; | ||
kind = 'Client'; | ||
break; | ||
case 5: | ||
kind = 'Server'; | ||
break; | ||
default: | ||
kind = 'HTTP'; | ||
} | ||
var msg = kind + ' Error: ' + | ||
'The server returned a status of ' + xhr.status + | ||
' for the request "' + | ||
req.method.toUpperCase() + ' ' + req.url + '"'; | ||
return createError(msg, req); | ||
} | ||
}); | ||
/** | ||
* Set responseType to `val`. Presently valid responseTypes are 'blob' and | ||
* 'arraybuffer'. | ||
* | ||
* Examples: | ||
* | ||
* req.get('/') | ||
* .responseType('blob') | ||
* .end(callback); | ||
* | ||
* @param {String} val | ||
* @return {Request} for chaining | ||
* @api public | ||
*/ | ||
var httpplease = interopDefault(index); | ||
Request.prototype.responseType = function(val){ | ||
this._responseType = val; | ||
return this; | ||
}; | ||
var request = httpplease.use(json$1); | ||
/** | ||
* Set Accept to `type`, mapping values from `request.types`. | ||
* | ||
* Examples: | ||
* | ||
* superagent.types.json = 'application/json'; | ||
* | ||
* request.get('/agent') | ||
* .accept('json') | ||
* .end(callback); | ||
* | ||
* request.get('/agent') | ||
* .accept('application/json') | ||
* .end(callback); | ||
* | ||
* @param {String} accept | ||
* @return {Request} for chaining | ||
* @api public | ||
*/ | ||
function send(method, url, args) { | ||
return new Promise(function (resolve, reject) { | ||
request({ method: method, url: url, body: args }, function (err, res) { | ||
if (err) { | ||
var error = err && err.body && err.body.meta && err.body.meta.errorMessage ? new Error(err.body.meta.errorMessage) : err; | ||
error.status = err.status; | ||
reject(error); | ||
} else { | ||
resolve(res); | ||
} | ||
}); | ||
}); | ||
} | ||
Request.prototype.accept = function(type){ | ||
this.set('Accept', request.types[type] || type); | ||
return this; | ||
}; | ||
function get(url) { | ||
return send('GET', url); | ||
} | ||
/** | ||
* Set Authorization field value with `user` and `pass`. | ||
* | ||
* @param {String} user | ||
* @param {String} pass | ||
* @param {Object} options with 'type' property 'auto' or 'basic' (default 'basic') | ||
* @return {Request} for chaining | ||
* @api public | ||
*/ | ||
function post(url, args) { | ||
return send('POST', url, args); | ||
} | ||
Request.prototype.auth = function(user, pass, options){ | ||
if (!options) { | ||
options = { | ||
type: 'basic' | ||
} | ||
} | ||
function findSegments(agent) { | ||
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; | ||
switch (options.type) { | ||
case 'basic': | ||
var str = btoa(user + ':' + pass); | ||
this.set('Authorization', 'Basic ' + str); | ||
break; | ||
return get(agent.url + '/segments' + makeQueryString(opts)).then(function (res) { | ||
return res.body.map(function (obj) { | ||
return segmentify(agent, obj); | ||
}); | ||
}); | ||
} | ||
case 'auto': | ||
this.username = user; | ||
this.password = pass; | ||
break; | ||
} | ||
return this; | ||
}; | ||
function getBranches(agent, prevLinkHash) { | ||
var tags = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2]; | ||
/** | ||
* Add query-string `val`. | ||
* | ||
* Examples: | ||
* | ||
* request.get('/shoes') | ||
* .query('size=10') | ||
* .query({ color: 'blue' }) | ||
* | ||
* @param {Object|String} val | ||
* @return {Request} for chaining | ||
* @api public | ||
*/ | ||
deprecated('Agent#getBranches(agent, prevLinkHash, tags = [])', 'Agent#findSegments(agent, filter)'); | ||
Request.prototype.query = function(val){ | ||
if ('string' != typeof val) val = serialize(val); | ||
if (val) this._query.push(val); | ||
return this; | ||
}; | ||
return findSegments(agent, { prevLinkHash: prevLinkHash, tags: tags }); | ||
} | ||
/** | ||
* Queue the given `file` as an attachment to the specified `field`, | ||
* with optional `filename`. | ||
* | ||
* ``` js | ||
* request.post('/upload') | ||
* .attach('content', new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"})) | ||
* .end(callback); | ||
* ``` | ||
* | ||
* @param {String} field | ||
* @param {Blob|File} file | ||
* @param {String} filename | ||
* @return {Request} for chaining | ||
* @api public | ||
*/ | ||
function segmentify(agent, obj) { | ||
Object.keys(agent.agentInfo.actions).filter(function (key) { | ||
return ['init'].indexOf(key) < 0; | ||
}).forEach(function (key) { | ||
/*eslint-disable*/ | ||
obj[key] = function () { | ||
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
Request.prototype.attach = function(field, file, filename){ | ||
this._getFormData().append(field, file, filename || file.name); | ||
return this; | ||
}; | ||
return post(agent.url + '/segments/' + obj.meta.linkHash + '/' + key, args).then(function (res) { | ||
return segmentify(agent, res.body); | ||
}); | ||
}; | ||
}); | ||
Request.prototype._getFormData = function(){ | ||
if (!this._formData) { | ||
this._formData = new root.FormData(); | ||
} | ||
return this._formData; | ||
}; | ||
/*eslint-disable*/ | ||
obj.getPrev = function () { | ||
/*eslint-enable*/ | ||
if (obj.link.meta.prevLinkHash) { | ||
return agent.getSegment(obj.link.meta.prevLinkHash); | ||
} | ||
/** | ||
* Invoke the callback with `err` and `res` | ||
* and handle arity check. | ||
* | ||
* @param {Error} err | ||
* @param {Response} res | ||
* @api private | ||
*/ | ||
return Promise.resolve(null); | ||
}; | ||
Request.prototype.callback = function(err, res){ | ||
var fn = this._callback; | ||
this.clearTimeout(); | ||
fn(err, res); | ||
}; | ||
// Deprecated. | ||
/*eslint-disable*/ | ||
obj.load = function () { | ||
/*eslint-enable*/ | ||
deprecated('segment#load()'); | ||
return Promise.resolve(segmentify(agent, { | ||
link: JSON.parse(JSON.stringify(obj.link)), | ||
meta: JSON.parse(JSON.stringify(obj.meta)) | ||
})); | ||
}; | ||
/** | ||
* Invoke callback with x-domain error. | ||
* | ||
* @api private | ||
*/ | ||
// Deprecated. | ||
/*eslint-disable*/ | ||
obj.getBranches = function () { | ||
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
args[_key2] = arguments[_key2]; | ||
} | ||
Request.prototype.crossDomainError = function(){ | ||
var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); | ||
err.crossDomain = true; | ||
/*eslint-enable*/ | ||
return getBranches.apply(undefined, [agent, obj.meta.linkHash].concat(args)); | ||
}; | ||
err.status = this.status; | ||
err.method = this.method; | ||
err.url = this.url; | ||
return obj; | ||
} | ||
this.callback(err); | ||
}; | ||
function createMap(agent) { | ||
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | ||
args[_key - 1] = arguments[_key]; | ||
} | ||
/** | ||
* Invoke callback with timeout error. | ||
* | ||
* @api private | ||
*/ | ||
return post(agent.url + '/segments', args).then(function (res) { | ||
return segmentify(agent, res.body); | ||
}); | ||
} | ||
Request.prototype._timeoutError = function(){ | ||
var timeout = this._timeout; | ||
var err = new Error('timeout of ' + timeout + 'ms exceeded'); | ||
err.timeout = timeout; | ||
this.callback(err); | ||
}; | ||
function getSegment(agent, linkHash) { | ||
return get(agent.url + '/segments/' + linkHash).then(function (res) { | ||
return segmentify(agent, res.body); | ||
}); | ||
} | ||
/** | ||
* Compose querystring to append to req.url | ||
* | ||
* @api private | ||
*/ | ||
function getMapIds(agent) { | ||
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; | ||
Request.prototype._appendQueryString = function(){ | ||
var query = this._query.join('&'); | ||
if (query) { | ||
this.url += ~this.url.indexOf('?') | ||
? '&' + query | ||
: '?' + query; | ||
} | ||
}; | ||
return get(agent.url + '/maps' + makeQueryString(opts)).then(function (res) { | ||
return res.body; | ||
}); | ||
} | ||
/** | ||
* Initiate request, invoking callback `fn(res)` | ||
* with an instanceof `Response`. | ||
* | ||
* @param {Function} fn | ||
* @return {Request} for chaining | ||
* @api public | ||
*/ | ||
function getLink(agent, hash) { | ||
deprecated('Agent#getLink(agent, hash)', 'Agent#getSegment(agent, hash)'); | ||
Request.prototype.end = function(fn){ | ||
var self = this; | ||
var xhr = this.xhr = request.getXHR(); | ||
var timeout = this._timeout; | ||
var data = this._formData || this._data; | ||
return getSegment(agent, hash); | ||
} | ||
// store callback | ||
this._callback = fn || noop; | ||
function getMap(agent, mapId) { | ||
var tags = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2]; | ||
// state change | ||
xhr.onreadystatechange = function(){ | ||
if (4 != xhr.readyState) return; | ||
deprecated('getMap(agent, mapId, tags = [])', 'findSegments(agent, filter)'); | ||
// In IE9, reads to any property (e.g. status) off of an aborted XHR will | ||
// result in the error "Could not complete the operation due to error c00c023f" | ||
var status; | ||
try { status = xhr.status } catch(e) { status = 0; } | ||
return findSegments(agent, { mapId: mapId, tags: tags }); | ||
} | ||
if (0 == status) { | ||
if (self.timedout) return self._timeoutError(); | ||
if (self._aborted) return; | ||
return self.crossDomainError(); | ||
} | ||
self.emit('end'); | ||
}; | ||
// Deprecated. | ||
function getAgent(url) { | ||
return get(url).then(function (res) { | ||
var agent = res.body; | ||
// progress | ||
var handleProgress = function(e){ | ||
if (e.total > 0) { | ||
e.percent = e.loaded / e.total * 100; | ||
} | ||
e.direction = 'download'; | ||
self.emit('progress', e); | ||
}; | ||
if (this.hasListeners('progress')) { | ||
xhr.onprogress = handleProgress; | ||
} | ||
try { | ||
if (xhr.upload && this.hasListeners('progress')) { | ||
xhr.upload.onprogress = handleProgress; | ||
} | ||
} catch(e) { | ||
// Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. | ||
// Reported here: | ||
// https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context | ||
} | ||
agent.url = url; | ||
agent.createMap = createMap.bind(null, agent); | ||
agent.getSegment = getSegment.bind(null, agent); | ||
agent.findSegments = findSegments.bind(null, agent); | ||
agent.getMapIds = getMapIds.bind(null, agent); | ||
// timeout | ||
if (timeout && !this._timer) { | ||
this._timer = setTimeout(function(){ | ||
self.timedout = true; | ||
self.abort(); | ||
}, timeout); | ||
} | ||
// Deprecated. | ||
agent.getBranches = getBranches.bind(null, agent); | ||
agent.getLink = getLink.bind(null, agent); | ||
agent.getMap = getMap.bind(null, agent); | ||
// querystring | ||
this._appendQueryString(); | ||
return agent; | ||
}); | ||
} | ||
// initiate request | ||
if (this.username && this.password) { | ||
xhr.open(this.method, this.url, true, this.username, this.password); | ||
} else { | ||
xhr.open(this.method, this.url, true); | ||
} | ||
function fromSegment(obj) { | ||
return getAgent(obj.meta.agentUrl || obj.meta.applicationLocation).then(function (agent) { | ||
var segment = segmentify(agent, obj); | ||
return { agent: agent, segment: segment }; | ||
}); | ||
} | ||
// CORS | ||
if (this._withCredentials) xhr.withCredentials = true; | ||
// Deprecated. | ||
var config = { | ||
applicationUrl: 'https://%s.stratumn.rocks' | ||
}; | ||
// body | ||
if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) { | ||
// serialize stuff | ||
var contentType = this._header['content-type']; | ||
var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; | ||
if (!serialize && isJSON(contentType)) serialize = request.serialize['application/json']; | ||
if (serialize) data = serialize(data); | ||
} | ||
function getApplication(name, url) { | ||
deprecated('getApplication(name, url)', 'getAgent(url)'); | ||
// set header fields | ||
for (var field in this.header) { | ||
if (null == this.header[field]) continue; | ||
xhr.setRequestHeader(field, this.header[field]); | ||
} | ||
return getAgent(url || config.applicationUrl.replace('%s', name)); | ||
} | ||
if (this._responseType) { | ||
xhr.responseType = this._responseType; | ||
} | ||
function loadLink(obj) { | ||
deprecated('loadLink(obj)', 'fromSegment(obj)'); | ||
// send stuff | ||
this.emit('request', this); | ||
return fromSegment(obj).then(function (_ref) { | ||
var segment = _ref.segment; | ||
return segment; | ||
}); | ||
} | ||
// IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) | ||
// We need null here if data is undefined | ||
xhr.send(typeof data !== 'undefined' ? data : null); | ||
return this; | ||
}; | ||
exports.getAgent = getAgent; | ||
exports.fromSegment = fromSegment; | ||
exports.getApplication = getApplication; | ||
exports.loadLink = loadLink; | ||
exports.config = config; | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
/** | ||
* Expose `Request`. | ||
*/ | ||
request.Request = Request; | ||
/** | ||
* GET `url` with optional callback `fn(res)`. | ||
* | ||
* @param {String} url | ||
* @param {Mixed|Function} [data] or fn | ||
* @param {Function} [fn] | ||
* @return {Request} | ||
* @api public | ||
*/ | ||
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; | ||
}; | ||
/** | ||
* HEAD `url` with optional callback `fn(res)`. | ||
* | ||
* @param {String} url | ||
* @param {Mixed|Function} [data] or fn | ||
* @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; | ||
}; | ||
/** | ||
* OPTIONS query to `url` with optional callback `fn(res)`. | ||
* | ||
* @param {String} url | ||
* @param {Mixed|Function} [data] or fn | ||
* @param {Function} [fn] | ||
* @return {Request} | ||
* @api public | ||
*/ | ||
request.options = function(url, data, fn){ | ||
var req = request('OPTIONS', url); | ||
if ('function' == typeof data) fn = data, data = null; | ||
if (data) req.send(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 | ||
*/ | ||
function del(url, fn){ | ||
var req = request('DELETE', url); | ||
if (fn) req.end(fn); | ||
return req; | ||
}; | ||
request['del'] = del; | ||
request['delete'] = del; | ||
/** | ||
* PATCH `url` with optional `data` and callback `fn(res)`. | ||
* | ||
* @param {String} url | ||
* @param {Mixed} [data] | ||
* @param {Function} [fn] | ||
* @return {Request} | ||
* @api public | ||
*/ | ||
request.patch = function(url, data, fn){ | ||
var req = request('PATCH', url); | ||
if ('function' == typeof data) fn = data, data = null; | ||
if (data) req.send(data); | ||
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 | ||
*/ | ||
request.post = function(url, data, fn){ | ||
var req = request('POST', url); | ||
if ('function' == typeof data) fn = data, data = null; | ||
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|Function} [data] or fn | ||
* @param {Function} [fn] | ||
* @return {Request} | ||
* @api public | ||
*/ | ||
request.put = function(url, data, fn){ | ||
var req = request('PUT', url); | ||
if ('function' == typeof data) fn = data, data = null; | ||
if (data) req.send(data); | ||
if (fn) req.end(fn); | ||
return req; | ||
}; | ||
/***/ }, | ||
/* 3 */ | ||
/***/ function(module, exports, __webpack_require__) { | ||
/** | ||
* Expose `Emitter`. | ||
*/ | ||
if (true) { | ||
module.exports = Emitter; | ||
} | ||
/** | ||
* Initialize a new `Emitter`. | ||
* | ||
* @api public | ||
*/ | ||
function Emitter(obj) { | ||
if (obj) return mixin(obj); | ||
}; | ||
/** | ||
* Mixin the emitter properties. | ||
* | ||
* @param {Object} obj | ||
* @return {Object} | ||
* @api private | ||
*/ | ||
function mixin(obj) { | ||
for (var key in Emitter.prototype) { | ||
obj[key] = Emitter.prototype[key]; | ||
} | ||
return obj; | ||
} | ||
/** | ||
* Listen on the given `event` with `fn`. | ||
* | ||
* @param {String} event | ||
* @param {Function} fn | ||
* @return {Emitter} | ||
* @api public | ||
*/ | ||
Emitter.prototype.on = | ||
Emitter.prototype.addEventListener = function(event, fn){ | ||
this._callbacks = this._callbacks || {}; | ||
(this._callbacks['$' + event] = this._callbacks['$' + event] || []) | ||
.push(fn); | ||
return this; | ||
}; | ||
/** | ||
* Adds an `event` listener that will be invoked a single | ||
* time then automatically removed. | ||
* | ||
* @param {String} event | ||
* @param {Function} fn | ||
* @return {Emitter} | ||
* @api public | ||
*/ | ||
Emitter.prototype.once = function(event, fn){ | ||
function on() { | ||
this.off(event, on); | ||
fn.apply(this, arguments); | ||
} | ||
on.fn = fn; | ||
this.on(event, on); | ||
return this; | ||
}; | ||
/** | ||
* Remove the given callback for `event` or all | ||
* registered callbacks. | ||
* | ||
* @param {String} event | ||
* @param {Function} fn | ||
* @return {Emitter} | ||
* @api public | ||
*/ | ||
Emitter.prototype.off = | ||
Emitter.prototype.removeListener = | ||
Emitter.prototype.removeAllListeners = | ||
Emitter.prototype.removeEventListener = function(event, fn){ | ||
this._callbacks = this._callbacks || {}; | ||
// all | ||
if (0 == arguments.length) { | ||
this._callbacks = {}; | ||
return this; | ||
} | ||
// specific event | ||
var callbacks = this._callbacks['$' + event]; | ||
if (!callbacks) return this; | ||
// remove all handlers | ||
if (1 == arguments.length) { | ||
delete this._callbacks['$' + event]; | ||
return this; | ||
} | ||
// remove specific handler | ||
var cb; | ||
for (var i = 0; i < callbacks.length; i++) { | ||
cb = callbacks[i]; | ||
if (cb === fn || cb.fn === fn) { | ||
callbacks.splice(i, 1); | ||
break; | ||
} | ||
} | ||
return this; | ||
}; | ||
/** | ||
* Emit `event` with the given args. | ||
* | ||
* @param {String} event | ||
* @param {Mixed} ... | ||
* @return {Emitter} | ||
*/ | ||
Emitter.prototype.emit = function(event){ | ||
this._callbacks = this._callbacks || {}; | ||
var args = [].slice.call(arguments, 1) | ||
, callbacks = this._callbacks['$' + event]; | ||
if (callbacks) { | ||
callbacks = callbacks.slice(0); | ||
for (var i = 0, len = callbacks.length; i < len; ++i) { | ||
callbacks[i].apply(this, args); | ||
} | ||
} | ||
return this; | ||
}; | ||
/** | ||
* Return array of callbacks for `event`. | ||
* | ||
* @param {String} event | ||
* @return {Array} | ||
* @api public | ||
*/ | ||
Emitter.prototype.listeners = function(event){ | ||
this._callbacks = this._callbacks || {}; | ||
return this._callbacks['$' + event] || []; | ||
}; | ||
/** | ||
* Check if this emitter has `event` handlers. | ||
* | ||
* @param {String} event | ||
* @return {Boolean} | ||
* @api public | ||
*/ | ||
Emitter.prototype.hasListeners = function(event){ | ||
return !! this.listeners(event).length; | ||
}; | ||
/***/ }, | ||
/* 4 */ | ||
/***/ function(module, exports, __webpack_require__) { | ||
/** | ||
* Module of mixed-in functions shared between node and client code | ||
*/ | ||
var isObject = __webpack_require__(5); | ||
/** | ||
* Clear previous timeout. | ||
* | ||
* @return {Request} for chaining | ||
* @api public | ||
*/ | ||
exports.clearTimeout = function _clearTimeout(){ | ||
this._timeout = 0; | ||
clearTimeout(this._timer); | ||
return this; | ||
}; | ||
/** | ||
* Override default response body parser | ||
* | ||
* This function will be called to convert incoming data into request.body | ||
* | ||
* @param {Function} | ||
* @api public | ||
*/ | ||
exports.parse = function parse(fn){ | ||
this._parser = fn; | ||
return this; | ||
}; | ||
/** | ||
* Override default request body serializer | ||
* | ||
* This function will be called to convert data set via .send or .attach into payload to send | ||
* | ||
* @param {Function} | ||
* @api public | ||
*/ | ||
exports.serialize = function serialize(fn){ | ||
this._serializer = fn; | ||
return this; | ||
}; | ||
/** | ||
* Set timeout to `ms`. | ||
* | ||
* @param {Number} ms | ||
* @return {Request} for chaining | ||
* @api public | ||
*/ | ||
exports.timeout = function timeout(ms){ | ||
this._timeout = ms; | ||
return this; | ||
}; | ||
/** | ||
* Promise support | ||
* | ||
* @param {Function} resolve | ||
* @param {Function} reject | ||
* @return {Request} | ||
*/ | ||
exports.then = function then(resolve, reject) { | ||
if (!this._fullfilledPromise) { | ||
var self = this; | ||
this._fullfilledPromise = new Promise(function(innerResolve, innerReject){ | ||
self.end(function(err, res){ | ||
if (err) innerReject(err); else innerResolve(res); | ||
}); | ||
}); | ||
} | ||
return this._fullfilledPromise.then(resolve, reject); | ||
} | ||
/** | ||
* Allow for extension | ||
*/ | ||
exports.use = function use(fn) { | ||
fn(this); | ||
return this; | ||
} | ||
/** | ||
* Get request header `field`. | ||
* Case-insensitive. | ||
* | ||
* @param {String} field | ||
* @return {String} | ||
* @api public | ||
*/ | ||
exports.get = function(field){ | ||
return this._header[field.toLowerCase()]; | ||
}; | ||
/** | ||
* Get case-insensitive header `field` value. | ||
* This is a deprecated internal API. Use `.get(field)` instead. | ||
* | ||
* (getHeader is no longer used internally by the superagent code base) | ||
* | ||
* @param {String} field | ||
* @return {String} | ||
* @api private | ||
* @deprecated | ||
*/ | ||
exports.getHeader = exports.get; | ||
/** | ||
* Set header `field` to `val`, or multiple fields with one object. | ||
* Case-insensitive. | ||
* | ||
* 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 | ||
*/ | ||
exports.set = function(field, val){ | ||
if (isObject(field)) { | ||
for (var key in field) { | ||
this.set(key, field[key]); | ||
} | ||
return this; | ||
} | ||
this._header[field.toLowerCase()] = val; | ||
this.header[field] = val; | ||
return this; | ||
}; | ||
/** | ||
* Remove header `field`. | ||
* Case-insensitive. | ||
* | ||
* Example: | ||
* | ||
* req.get('/') | ||
* .unset('User-Agent') | ||
* .end(callback); | ||
* | ||
* @param {String} field | ||
*/ | ||
exports.unset = function(field){ | ||
delete this._header[field.toLowerCase()]; | ||
delete this.header[field]; | ||
return this; | ||
}; | ||
/** | ||
* Write the field `name` and `val` for "multipart/form-data" | ||
* request bodies. | ||
* | ||
* ``` js | ||
* request.post('/upload') | ||
* .field('foo', 'bar') | ||
* .end(callback); | ||
* ``` | ||
* | ||
* @param {String} name | ||
* @param {String|Blob|File|Buffer|fs.ReadStream} val | ||
* @return {Request} for chaining | ||
* @api public | ||
*/ | ||
exports.field = function(name, val) { | ||
this._getFormData().append(name, val); | ||
return this; | ||
}; | ||
/** | ||
* Abort the request, and clear potential timeout. | ||
* | ||
* @return {Request} | ||
* @api public | ||
*/ | ||
exports.abort = function(){ | ||
if (this._aborted) { | ||
return this; | ||
} | ||
this._aborted = true; | ||
this.xhr && this.xhr.abort(); // browser | ||
this.req && this.req.abort(); // node | ||
this.clearTimeout(); | ||
this.emit('abort'); | ||
return this; | ||
}; | ||
/** | ||
* Enable transmission of cookies with x-domain requests. | ||
* | ||
* Note that for this to work the origin must not be | ||
* using "Access-Control-Allow-Origin" with a wildcard, | ||
* and also must set "Access-Control-Allow-Credentials" | ||
* to "true". | ||
* | ||
* @api public | ||
*/ | ||
exports.withCredentials = function(){ | ||
// This is browser-only functionality. Node side is no-op. | ||
this._withCredentials = true; | ||
return this; | ||
}; | ||
/** | ||
* Set the max redirects to `n`. Does noting in browser XHR implementation. | ||
* | ||
* @param {Number} n | ||
* @return {Request} for chaining | ||
* @api public | ||
*/ | ||
exports.redirects = function(n){ | ||
this._maxRedirects = n; | ||
return this; | ||
}; | ||
/** | ||
* Convert to a plain javascript object (not JSON string) of scalar properties. | ||
* Note as this method is designed to return a useful non-this value, | ||
* it cannot be chained. | ||
* | ||
* @return {Object} describing method, url, and data of this request | ||
* @api public | ||
*/ | ||
exports.toJSON = function(){ | ||
return { | ||
method: this.method, | ||
url: this.url, | ||
data: this._data, | ||
headers: this._header | ||
}; | ||
}; | ||
/** | ||
* Check if `obj` is a host object, | ||
* we don't want to serialize these :) | ||
* | ||
* TODO: future proof, move to compoent land | ||
* | ||
* @param {Object} obj | ||
* @return {Boolean} | ||
* @api private | ||
*/ | ||
exports._isHost = function _isHost(obj) { | ||
var str = {}.toString.call(obj); | ||
switch (str) { | ||
case '[object File]': | ||
case '[object Blob]': | ||
case '[object FormData]': | ||
return true; | ||
default: | ||
return false; | ||
} | ||
} | ||
/** | ||
* Send `data` as the request body, defaulting the `.type()` to "json" when | ||
* an object is given. | ||
* | ||
* Examples: | ||
* | ||
* // 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 | ||
*/ | ||
exports.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) { | ||
// default to x-www-form-urlencoded | ||
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; | ||
} | ||
} else { | ||
this._data = data; | ||
} | ||
if (!obj || this._isHost(data)) return this; | ||
// default to json | ||
if (!type) this.type('json'); | ||
return this; | ||
}; | ||
/***/ }, | ||
/* 5 */ | ||
/***/ function(module, exports) { | ||
/** | ||
* Check if `obj` is an object. | ||
* | ||
* @param {Object} obj | ||
* @return {Boolean} | ||
* @api private | ||
*/ | ||
function isObject(obj) { | ||
return null !== obj && 'object' === typeof obj; | ||
} | ||
module.exports = isObject; | ||
/***/ }, | ||
/* 6 */ | ||
/***/ function(module, exports) { | ||
// The node and browser modules expose versions of this with the | ||
// appropriate constructor function bound as first argument | ||
/** | ||
* 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 | ||
*/ | ||
function request(RequestConstructor, method, url) { | ||
// callback | ||
if ('function' == typeof url) { | ||
return new RequestConstructor('GET', method).end(url); | ||
} | ||
// url first | ||
if (2 == arguments.length) { | ||
return new RequestConstructor('GET', method); | ||
} | ||
return new RequestConstructor(method, url); | ||
} | ||
module.exports = request; | ||
/***/ }, | ||
/* 7 */ | ||
/***/ function(module, exports, __webpack_require__) { | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.default = createMap; | ||
var _superagent = __webpack_require__(2); | ||
var _superagent2 = _interopRequireDefault(_superagent); | ||
var _segmentify = __webpack_require__(8); | ||
var _segmentify2 = _interopRequireDefault(_segmentify); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function createMap(agent) { | ||
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | ||
args[_key - 1] = arguments[_key]; | ||
} | ||
return new Promise(function (resolve, reject) { | ||
var url = agent.url + '/segments'; | ||
_superagent2.default.post(url).send(args).end(function (err, res) { | ||
var error = res.body.meta && res.body.meta.errorMessage ? new Error(res.body.meta.errorMessage) : err; | ||
if (error) { | ||
error.status = res && res.statusCode; | ||
reject(error); | ||
return; | ||
} | ||
resolve((0, _segmentify2.default)(agent, res.body)); | ||
}); | ||
}); | ||
} | ||
/***/ }, | ||
/* 8 */ | ||
/***/ function(module, exports, __webpack_require__) { | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.default = segmentify; | ||
var _superagent = __webpack_require__(2); | ||
var _superagent2 = _interopRequireDefault(_superagent); | ||
var _deprecated = __webpack_require__(9); | ||
var _deprecated2 = _interopRequireDefault(_deprecated); | ||
var _getBranches = __webpack_require__(10); | ||
var _getBranches2 = _interopRequireDefault(_getBranches); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function segmentify(agent, obj) { | ||
Object.keys(agent.agentInfo.actions).filter(function (key) { | ||
return ['init'].indexOf(key) < 0; | ||
}).forEach(function (key) { | ||
/*eslint-disable*/ | ||
obj[key] = function () { | ||
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
return new Promise(function (resolve, reject) { | ||
var url = agent.url + '/segments/' + obj.meta.linkHash + '/' + key; | ||
/*eslint-enable*/ | ||
_superagent2.default.post(url).send(args).end(function (err, res) { | ||
var error = res.body.meta && res.body.meta.errorMessage ? new Error(res.body.meta.errorMessage) : err; | ||
if (error) { | ||
error.status = res && res.statusCode; | ||
reject(error); | ||
return; | ||
} | ||
resolve(segmentify(agent, res.body)); | ||
}); | ||
}); | ||
}; | ||
}); | ||
/*eslint-disable*/ | ||
obj.getPrev = function () { | ||
/*eslint-enable*/ | ||
if (obj.link.meta.prevLinkHash) { | ||
return agent.getSegment(obj.link.meta.prevLinkHash); | ||
} | ||
return Promise.resolve(null); | ||
}; | ||
// Deprecated. | ||
/*eslint-disable*/ | ||
obj.load = function () { | ||
/*eslint-enable*/ | ||
(0, _deprecated2.default)('segment#load()'); | ||
return Promise.resolve(segmentify(agent, { | ||
link: JSON.parse(JSON.stringify(obj.link)), | ||
meta: JSON.parse(JSON.stringify(obj.meta)) | ||
})); | ||
}; | ||
// Deprecated. | ||
/*eslint-disable*/ | ||
obj.getBranches = function () { | ||
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
args[_key2] = arguments[_key2]; | ||
} | ||
/*eslint-enable*/ | ||
return _getBranches2.default.apply(undefined, [agent, obj.meta.linkHash].concat(args)); | ||
}; | ||
return obj; | ||
} | ||
/***/ }, | ||
/* 9 */ | ||
/***/ function(module, exports) { | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.default = deprecated; | ||
function deprecated(oldFunc, newFunc) { | ||
if (!newFunc) { | ||
console.warn("WARNING: " + oldFunc + " is deprecated."); | ||
} else { | ||
console.warn("WARNING: " + oldFunc + " is deprecated. Please use " + newFunc + " instead."); | ||
} | ||
} | ||
/***/ }, | ||
/* 10 */ | ||
/***/ function(module, exports, __webpack_require__) { | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.default = getBranches; | ||
var _findSegments = __webpack_require__(11); | ||
var _findSegments2 = _interopRequireDefault(_findSegments); | ||
var _deprecated = __webpack_require__(9); | ||
var _deprecated2 = _interopRequireDefault(_deprecated); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function getBranches(agent, prevLinkHash) { | ||
var tags = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2]; | ||
(0, _deprecated2.default)('Agent#getBranches(agent, prevLinkHash, tags = [])', 'Agent#findSegments(agent, filter)'); | ||
return (0, _findSegments2.default)(agent, { prevLinkHash: prevLinkHash, tags: tags }); | ||
} | ||
/***/ }, | ||
/* 11 */ | ||
/***/ function(module, exports, __webpack_require__) { | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.default = findSegments; | ||
var _superagent = __webpack_require__(2); | ||
var _superagent2 = _interopRequireDefault(_superagent); | ||
var _segmentify = __webpack_require__(8); | ||
var _segmentify2 = _interopRequireDefault(_segmentify); | ||
var _makeQueryString = __webpack_require__(12); | ||
var _makeQueryString2 = _interopRequireDefault(_makeQueryString); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function findSegments(agent) { | ||
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; | ||
return new Promise(function (resolve, reject) { | ||
var url = agent.url + '/segments' + (0, _makeQueryString2.default)(opts); | ||
_superagent2.default.get(url).end(function (err, res) { | ||
if (err) { | ||
/*eslint-disable*/ | ||
err.message = res && res.body.error ? res.body.error : err.message; | ||
err.status = res && res.statusCode; | ||
/*eslint-enable*/ | ||
reject(err); | ||
return; | ||
} | ||
resolve(res.body.map(function (obj) { | ||
return (0, _segmentify2.default)(agent, obj); | ||
})); | ||
}); | ||
}); | ||
} | ||
/***/ }, | ||
/* 12 */ | ||
/***/ function(module, exports) { | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.default = makeQueryString; | ||
/** | ||
* Makes a query string. | ||
* @param {object} obj - an object of keys | ||
* @returns {string} a query string | ||
*/ | ||
function makeQueryString(obj) { | ||
var parts = Object.keys(obj).reduce(function (curr, key) { | ||
var val = Array.isArray(obj[key]) ? obj[key].join('+') : obj[key]; | ||
curr.push(encodeURIComponent(key) + '=' + encodeURIComponent(val)); | ||
return curr; | ||
}, []); | ||
if (parts.length) { | ||
return '?' + parts.join('&'); | ||
} | ||
return ''; | ||
} | ||
/***/ }, | ||
/* 13 */ | ||
/***/ function(module, exports, __webpack_require__) { | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.default = getSegment; | ||
var _superagent = __webpack_require__(2); | ||
var _superagent2 = _interopRequireDefault(_superagent); | ||
var _segmentify = __webpack_require__(8); | ||
var _segmentify2 = _interopRequireDefault(_segmentify); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function getSegment(agent, linkHash) { | ||
return new Promise(function (resolve, reject) { | ||
var url = agent.url + '/segments/' + linkHash; | ||
_superagent2.default.get(url).end(function (err, res) { | ||
if (err) { | ||
/*eslint-disable*/ | ||
err.message = res && res.body.error ? res.body.error : err.message; | ||
err.status = res && res.statusCode; | ||
/*eslint-enable*/ | ||
reject(err); | ||
return; | ||
} | ||
resolve((0, _segmentify2.default)(agent, res.body)); | ||
}); | ||
}); | ||
} | ||
/***/ }, | ||
/* 14 */ | ||
/***/ function(module, exports, __webpack_require__) { | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.default = getMapIds; | ||
var _superagent = __webpack_require__(2); | ||
var _superagent2 = _interopRequireDefault(_superagent); | ||
var _makeQueryString = __webpack_require__(12); | ||
var _makeQueryString2 = _interopRequireDefault(_makeQueryString); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function getMapIds(agent) { | ||
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; | ||
return new Promise(function (resolve, reject) { | ||
var url = agent.url + '/maps' + (0, _makeQueryString2.default)(opts); | ||
_superagent2.default.get(url).end(function (err, res) { | ||
if (err) { | ||
/*eslint-disable*/ | ||
err.message = res && res.body.error ? res.body.error : err.message; | ||
err.status = res && res.statusCode; | ||
/*eslint-enable*/ | ||
reject(err); | ||
return; | ||
} | ||
resolve(res.body); | ||
}); | ||
}); | ||
} | ||
/***/ }, | ||
/* 15 */ | ||
/***/ function(module, exports, __webpack_require__) { | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.default = getLink; | ||
var _getSegment = __webpack_require__(13); | ||
var _getSegment2 = _interopRequireDefault(_getSegment); | ||
var _deprecated = __webpack_require__(9); | ||
var _deprecated2 = _interopRequireDefault(_deprecated); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function getLink(agent, hash) { | ||
(0, _deprecated2.default)('Agent#getLink(agent, hash)', 'Agent#getSegment(agent, hash)'); | ||
return (0, _getSegment2.default)(agent, hash); | ||
} | ||
/***/ }, | ||
/* 16 */ | ||
/***/ function(module, exports, __webpack_require__) { | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.default = getMap; | ||
var _findSegments = __webpack_require__(11); | ||
var _findSegments2 = _interopRequireDefault(_findSegments); | ||
var _deprecated = __webpack_require__(9); | ||
var _deprecated2 = _interopRequireDefault(_deprecated); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function getMap(agent, mapId) { | ||
var tags = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2]; | ||
(0, _deprecated2.default)('getMap(agent, mapId, tags = [])', 'findSegments(agent, filter)'); | ||
return (0, _findSegments2.default)(agent, { mapId: mapId, tags: tags }); | ||
} | ||
/***/ }, | ||
/* 17 */ | ||
/***/ function(module, exports, __webpack_require__) { | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.default = fromSegment; | ||
var _getAgent = __webpack_require__(1); | ||
var _getAgent2 = _interopRequireDefault(_getAgent); | ||
var _segmentify = __webpack_require__(8); | ||
var _segmentify2 = _interopRequireDefault(_segmentify); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function fromSegment(obj) { | ||
return (0, _getAgent2.default)(obj.meta.agentUrl || obj.meta.applicationLocation).then(function (agent) { | ||
var segment = (0, _segmentify2.default)(agent, obj); | ||
return { agent: agent, segment: segment }; | ||
}); | ||
} | ||
/***/ }, | ||
/* 18 */ | ||
/***/ function(module, exports, __webpack_require__) { | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.default = getApplication; | ||
var _getAgent = __webpack_require__(1); | ||
var _getAgent2 = _interopRequireDefault(_getAgent); | ||
var _deprecated = __webpack_require__(9); | ||
var _deprecated2 = _interopRequireDefault(_deprecated); | ||
var _config = __webpack_require__(19); | ||
var _config2 = _interopRequireDefault(_config); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function getApplication(name, url) { | ||
(0, _deprecated2.default)('getApplication(name, url)', 'getAgent(url)'); | ||
return (0, _getAgent2.default)(url || _config2.default.applicationUrl.replace('%s', name)); | ||
} | ||
/***/ }, | ||
/* 19 */ | ||
/***/ function(module, exports) { | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
// Deprecated. | ||
exports.default = { | ||
applicationUrl: 'https://%s.stratumn.rocks' | ||
}; | ||
/***/ }, | ||
/* 20 */ | ||
/***/ function(module, exports, __webpack_require__) { | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.default = loadLink; | ||
var _fromSegment = __webpack_require__(17); | ||
var _fromSegment2 = _interopRequireDefault(_fromSegment); | ||
var _deprecated = __webpack_require__(9); | ||
var _deprecated2 = _interopRequireDefault(_deprecated); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function loadLink(obj) { | ||
(0, _deprecated2.default)('loadLink(obj)', 'fromSegment(obj)'); | ||
return (0, _fromSegment2.default)(obj).then(function (_ref) { | ||
var segment = _ref.segment; | ||
return segment; | ||
}); | ||
} | ||
/***/ } | ||
/******/ ]) | ||
}); | ||
; | ||
}))); | ||
//# sourceMappingURL=stratumn-sdk.js.map |
@@ -1,1 +0,2 @@ | ||
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.StratumnSDK=e():t.StratumnSDK=e()}(this,function(){return function(t){function e(n){if(r[n])return r[n].exports;var s=r[n]={exports:{},id:n,loaded:!1};return t[n].call(s.exports,s,s.exports,e),s.loaded=!0,s.exports}var r={};return e.m=t,e.c=r,e.p="",e(0)}([function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}var s=r(1),i=n(s),o=r(17),a=n(o),u=r(18),l=n(u),c=r(20),d=n(c),f=r(19),h=n(f);t.exports={getAgent:i["default"],fromSegment:a["default"],getApplication:l["default"],loadLink:d["default"],config:h["default"]}},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function s(t){return new Promise(function(e,r){o["default"].get(t).end(function(n,s){if(n)return n.message=s&&s.body.error?s.body.error:n.message,n.status=s&&s.statusCode,void r(n);var i=s.body;i.url=t,i.createMap=u["default"].bind(null,i),i.getSegment=c["default"].bind(null,i),i.findSegments=f["default"].bind(null,i),i.getMapIds=p["default"].bind(null,i),i.getBranches=m["default"].bind(null,i),i.getLink=v["default"].bind(null,i),i.getMap=b["default"].bind(null,i),e(i)})})}Object.defineProperty(e,"__esModule",{value:!0}),e["default"]=s;var i=r(2),o=n(i),a=r(7),u=n(a),l=r(13),c=n(l),d=r(11),f=n(d),h=r(14),p=n(h),y=r(10),m=n(y),_=r(15),v=n(_),g=r(16),b=n(g)},function(t,e,r){function n(){}function s(t){if(!_(t))return t;var e=[];for(var r in t)null!=t[r]&&i(e,r,t[r]);return e.join("&")}function i(t,e,r){if(Array.isArray(r))return r.forEach(function(r){i(t,e,r)});if(_(r))for(var n in r)i(t,e+"["+n+"]",r[n]);else t.push(encodeURIComponent(e)+"="+encodeURIComponent(r))}function o(t){for(var e,r,n={},s=t.split("&"),i=0,o=s.length;o>i;++i)e=s[i],r=e.indexOf("="),-1==r?n[decodeURIComponent(e)]="":n[decodeURIComponent(e.slice(0,r))]=decodeURIComponent(e.slice(r+1));return n}function a(t){var e,r,n,s,i=t.split(/\r?\n/),o={};i.pop();for(var a=0,u=i.length;u>a;++a)r=i[a],e=r.indexOf(":"),n=r.slice(0,e).toLowerCase(),s=g(r.slice(e+1)),o[n]=s;return o}function u(t){return/[\/+]json\b/.test(t)}function l(t){return t.split(/ *; */).shift()}function c(t){return t.split(/ *; */).reduce(function(t,e){var r=e.split(/ *= */),n=r.shift(),s=r.shift();return n&&s&&(t[n]=s),t},{})}function d(t,e){e=e||{},this.req=t,this.xhr=this.req.xhr,this.text="HEAD"!=this.req.method&&(""===this.xhr.responseType||"text"===this.xhr.responseType)||"undefined"==typeof this.xhr.responseType?this.xhr.responseText:null,this.statusText=this.req.xhr.statusText,this._setStatusProperties(this.xhr.status),this.header=this.headers=a(this.xhr.getAllResponseHeaders()),this.header["content-type"]=this.xhr.getResponseHeader("content-type"),this._setHeaderProperties(this.header),this.body="HEAD"!=this.req.method?this._parseBody(this.text?this.text:this.xhr.response):null}function f(t,e){var r=this;this._query=this._query||[],this.method=t,this.url=e,this.header={},this._header={},this.on("end",function(){var t=null,e=null;try{e=new d(r)}catch(n){return t=new Error("Parser is unable to parse the response"),t.parse=!0,t.original=n,t.rawResponse=r.xhr&&r.xhr.responseText?r.xhr.responseText:null,t.statusCode=r.xhr&&r.xhr.status?r.xhr.status:null,r.callback(t)}r.emit("response",e);var s;try{(e.status<200||e.status>=300)&&(s=new Error(e.statusText||"Unsuccessful HTTP response"),s.original=t,s.response=e,s.status=e.status)}catch(n){s=n}s?r.callback(s,e):r.callback(null,e)})}function h(t,e){var r=v("DELETE",t);return e&&r.end(e),r}var p;"undefined"!=typeof window?p=window:"undefined"!=typeof self?p=self:(console.warn("Using browser-only version of superagent in non-browser environment"),p=this);var y=r(3),m=r(4),_=r(5),v=t.exports=r(6).bind(null,f);v.getXHR=function(){if(!(!p.XMLHttpRequest||p.location&&"file:"==p.location.protocol&&p.ActiveXObject))return new XMLHttpRequest;try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(t){}throw Error("Browser-only verison of superagent could not find XHR")};var g="".trim?function(t){return t.trim()}:function(t){return t.replace(/(^\s*|\s*$)/g,"")};v.serializeObject=s,v.parseString=o,v.types={html:"text/html",json:"application/json",xml:"application/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"},v.serialize={"application/x-www-form-urlencoded":s,"application/json":JSON.stringify},v.parse={"application/x-www-form-urlencoded":o,"application/json":JSON.parse},d.prototype.get=function(t){return this.header[t.toLowerCase()]},d.prototype._setHeaderProperties=function(t){var e=this.header["content-type"]||"";this.type=l(e);var r=c(e);for(var n in r)this[n]=r[n]},d.prototype._parseBody=function(t){var e=v.parse[this.type];return!e&&u(this.type)&&(e=v.parse["application/json"]),e&&t&&(t.length||t instanceof Object)?e(t):null},d.prototype._setStatusProperties=function(t){1223===t&&(t=204);var e=t/100|0;this.status=this.statusCode=t,this.statusType=e,this.info=1==e,this.ok=2==e,this.clientError=4==e,this.serverError=5==e,this.error=4==e||5==e?this.toError():!1,this.accepted=202==t,this.noContent=204==t,this.badRequest=400==t,this.unauthorized=401==t,this.notAcceptable=406==t,this.notFound=404==t,this.forbidden=403==t},d.prototype.toError=function(){var t=this.req,e=t.method,r=t.url,n="cannot "+e+" "+r+" ("+this.status+")",s=new Error(n);return s.status=this.status,s.method=e,s.url=r,s},v.Response=d,y(f.prototype);for(var b in m)f.prototype[b]=m[b];f.prototype.type=function(t){return this.set("Content-Type",v.types[t]||t),this},f.prototype.responseType=function(t){return this._responseType=t,this},f.prototype.accept=function(t){return this.set("Accept",v.types[t]||t),this},f.prototype.auth=function(t,e,r){switch(r||(r={type:"basic"}),r.type){case"basic":var n=btoa(t+":"+e);this.set("Authorization","Basic "+n);break;case"auto":this.username=t,this.password=e}return this},f.prototype.query=function(t){return"string"!=typeof t&&(t=s(t)),t&&this._query.push(t),this},f.prototype.attach=function(t,e,r){return this._getFormData().append(t,e,r||e.name),this},f.prototype._getFormData=function(){return this._formData||(this._formData=new p.FormData),this._formData},f.prototype.callback=function(t,e){var r=this._callback;this.clearTimeout(),r(t,e)},f.prototype.crossDomainError=function(){var t=new Error("Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.");t.crossDomain=!0,t.status=this.status,t.method=this.method,t.url=this.url,this.callback(t)},f.prototype._timeoutError=function(){var t=this._timeout,e=new Error("timeout of "+t+"ms exceeded");e.timeout=t,this.callback(e)},f.prototype._appendQueryString=function(){var t=this._query.join("&");t&&(this.url+=~this.url.indexOf("?")?"&"+t:"?"+t)},f.prototype.end=function(t){var e=this,r=this.xhr=v.getXHR(),s=this._timeout,i=this._formData||this._data;this._callback=t||n,r.onreadystatechange=function(){if(4==r.readyState){var t;try{t=r.status}catch(n){t=0}if(0==t){if(e.timedout)return e._timeoutError();if(e._aborted)return;return e.crossDomainError()}e.emit("end")}};var o=function(t){t.total>0&&(t.percent=t.loaded/t.total*100),t.direction="download",e.emit("progress",t)};this.hasListeners("progress")&&(r.onprogress=o);try{r.upload&&this.hasListeners("progress")&&(r.upload.onprogress=o)}catch(a){}if(s&&!this._timer&&(this._timer=setTimeout(function(){e.timedout=!0,e.abort()},s)),this._appendQueryString(),this.username&&this.password?r.open(this.method,this.url,!0,this.username,this.password):r.open(this.method,this.url,!0),this._withCredentials&&(r.withCredentials=!0),"GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof i&&!this._isHost(i)){var l=this._header["content-type"],c=this._serializer||v.serialize[l?l.split(";")[0]:""];!c&&u(l)&&(c=v.serialize["application/json"]),c&&(i=c(i))}for(var d in this.header)null!=this.header[d]&&r.setRequestHeader(d,this.header[d]);return this._responseType&&(r.responseType=this._responseType),this.emit("request",this),r.send("undefined"!=typeof i?i:null),this},v.Request=f,v.get=function(t,e,r){var n=v("GET",t);return"function"==typeof e&&(r=e,e=null),e&&n.query(e),r&&n.end(r),n},v.head=function(t,e,r){var n=v("HEAD",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n},v.options=function(t,e,r){var n=v("OPTIONS",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n},v.del=h,v["delete"]=h,v.patch=function(t,e,r){var n=v("PATCH",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n},v.post=function(t,e,r){var n=v("POST",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n},v.put=function(t,e,r){var n=v("PUT",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n}},function(t,e,r){function n(t){return t?s(t):void 0}function s(t){for(var e in n.prototype)t[e]=n.prototype[e];return t}t.exports=n,n.prototype.on=n.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},n.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},n.prototype.off=n.prototype.removeListener=n.prototype.removeAllListeners=n.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var n,s=0;s<r.length;s++)if(n=r[s],n===e||n.fn===e){r.splice(s,1);break}return this},n.prototype.emit=function(t){this._callbacks=this._callbacks||{};var e=[].slice.call(arguments,1),r=this._callbacks["$"+t];if(r){r=r.slice(0);for(var n=0,s=r.length;s>n;++n)r[n].apply(this,e)}return this},n.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},n.prototype.hasListeners=function(t){return!!this.listeners(t).length}},function(t,e,r){var n=r(5);e.clearTimeout=function(){return this._timeout=0,clearTimeout(this._timer),this},e.parse=function(t){return this._parser=t,this},e.serialize=function(t){return this._serializer=t,this},e.timeout=function(t){return this._timeout=t,this},e.then=function(t,e){if(!this._fullfilledPromise){var r=this;this._fullfilledPromise=new Promise(function(t,e){r.end(function(r,n){r?e(r):t(n)})})}return this._fullfilledPromise.then(t,e)},e.use=function(t){return t(this),this},e.get=function(t){return this._header[t.toLowerCase()]},e.getHeader=e.get,e.set=function(t,e){if(n(t)){for(var r in t)this.set(r,t[r]);return this}return this._header[t.toLowerCase()]=e,this.header[t]=e,this},e.unset=function(t){return delete this._header[t.toLowerCase()],delete this.header[t],this},e.field=function(t,e){return this._getFormData().append(t,e),this},e.abort=function(){return this._aborted?this:(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req&&this.req.abort(),this.clearTimeout(),this.emit("abort"),this)},e.withCredentials=function(){return this._withCredentials=!0,this},e.redirects=function(t){return this._maxRedirects=t,this},e.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},e._isHost=function(t){var e={}.toString.call(t);switch(e){case"[object File]":case"[object Blob]":case"[object FormData]":return!0;default:return!1}},e.send=function(t){var e=n(t),r=this._header["content-type"];if(e&&n(this._data))for(var s in t)this._data[s]=t[s];else"string"==typeof t?(r||this.type("form"),r=this._header["content-type"],"application/x-www-form-urlencoded"==r?this._data=this._data?this._data+"&"+t:t:this._data=(this._data||"")+t):this._data=t;return!e||this._isHost(t)?this:(r||this.type("json"),this)}},function(t,e){function r(t){return null!==t&&"object"==typeof t}t.exports=r},function(t,e){function r(t,e,r){return"function"==typeof r?new t("GET",e).end(r):2==arguments.length?new t("GET",e):new t(e,r)}t.exports=r},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function s(t){for(var e=arguments.length,r=Array(e>1?e-1:0),n=1;e>n;n++)r[n-1]=arguments[n];return new Promise(function(e,n){var s=t.url+"/segments";o["default"].post(s).send(r).end(function(r,s){var i=s.body.meta&&s.body.meta.errorMessage?new Error(s.body.meta.errorMessage):r;return i?(i.status=s&&s.statusCode,void n(i)):void e((0,u["default"])(t,s.body))})})}Object.defineProperty(e,"__esModule",{value:!0}),e["default"]=s;var i=r(2),o=n(i),a=r(8),u=n(a)},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function s(t,e){return Object.keys(t.agentInfo.actions).filter(function(t){return["init"].indexOf(t)<0}).forEach(function(r){e[r]=function(){for(var n=arguments.length,i=Array(n),a=0;n>a;a++)i[a]=arguments[a];return new Promise(function(n,a){var u=t.url+"/segments/"+e.meta.linkHash+"/"+r;o["default"].post(u).send(i).end(function(e,r){var i=r.body.meta&&r.body.meta.errorMessage?new Error(r.body.meta.errorMessage):e;return i?(i.status=r&&r.statusCode,void a(i)):void n(s(t,r.body))})})}}),e.getPrev=function(){return e.link.meta.prevLinkHash?t.getSegment(e.link.meta.prevLinkHash):Promise.resolve(null)},e.load=function(){return(0,u["default"])("segment#load()"),Promise.resolve(s(t,{link:JSON.parse(JSON.stringify(e.link)),meta:JSON.parse(JSON.stringify(e.meta))}))},e.getBranches=function(){for(var r=arguments.length,n=Array(r),s=0;r>s;s++)n[s]=arguments[s];return c["default"].apply(void 0,[t,e.meta.linkHash].concat(n))},e}Object.defineProperty(e,"__esModule",{value:!0}),e["default"]=s;var i=r(2),o=n(i),a=r(9),u=n(a),l=r(10),c=n(l)},function(t,e){"use strict";function r(t,e){e?console.warn("WARNING: "+t+" is deprecated. Please use "+e+" instead."):console.warn("WARNING: "+t+" is deprecated.")}Object.defineProperty(e,"__esModule",{value:!0}),e["default"]=r},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function s(t,e){var r=arguments.length<=2||void 0===arguments[2]?[]:arguments[2];return(0,u["default"])("Agent#getBranches(agent, prevLinkHash, tags = [])","Agent#findSegments(agent, filter)"),(0,o["default"])(t,{prevLinkHash:e,tags:r})}Object.defineProperty(e,"__esModule",{value:!0}),e["default"]=s;var i=r(11),o=n(i),a=r(9),u=n(a)},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function s(t){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return new Promise(function(r,n){var s=t.url+"/segments"+(0,c["default"])(e);o["default"].get(s).end(function(e,s){return e?(e.message=s&&s.body.error?s.body.error:e.message,e.status=s&&s.statusCode,void n(e)):void r(s.body.map(function(e){return(0,u["default"])(t,e)}))})})}Object.defineProperty(e,"__esModule",{value:!0}),e["default"]=s;var i=r(2),o=n(i),a=r(8),u=n(a),l=r(12),c=n(l)},function(t,e){"use strict";function r(t){var e=Object.keys(t).reduce(function(e,r){var n=Array.isArray(t[r])?t[r].join("+"):t[r];return e.push(encodeURIComponent(r)+"="+encodeURIComponent(n)),e},[]);return e.length?"?"+e.join("&"):""}Object.defineProperty(e,"__esModule",{value:!0}),e["default"]=r},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function s(t,e){return new Promise(function(r,n){var s=t.url+"/segments/"+e;o["default"].get(s).end(function(e,s){return e?(e.message=s&&s.body.error?s.body.error:e.message,e.status=s&&s.statusCode,void n(e)):void r((0,u["default"])(t,s.body))})})}Object.defineProperty(e,"__esModule",{value:!0}),e["default"]=s;var i=r(2),o=n(i),a=r(8),u=n(a)},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function s(t){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return new Promise(function(r,n){var s=t.url+"/maps"+(0,u["default"])(e);o["default"].get(s).end(function(t,e){return t?(t.message=e&&e.body.error?e.body.error:t.message,t.status=e&&e.statusCode,void n(t)):void r(e.body)})})}Object.defineProperty(e,"__esModule",{value:!0}),e["default"]=s;var i=r(2),o=n(i),a=r(12),u=n(a)},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function s(t,e){return(0,u["default"])("Agent#getLink(agent, hash)","Agent#getSegment(agent, hash)"),(0,o["default"])(t,e)}Object.defineProperty(e,"__esModule",{value:!0}),e["default"]=s;var i=r(13),o=n(i),a=r(9),u=n(a)},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function s(t,e){var r=arguments.length<=2||void 0===arguments[2]?[]:arguments[2];return(0,u["default"])("getMap(agent, mapId, tags = [])","findSegments(agent, filter)"),(0,o["default"])(t,{mapId:e,tags:r})}Object.defineProperty(e,"__esModule",{value:!0}),e["default"]=s;var i=r(11),o=n(i),a=r(9),u=n(a)},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function s(t){return(0,o["default"])(t.meta.agentUrl||t.meta.applicationLocation).then(function(e){var r=(0,u["default"])(e,t);return{agent:e,segment:r}})}Object.defineProperty(e,"__esModule",{value:!0}),e["default"]=s;var i=r(1),o=n(i),a=r(8),u=n(a)},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function s(t,e){return(0,u["default"])("getApplication(name, url)","getAgent(url)"),(0,o["default"])(e||c["default"].applicationUrl.replace("%s",t))}Object.defineProperty(e,"__esModule",{value:!0}),e["default"]=s;var i=r(1),o=n(i),a=r(9),u=n(a),l=r(19),c=n(l)},function(t,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e["default"]={applicationUrl:"https://%s.stratumn.rocks"}},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function s(t){return(0,u["default"])("loadLink(obj)","fromSegment(obj)"),(0,o["default"])(t).then(function(t){var e=t.segment;return e})}Object.defineProperty(e,"__esModule",{value:!0}),e["default"]=s;var i=r(17),o=n(i),a=r(9),u=n(a)}])}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.StratumnSDK=e.StratumnSDK||{})}(this,function(e){"use strict";function t(e,t){t?console.warn("WARNING: "+e+" is deprecated. Please use "+t+" instead."):console.warn("WARNING: "+e+" is deprecated.")}function n(e){var t=Object.keys(e).reduce(function(t,n){var r=Array.isArray(e[n])?e[n].join("+"):e[n];return t.push(encodeURIComponent(n)+"="+encodeURIComponent(r)),t},[]);return t.length?"?"+t.join("&"):""}function r(e){return e&&"object"==typeof e&&"default"in e?e.default:e}function o(e,t){return t={exports:{}},e(t,t.exports),t.exports}function s(e,t,n){return new Promise(function(r,o){ae({method:e,url:t,body:n},function(e,t){if(e){var n=e&&e.body&&e.body.meta&&e.body.meta.errorMessage?new Error(e.body.meta.errorMessage):e;n.status=e.status,o(n)}else r(t)})})}function u(e){return s("GET",e)}function a(e,t){return s("POST",e,t)}function i(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return u(e.url+"/segments"+n(t)).then(function(t){return t.body.map(function(t){return f(e,t)})})}function c(e,n){var r=arguments.length<=2||void 0===arguments[2]?[]:arguments[2];return t("Agent#getBranches(agent, prevLinkHash, tags = [])","Agent#findSegments(agent, filter)"),i(e,{prevLinkHash:n,tags:r})}function f(e,n){return Object.keys(e.agentInfo.actions).filter(function(e){return["init"].indexOf(e)<0}).forEach(function(t){n[t]=function(){for(var r=arguments.length,o=Array(r),s=0;s<r;s++)o[s]=arguments[s];return a(e.url+"/segments/"+n.meta.linkHash+"/"+t,o).then(function(t){return f(e,t.body)})}}),n.getPrev=function(){return n.link.meta.prevLinkHash?e.getSegment(n.link.meta.prevLinkHash):Promise.resolve(null)},n.load=function(){return t("segment#load()"),Promise.resolve(f(e,{link:JSON.parse(JSON.stringify(n.link)),meta:JSON.parse(JSON.stringify(n.meta))}))},n.getBranches=function(){for(var t=arguments.length,r=Array(t),o=0;o<t;o++)r[o]=arguments[o];return c.apply(void 0,[e,n.meta.linkHash].concat(r))},n}function p(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return a(e.url+"/segments",n).then(function(t){return f(e,t.body)})}function l(e,t){return u(e.url+"/segments/"+t).then(function(t){return f(e,t.body)})}function d(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return u(e.url+"/maps"+n(t)).then(function(e){return e.body})}function h(e,n){return t("Agent#getLink(agent, hash)","Agent#getSegment(agent, hash)"),l(e,n)}function g(e,n){var r=arguments.length<=2||void 0===arguments[2]?[]:arguments[2];return t("getMap(agent, mapId, tags = [])","findSegments(agent, filter)"),i(e,{mapId:n,tags:r})}function m(e){return u(e).then(function(t){var n=t.body;return n.url=e,n.createMap=p.bind(null,n),n.getSegment=l.bind(null,n),n.findSegments=i.bind(null,n),n.getMapIds=d.bind(null,n),n.getBranches=c.bind(null,n),n.getLink=h.bind(null,n),n.getMap=g.bind(null,n),n})}function y(e){return m(e.meta.agentUrl||e.meta.applicationLocation).then(function(t){var n=f(t,e);return{agent:t,segment:n}})}function b(e,n){return t("getApplication(name, url)","getAgent(url)"),m(n||ie.applicationUrl.replace("%s",e))}function v(e){return t("loadLink(obj)","fromSegment(obj)"),y(e).then(function(e){var t=e.segment;return t})}var R=o(function(e){e.exports={processRequest:function(e){var t=e.header("Content-Type"),n=t&&t.indexOf("application/json")!==-1;(null==t||n)&&e.body&&(t||e.header("Content-Type","application/json"),e.body=JSON.stringify(e.body))}}}),x=r(R),O=R.processRequest,q=Object.freeze({default:x,processRequest:O}),j=o(function(e){e.exports={processRequest:function(e){var t=e.header("Accept");null==t&&e.header("Accept","application/json")},processResponse:function(e){if(e.contentType&&/^.*\/(?:.*\+)?json(;|$)/i.test(e.contentType)){var t="string"==typeof e.body?e.body:e.text;t&&(e.body=JSON.parse(t))}}}}),k=r(j),A=j.processRequest,S=j.processResponse,T=Object.freeze({default:k,processRequest:A,processResponse:S}),w=o(function(e){var t=r(q),n=r(T);e.exports={processRequest:function(e){t.processRequest.call(this,e),n.processRequest.call(this,e)},processResponse:function(e){n.processResponse.call(this,e)}}}),H=r(w),E=o(function(e){e.exports={processRequest:function(e){e.url=e.url.replace(/[^%]+/g,function(e){return encodeURI(e)})}}}),L=r(E),P=E.processRequest,z=Object.freeze({default:L,processRequest:P}),C=o(function(e){e.exports=window.XMLHttpRequest}),I=r(C),N=Object.freeze({default:I}),M=o(function(e){e.exports=function(e){return function(){var t=Array.prototype.slice.call(arguments,0),n=function(){return e.apply(null,t)};setTimeout(n,0)}}}),U=r(M),J=Object.freeze({default:U}),G=o(function(e){function t(e){var t="string"==typeof e?{url:e}:e||{};this.method=t.method?t.method.toUpperCase():"GET",this.url=t.url,this.headers=t.headers||{},this.body=t.body,this.timeout=t.timeout||0,this.errorOn404=null==t.errorOn404||t.errorOn404,this.onload=t.onload,this.onerror=t.onerror}t.prototype.abort=function(){if(!this.aborted)return this.aborted=!0,this.xhr.abort(),this},t.prototype.header=function(e,t){var n;for(n in this.headers)if(this.headers.hasOwnProperty(n)&&e.toLowerCase()===n.toLowerCase()){if(1===arguments.length)return this.headers[n];delete this.headers[n];break}if(null!=t)return this.headers[e]=t,t},e.exports=t}),X=r(G),B=Object.freeze({default:X}),D=o(function(e){function t(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var r in n)n.hasOwnProperty(r)&&(e[r]=n[r])}return e}e.exports=t}),K=r(D),W=Object.freeze({default:K}),_=o(function(e){var t=r(W);e.exports=function(e){var n=e.xhr,r={request:e,xhr:n};try{var o,s,u,a={};if(n.getAllResponseHeaders)for(o=n.getAllResponseHeaders().split("\n"),s=0;s<o.length;s++)(u=o[s].match(/\s*([^\s]+):\s+([^\s]+)/))&&(a[u[1]]=u[2]);r=t(r,{status:n.status,contentType:n.contentType||n.getResponseHeader&&n.getResponseHeader("Content-Type"),headers:a,text:n.responseText,body:n.response||n.responseText})}catch(e){}return r}}),$=r(_),F=Object.freeze({default:$}),Q=o(function(e){function t(e){this.request=e.request,this.xhr=e.xhr,this.headers=e.headers||{},this.status=e.status||0,this.text=e.text,this.body=e.body,this.contentType=e.contentType,this.isHttpError=e.status>=400}var n=r(B),o=r(F);t.prototype.header=n.prototype.header,t.fromRequest=function(e){return new t(o(e))},e.exports=t}),V=r(Q),Y=Object.freeze({default:V}),Z=o(function(e){function t(e,t){var n=new Error(e);n.name="RequestError",this.name=n.name,this.message=n.message,n.stack&&(this.stack=n.stack),this.toString=function(){return this.message};for(var r in t)t.hasOwnProperty(r)&&(this[r]=t[r])}var n=r(Y),o=r(F),s=r(W);t.prototype=s(Error.prototype),t.prototype.constructor=t,t.create=function(e,r,s){var u=new t(e,s);return n.call(u,o(r)),u},e.exports=t}),ee=r(Z),te=Object.freeze({default:ee}),ne=o(function(e){e.exports=function(e){var t,n=!1;return function(){return n||(n=!0,t=e.apply(this,arguments)),t}}}),re=r(ne),oe=Object.freeze({default:re}),se=o(function(e){function t(e,r){function s(t,s){var i,d,h,g,m,y;for(t=new f(p(e,t)),o=0;o<r.length;o++)d=r[o],d.processRequest&&d.processRequest(t);for(o=0;o<r.length;o++)if(d=r[o],d.createXHR){i=d.createXHR(t);break}i=i||new u,t.xhr=i,h=l(a(function(e){clearTimeout(m),i.onload=i.onerror=i.onabort=i.onreadystatechange=i.ontimeout=i.onprogress=null;var u=n(t,e),a=u||c.fromRequest(t);for(o=0;o<r.length;o++)d=r[o],d.processResponse&&d.processResponse(a);u&&t.onerror&&t.onerror(u),!u&&t.onload&&t.onload(a),s&&s(u,u?void 0:a)})),y="onload"in i&&"onerror"in i,i.onload=function(){h()},i.onerror=h,i.onabort=function(){h()},i.onreadystatechange=function(){if(4===i.readyState){if(t.aborted)return h();if(!y){var e;try{e=i.status}catch(e){}var n=0===e?new Error("Internal XHR Error"):null;return h(n)}}},i.ontimeout=function(){},i.onprogress=function(){},i.open(t.method,t.url),t.timeout&&(m=setTimeout(function(){t.timedOut=!0,h();try{i.abort()}catch(e){}},t.timeout));for(g in t.headers)t.headers.hasOwnProperty(g)&&i.setRequestHeader(g,t.headers[g]);return i.send(t.body),t}e=e||{},r=r||[];var d,h=["get","post","put","head","patch","delete"],g=function(e){return function(t,n){return t=new f(t),t.method=e,s(t,n)}};for(o=0;o<h.length;o++)d=h[o],s[d]=g(d);return s.plugins=function(){return r},s.defaults=function(n){return n?t(p(e,n),r):e},s.use=function(){var n=Array.prototype.slice.call(arguments,0);return t(e,r.concat(n))},s.bare=function(){return t()},s.Request=f,s.Response=c,s.RequestError=i,s}function n(e,t){if(e.aborted)return d("Request aborted",e,{name:"Abort"});if(e.timedOut)return d("Request timeout",e,{name:"Timeout"});var n,r=e.xhr,o=Math.floor(r.status/100);switch(o){case 0:case 2:if(!t)return;return d(t.message,e);case 4:if(404===r.status&&!e.errorOn404)return;n="Client";break;case 5:n="Server";break;default:n="HTTP"}var s=n+" Error: The server returned a status of "+r.status+' for the request "'+e.method.toUpperCase()+" "+e.url+'"';return d(s,e)}var o,s=r(z),u=r(N),a=r(J),i=r(te),c=r(Y),f=r(B),p=r(W),l=r(oe),d=i.create;e.exports=t({},[s])}),ue=r(se),ae=ue.use(H),ie={applicationUrl:"https://%s.stratumn.rocks"};e.getAgent=m,e.fromSegment=y,e.getApplication=b,e.loadLink=v,e.config=ie,Object.defineProperty(e,"__esModule",{value:!0})}); | ||
//# sourceMappingURL=stratumn-sdk.min.js.map |
{ | ||
"name": "stratumn-sdk", | ||
"version": "1.4.0", | ||
"version": "1.5.0", | ||
"description": "Stratumn SDK for Javascript", | ||
"main": "lib/index.js", | ||
"main": "lib/stratumn-sdk.js", | ||
"jsnext:main": "lib/stratumn-sdk.mjs", | ||
"scripts": { | ||
"test": "mocha --compilers js:babel-core/register --recursive --require babel-polyfill --require should", | ||
"test:cov": "babel-node ./node_modules/isparta/bin/isparta cover ./node_modules/mocha/bin/_mocha -- --recursive --require should --require should", | ||
"test": "mocha --compilers js:babel-core/register --recursive --require babel-polyfill --require should 2> /dev/null", | ||
"test:cov": "babel-node ./node_modules/isparta/bin/isparta cover ./node_modules/mocha/bin/_mocha -- --recursive --require should --require should 2> /dev/null", | ||
"lint": "eslint src test", | ||
"check": "npm run lint && npm run test", | ||
"build:lib": "babel src --out-dir lib", | ||
"build:umd": "webpack src/index.js dist/stratumn-sdk.js --config webpack.config.js", | ||
"build:umd:min": "webpack src/index.js dist/stratumn-sdk.min.js --config webpack.min.config.js", | ||
"build:all": "npm run build:lib && npm run build:umd && npm run build:umd:min", | ||
"build:lib": "rollup -c rollup.es.config.js && rollup -c rollup.umd.config.js", | ||
"build:bower": "rollup -c rollup.bower.config.js", | ||
"build:bower:min": "rollup -c rollup.bower.min.config.js", | ||
"build:all": "npm run build:lib && npm run build:bower && npm run build:bower:min", | ||
"clean": "rimraf lib coverage", | ||
@@ -42,5 +43,7 @@ "preversion": "npm run clean && npm run check", | ||
"babel-eslint": "^6.0.0", | ||
"babel-loader": "^6.2.3", | ||
"babel-plugin-external-helpers": "^6.8.0", | ||
"babel-polyfill": "^6.5.0", | ||
"babel-preset-es2015": "^6.5.0", | ||
"babel-register": "^6.11.6", | ||
"babelrc-rollup": "^3.0.0", | ||
"eslint": "^2.3.0", | ||
@@ -52,10 +55,15 @@ "eslint-config-airbnb": "^6.0.2", | ||
"rimraf": "^2.5.2", | ||
"rollup": "^0.34.10", | ||
"rollup-plugin-babel": "^2.6.1", | ||
"rollup-plugin-commonjs": "^3.3.1", | ||
"rollup-plugin-node-resolve": "^2.0.0", | ||
"rollup-plugin-uglify": "^1.0.1", | ||
"rollup-pluginutils": "^1.5.1", | ||
"should": "^8.2.2", | ||
"stratumn-agent": "^0.12.3", | ||
"stratumn-agent-js": "^0.2.1", | ||
"webpack": "^1.12.14" | ||
"stratumn-agent": "^0.12.3" | ||
}, | ||
"dependencies": { | ||
"superagent": "^2.1.0" | ||
"httpplease": "^0.16.4", | ||
"xmlhttprequest": "~1.7.0" | ||
} | ||
} |
# Stratumn SDK for Javascript [ALPHA - incompatible with production] | ||
[![Build Status](https://travis-ci.org/stratumn/stratumn-sdk-js.svg?branch=alpha)](https://travis-ci.org/stratumn/stratumn-sdk-js) | ||
[![codecov](https://codecov.io/gh/stratumn/stratumn-sdk-js/branch/alpha/graph/badge.svg)](https://codecov.io/gh/stratumn/stratumn-sdk-js) | ||
[![codecov](https://codecov.io/gh/stratumn/stratumn-sdk-js/branch/alpha/graph/badge.svg)](https://codecov.io/gh/stratumn/stratumn-sdk-js/branch/alpha) | ||
[![Build Status](https://david-dm.org/stratumn/stratumn-sdk-js.svg?branch=alpha)](https://david-dm.org/stratumn/stratumn-sdk-js) | ||
@@ -6,0 +6,0 @@ |
@@ -1,25 +0,7 @@ | ||
import request from 'superagent'; | ||
import segmentify from './segmentify'; | ||
import { post } from './request'; | ||
export default function createMap(agent, ...args) { | ||
return new Promise((resolve, reject) => { | ||
const url = `${agent.url}/segments`; | ||
request | ||
.post(url) | ||
.send(args) | ||
.end((err, res) => { | ||
const error = (res.body.meta && res.body.meta.errorMessage) | ||
? new Error(res.body.meta.errorMessage) | ||
: err; | ||
if (error) { | ||
error.status = res && res.statusCode; | ||
reject(error); | ||
return; | ||
} | ||
resolve(segmentify(agent, res.body)); | ||
}); | ||
}); | ||
return post(`${agent.url}/segments`, args) | ||
.then(res => segmentify(agent, res.body)); | ||
} |
@@ -1,24 +0,8 @@ | ||
import request from 'superagent'; | ||
import segmentify from './segmentify'; | ||
import makeQueryString from './makeQueryString'; | ||
import { get } from './request'; | ||
export default function findSegments(agent, opts = {}) { | ||
return new Promise((resolve, reject) => { | ||
const url = `${agent.url}/segments${makeQueryString(opts)}`; | ||
request | ||
.get(url) | ||
.end((err, res) => { | ||
if (err) { | ||
/*eslint-disable*/ | ||
err.message = res && res.body.error ? res.body.error : err.message; | ||
err.status = res && res.statusCode; | ||
/*eslint-enable*/ | ||
reject(err); | ||
return; | ||
} | ||
resolve(res.body.map(obj => segmentify(agent, obj))); | ||
}); | ||
}); | ||
return get(`${agent.url}/segments${makeQueryString(opts)}`) | ||
.then(res => res.body.map(obj => segmentify(agent, obj))); | ||
} |
@@ -1,2 +0,1 @@ | ||
import request from 'superagent'; | ||
import createMap from './createMap'; | ||
@@ -6,2 +5,3 @@ import getSegment from './getSegment'; | ||
import getMapIds from './getMapIds'; | ||
import { get } from './request'; | ||
@@ -14,31 +14,19 @@ // Deprecated. | ||
export default function getAgent(url) { | ||
return new Promise((resolve, reject) => { | ||
request | ||
.get(url) | ||
.end((err, res) => { | ||
if (err) { | ||
/*eslint-disable*/ | ||
err.message = res && res.body.error ? res.body.error : err.message; | ||
err.status = res && res.statusCode; | ||
/*eslint-enable*/ | ||
reject(err); | ||
return; | ||
} | ||
return get(url) | ||
.then(res => { | ||
const agent = res.body; | ||
const agent = res.body; | ||
agent.url = url; | ||
agent.createMap = createMap.bind(null, agent); | ||
agent.getSegment = getSegment.bind(null, agent); | ||
agent.findSegments = findSegments.bind(null, agent); | ||
agent.getMapIds = getMapIds.bind(null, agent); | ||
agent.url = url; | ||
agent.createMap = createMap.bind(null, agent); | ||
agent.getSegment = getSegment.bind(null, agent); | ||
agent.findSegments = findSegments.bind(null, agent); | ||
agent.getMapIds = getMapIds.bind(null, agent); | ||
// Deprecated. | ||
agent.getBranches = getBranches.bind(null, agent); | ||
agent.getLink = getLink.bind(null, agent); | ||
agent.getMap = getMap.bind(null, agent); | ||
// Deprecated. | ||
agent.getBranches = getBranches.bind(null, agent); | ||
agent.getLink = getLink.bind(null, agent); | ||
agent.getMap = getMap.bind(null, agent); | ||
resolve(agent); | ||
}); | ||
}); | ||
return agent; | ||
}); | ||
} |
@@ -1,23 +0,7 @@ | ||
import request from 'superagent'; | ||
import makeQueryString from './makeQueryString'; | ||
import { get } from './request'; | ||
export default function getMapIds(agent, opts = {}) { | ||
return new Promise((resolve, reject) => { | ||
const url = `${agent.url}/maps${makeQueryString(opts)}`; | ||
request | ||
.get(url) | ||
.end((err, res) => { | ||
if (err) { | ||
/*eslint-disable*/ | ||
err.message = res && res.body.error ? res.body.error : err.message; | ||
err.status = res && res.statusCode; | ||
/*eslint-enable*/ | ||
reject(err); | ||
return; | ||
} | ||
resolve(res.body); | ||
}); | ||
}); | ||
return get(`${agent.url}/maps${makeQueryString(opts)}`) | ||
.then(res => res.body); | ||
} |
@@ -1,23 +0,7 @@ | ||
import request from 'superagent'; | ||
import segmentify from './segmentify'; | ||
import { get } from './request'; | ||
export default function getSegment(agent, linkHash) { | ||
return new Promise((resolve, reject) => { | ||
const url = `${agent.url}/segments/${linkHash}`; | ||
request | ||
.get(url) | ||
.end((err, res) => { | ||
if (err) { | ||
/*eslint-disable*/ | ||
err.message = res && res.body.error ? res.body.error : err.message; | ||
err.status = res && res.statusCode; | ||
/*eslint-enable*/ | ||
reject(err); | ||
return; | ||
} | ||
resolve(segmentify(agent, res.body)); | ||
}); | ||
}); | ||
return get(`${agent.url}/segments/${linkHash}`) | ||
.then(res => segmentify(agent, res.body)); | ||
} |
@@ -1,17 +0,7 @@ | ||
import getAgent from './getAgent'; | ||
import fromSegment from './fromSegment'; | ||
export { default as getAgent } from './getAgent'; | ||
export { default as fromSegment } from './fromSegment'; | ||
// Deprecated. | ||
import getApplication from './getApplication'; | ||
import loadLink from './loadLink'; | ||
import config from './config'; | ||
module.exports = { | ||
getAgent, | ||
fromSegment, | ||
// Deprecated. | ||
getApplication, | ||
loadLink, | ||
config | ||
}; | ||
export { default as getApplication } from './getApplication'; | ||
export { default as loadLink } from './loadLink'; | ||
export { default as config } from './config'; |
@@ -1,4 +0,4 @@ | ||
import request from 'superagent'; | ||
import deprecated from './deprecated'; | ||
import getBranches from './getBranches'; | ||
import { post } from './request'; | ||
@@ -12,23 +12,4 @@ export default function segmentify(agent, obj) { | ||
obj[key] = (...args) => | ||
new Promise((resolve, reject) => { | ||
const url = `${agent.url}/segments/${obj.meta.linkHash}/${key}`; | ||
/*eslint-enable*/ | ||
request | ||
.post(url) | ||
.send(args) | ||
.end((err, res) => { | ||
const error = (res.body.meta && res.body.meta.errorMessage) | ||
? new Error(res.body.meta.errorMessage) | ||
: err; | ||
if (error) { | ||
error.status = res && res.statusCode; | ||
reject(error); | ||
return; | ||
} | ||
resolve(segmentify(agent, res.body)); | ||
}); | ||
}); | ||
post(`${agent.url}/segments/${obj.meta.linkHash}/${key}`, args) | ||
.then(res => segmentify(agent, res.body)) | ||
}); | ||
@@ -35,0 +16,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 2 instances in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
152961
2
22
41
1292
7
+ Addedhttpplease@^0.16.4
+ Addedxmlhttprequest@~1.7.0
+ Addedhttpplease@0.16.4(transitive)
+ Addedurllite@0.5.0(transitive)
+ Addedxmlhttprequest@1.7.0(transitive)
+ Addedxtend@3.0.04.0.2(transitive)
- Removedsuperagent@^2.1.0
- Removedasync@1.5.2(transitive)
- Removedcall-bind@1.0.7(transitive)
- Removedcombined-stream@1.0.8(transitive)
- Removedcomponent-emitter@1.3.1(transitive)
- Removedcookiejar@2.1.4(transitive)
- Removedcore-util-is@1.0.3(transitive)
- Removeddebug@2.6.9(transitive)
- Removeddefine-data-property@1.1.4(transitive)
- Removeddelayed-stream@1.0.0(transitive)
- Removedes-define-property@1.0.0(transitive)
- Removedes-errors@1.3.0(transitive)
- Removedextend@3.0.2(transitive)
- Removedform-data@1.0.0-rc4(transitive)
- Removedformidable@1.2.6(transitive)
- Removedfunction-bind@1.1.2(transitive)
- Removedget-intrinsic@1.2.4(transitive)
- Removedgopd@1.0.1(transitive)
- Removedhas-property-descriptors@1.0.2(transitive)
- Removedhas-proto@1.0.3(transitive)
- Removedhas-symbols@1.0.3(transitive)
- Removedhasown@2.0.2(transitive)
- Removedinherits@2.0.4(transitive)
- Removedisarray@1.0.0(transitive)
- Removedmethods@1.1.2(transitive)
- Removedmime@1.6.0(transitive)
- Removedmime-db@1.52.0(transitive)
- Removedmime-types@2.1.35(transitive)
- Removedms@2.0.0(transitive)
- Removedobject-inspect@1.13.2(transitive)
- Removedprocess-nextick-args@2.0.1(transitive)
- Removedqs@6.13.0(transitive)
- Removedreadable-stream@2.3.8(transitive)
- Removedsafe-buffer@5.1.2(transitive)
- Removedset-function-length@1.2.2(transitive)
- Removedside-channel@1.0.6(transitive)
- Removedstring_decoder@1.1.1(transitive)
- Removedsuperagent@2.3.0(transitive)
- Removedutil-deprecate@1.0.2(transitive)