stratumn-agent-client
Advanced tools
Comparing version 1.6.0 to 1.7.1
@@ -50,2 +50,37 @@ (function (global, factory) { | ||
/* | ||
Copyright (C) 2017 Stratumn SAS | ||
This Source Code Form is subject to the terms of the Mozilla Public | ||
License, v. 2.0. If a copy of the MPL was not distributed with this | ||
file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
*/ | ||
/** | ||
* Calls a function that returns a Promise until a condition is reached | ||
* @param {function} condition - while condition is true body will keep being called | ||
* @param {function} body - a function that is repeatedly called while condition is true | ||
* @returns {Promise} a Promise that resolves when the condition is no longer true | ||
*/ | ||
function promiseWhile(condition, body) { | ||
return new Promise(function (resolve, reject) { | ||
function loop() { | ||
body().then(function () { | ||
// When the result of calling `condition` is no longer true, we are | ||
// done. | ||
if (!condition()) { | ||
resolve(); | ||
} else { | ||
loop(); | ||
} | ||
}).catch(reject); | ||
} | ||
// Start running the loop in the next tick so that this function is | ||
// completely async. It would be unexpected if `body` was called | ||
// synchronously the first time. | ||
setImmediate(loop); | ||
}); | ||
} | ||
function interopDefault(ex) { | ||
@@ -675,2 +710,125 @@ return ex && typeof ex === 'object' && 'default' in ex ? ex['default'] : ex; | ||
var asyncGenerator = function () { | ||
function AwaitValue(value) { | ||
this.value = value; | ||
} | ||
function AsyncGenerator(gen) { | ||
var front, back; | ||
function send(key, arg) { | ||
return new Promise(function (resolve, reject) { | ||
var request = { | ||
key: key, | ||
arg: arg, | ||
resolve: resolve, | ||
reject: reject, | ||
next: null | ||
}; | ||
if (back) { | ||
back = back.next = request; | ||
} else { | ||
front = back = request; | ||
resume(key, arg); | ||
} | ||
}); | ||
} | ||
function resume(key, arg) { | ||
try { | ||
var result = gen[key](arg); | ||
var value = result.value; | ||
if (value instanceof AwaitValue) { | ||
Promise.resolve(value.value).then(function (arg) { | ||
resume("next", arg); | ||
}, function (arg) { | ||
resume("throw", arg); | ||
}); | ||
} else { | ||
settle(result.done ? "return" : "normal", result.value); | ||
} | ||
} catch (err) { | ||
settle("throw", err); | ||
} | ||
} | ||
function settle(type, value) { | ||
switch (type) { | ||
case "return": | ||
front.resolve({ | ||
value: value, | ||
done: true | ||
}); | ||
break; | ||
case "throw": | ||
front.reject(value); | ||
break; | ||
default: | ||
front.resolve({ | ||
value: value, | ||
done: false | ||
}); | ||
break; | ||
} | ||
front = front.next; | ||
if (front) { | ||
resume(front.key, front.arg); | ||
} else { | ||
back = null; | ||
} | ||
} | ||
this._invoke = send; | ||
if (typeof gen.return !== "function") { | ||
this.return = undefined; | ||
} | ||
} | ||
if (typeof Symbol === "function" && Symbol.asyncIterator) { | ||
AsyncGenerator.prototype[Symbol.asyncIterator] = function () { | ||
return this; | ||
}; | ||
} | ||
AsyncGenerator.prototype.next = function (arg) { | ||
return this._invoke("next", arg); | ||
}; | ||
AsyncGenerator.prototype.throw = function (arg) { | ||
return this._invoke("throw", arg); | ||
}; | ||
AsyncGenerator.prototype.return = function (arg) { | ||
return this._invoke("return", arg); | ||
}; | ||
return { | ||
wrap: function (fn) { | ||
return function () { | ||
return new AsyncGenerator(fn.apply(this, arguments)); | ||
}; | ||
}, | ||
await: function (value) { | ||
return new AwaitValue(value); | ||
} | ||
}; | ||
}(); | ||
var toConsumableArray = function (arr) { | ||
if (Array.isArray(arr)) { | ||
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; | ||
return arr2; | ||
} else { | ||
return Array.from(arr); | ||
} | ||
}; | ||
/* | ||
@@ -684,10 +842,31 @@ Copyright (C) 2017 Stratumn SAS | ||
var DEFAULT_BATCH_SIZE = 20; | ||
function findSegments(agent) { | ||
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
return get(agent.url + '/segments' + makeQueryString(opts)).then(function (res) { | ||
return res.body.map(function (obj) { | ||
return segmentify(agent, obj); | ||
}); | ||
var options = Object.assign({}, opts); | ||
if (opts.limit === -1) { | ||
options.limit = options.batchSize || DEFAULT_BATCH_SIZE; | ||
delete options.batchSize; | ||
options.offset = 0; | ||
var segments = []; | ||
return promiseWhile(function () { | ||
return segments.length === options.limit; | ||
}, function () { | ||
return findSegments(agent, options).then(function (newSegments) { | ||
segments.push.apply(segments, toConsumableArray(newSegments)); | ||
options.offset += options.limit; | ||
}); | ||
}).then(function () { | ||
return segments; | ||
}); | ||
} | ||
return get(agent.url + '/segments' + makeQueryString(opts)).then(function (res) { | ||
return res.body.map(function (obj) { | ||
return segmentify(agent, obj); | ||
}); | ||
}); | ||
} | ||
@@ -694,0 +873,0 @@ |
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.StratumnAgentClient=e.StratumnAgentClient||{})}(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,T=j.processResponse,w=Object.freeze({default:k,processRequest:A,processResponse:T}),S=o(function(e){var t=r(q),n=r(w);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(S),C=o(function(e){e.exports={processRequest:function(e){e.url=e.url.replace(/[^%]+/g,function(e){return encodeURI(e)})}}}),E=r(C),L=C.processRequest,P=Object.freeze({default:E,processRequest:L}),z=o(function(e){e.exports=window.XMLHttpRequest}),I=r(z),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}),W=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}),_=r(W),$=Object.freeze({default:_}),D=o(function(e){var t=r($);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}}),F=r(D),K=Object.freeze({default:F}),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(K);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(K),s=r($);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(P),u=r(N),a=r(J),i=r(te),c=r(Y),f=r(B),p=r($),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})}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.StratumnAgentClient=e.StratumnAgentClient||{})}(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,t){return new Promise(function(n,r){function o(){t().then(function(){e()?o():n()}).catch(r)}setImmediate(o)})}function o(e){return e&&"object"==typeof e&&"default"in e?e.default:e}function s(e,t){return t={exports:{}},e(t,t.exports),t.exports}function u(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 i(e){return u("GET",e)}function a(e,t){return u("POST",e,t)}function c(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=Object.assign({},t);if(t.limit===-1){o.limit=o.batchSize||fe,delete o.batchSize,o.offset=0;var s=[];return r(function(){return s.length===o.limit},function(){return c(e,o).then(function(e){s.push.apply(s,ce(e)),o.offset+=o.limit})}).then(function(){return s})}return i(e.url+"/segments"+n(t)).then(function(t){return t.body.map(function(t){return l(e,t)})})}function f(e,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];return t("Agent#getBranches(agent, prevLinkHash, tags = [])","Agent#findSegments(agent, filter)"),c(e,{prevLinkHash:n,tags:r})}function l(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 l(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(l(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 f.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 l(e,t.body)})}function h(e,t){return i(e.url+"/segments/"+t).then(function(t){return l(e,t.body)})}function d(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return i(e.url+"/maps"+n(t)).then(function(e){return e.body})}function g(e,n){return t("Agent#getLink(agent, hash)","Agent#getSegment(agent, hash)"),h(e,n)}function y(e,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];return t("getMap(agent, mapId, tags = [])","findSegments(agent, filter)"),c(e,{mapId:n,tags:r})}function m(e){return i(e).then(function(t){var n=t.body;return n.url=e,n.createMap=p.bind(null,n),n.getSegment=h.bind(null,n),n.findSegments=c.bind(null,n),n.getMapIds=d.bind(null,n),n.getBranches=f.bind(null,n),n.getLink=g.bind(null,n),n.getMap=y.bind(null,n),n})}function v(e){return m(e.meta.agentUrl||e.meta.applicationLocation).then(function(t){var n=l(t,e);return{agent:t,segment:n}})}function b(e,n){return t("getApplication(name, url)","getAgent(url)"),m(n||le.applicationUrl.replace("%s",e))}function R(e){return t("loadLink(obj)","fromSegment(obj)"),v(e).then(function(e){var t=e.segment;return t})}var x=s(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))}}}),O=o(x),k=x.processRequest,w=Object.freeze({default:O,processRequest:k}),A=s(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))}}}}),j=o(A),q=A.processRequest,S=A.processResponse,T=Object.freeze({default:j,processRequest:q,processResponse:S}),H=s(function(e){var t=o(w),n=o(T);e.exports={processRequest:function(e){t.processRequest.call(this,e),n.processRequest.call(this,e)},processResponse:function(e){n.processResponse.call(this,e)}}}),P=o(H),z=s(function(e){e.exports={processRequest:function(e){e.url=e.url.replace(/[^%]+/g,function(e){return encodeURI(e)})}}}),I=o(z),C=z.processRequest,E=Object.freeze({default:I,processRequest:C}),L=s(function(e){e.exports=window.XMLHttpRequest}),N=o(L),M=Object.freeze({default:N}),U=s(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)}}}),J=o(U),_=Object.freeze({default:J}),G=s(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=o(G),B=Object.freeze({default:X}),W=s(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}),$=o(W),D=Object.freeze({default:$}),F=s(function(e){var t=o(D);e.exports=function(e){var n=e.xhr,r={request:e,xhr:n};try{var o,s,u,i={};if(n.getAllResponseHeaders)for(o=n.getAllResponseHeaders().split("\n"),s=0;s<o.length;s++)(u=o[s].match(/\s*([^\s]+):\s+([^\s]+)/))&&(i[u[1]]=u[2]);r=t(r,{status:n.status,contentType:n.contentType||n.getResponseHeader&&n.getResponseHeader("Content-Type"),headers:i,text:n.responseText,body:n.response||n.responseText})}catch(e){}return r}}),K=o(F),Q=Object.freeze({default:K}),V=s(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=o(B),r=o(Q);t.prototype.header=n.prototype.header,t.fromRequest=function(e){return new t(r(e))},e.exports=t}),Y=o(V),Z=Object.freeze({default:Y}),ee=s(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=o(Z),r=o(Q),s=o(D);t.prototype=s(Error.prototype),t.prototype.constructor=t,t.create=function(e,o,s){var u=new t(e,s);return n.call(u,r(o)),u},e.exports=t}),te=o(ee),ne=Object.freeze({default:te}),re=s(function(e){e.exports=function(e){var t,n=!1;return function(){return n||(n=!0,t=e.apply(this,arguments)),t}}}),oe=o(re),se=Object.freeze({default:oe}),ue=s(function(e){function t(e,o){function s(t,s){var a,h,d,g,y,m;for(t=new f(l(e,t)),r=0;r<o.length;r++)h=o[r],h.processRequest&&h.processRequest(t);for(r=0;r<o.length;r++)if(h=o[r],h.createXHR){a=h.createXHR(t);break}a=a||new u,t.xhr=a,d=p(i(function(e){clearTimeout(y),a.onload=a.onerror=a.onabort=a.onreadystatechange=a.ontimeout=a.onprogress=null;var u=n(t,e),i=u||c.fromRequest(t);for(r=0;r<o.length;r++)h=o[r],h.processResponse&&h.processResponse(i);u&&t.onerror&&t.onerror(u),!u&&t.onload&&t.onload(i),s&&s(u,u?void 0:i)})),m="onload"in a&&"onerror"in a,a.onload=function(){d()},a.onerror=d,a.onabort=function(){d()},a.onreadystatechange=function(){if(4===a.readyState){if(t.aborted)return d();if(!m){var e;try{e=a.status}catch(e){}var n=0===e?new Error("Internal XHR Error"):null;return d(n)}}},a.ontimeout=function(){},a.onprogress=function(){},a.open(t.method,t.url),t.timeout&&(y=setTimeout(function(){t.timedOut=!0,d();try{a.abort()}catch(e){}},t.timeout));for(g in t.headers)t.headers.hasOwnProperty(g)&&a.setRequestHeader(g,t.headers[g]);return a.send(t.body),t}e=e||{},o=o||[];var h,d=["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(r=0;r<d.length;r++)h=d[r],s[h]=g(h);return s.plugins=function(){return o},s.defaults=function(n){return n?t(l(e,n),o):e},s.use=function(){var n=Array.prototype.slice.call(arguments,0);return t(e,o.concat(n))},s.bare=function(){return t()},s.Request=f,s.Response=c,s.RequestError=a,s}function n(e,t){if(e.aborted)return h("Request aborted",e,{name:"Abort"});if(e.timedOut)return h("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 h(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 h(s,e)}var r,s=o(E),u=o(M),i=o(_),a=o(ne),c=o(Z),f=o(B),l=o(D),p=o(se),h=a.create;e.exports=t({},[s])}),ie=o(ue),ae=ie.use(P),ce=(function(){function e(e){this.value=e}function t(t){function n(e,t){return new Promise(function(n,o){var i={key:e,arg:t,resolve:n,reject:o,next:null};u?u=u.next=i:(s=u=i,r(e,t))})}function r(n,s){try{var u=t[n](s),i=u.value;i instanceof e?Promise.resolve(i.value).then(function(e){r("next",e)},function(e){r("throw",e)}):o(u.done?"return":"normal",u.value)}catch(e){o("throw",e)}}function o(e,t){switch(e){case"return":s.resolve({value:t,done:!0});break;case"throw":s.reject(t);break;default:s.resolve({value:t,done:!1})}s=s.next,s?r(s.key,s.arg):u=null}var s,u;this._invoke=n,"function"!=typeof t.return&&(this.return=void 0)}return"function"==typeof Symbol&&Symbol.asyncIterator&&(t.prototype[Symbol.asyncIterator]=function(){return this}),t.prototype.next=function(e){return this._invoke("next",e)},t.prototype.throw=function(e){return this._invoke("throw",e)},t.prototype.return=function(e){return this._invoke("return",e)},{wrap:function(e){return function(){return new t(e.apply(this,arguments))}},await:function(t){return new e(t)}}}(),function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}),fe=20,le={applicationUrl:"https://%s.stratumn.rocks"};e.getAgent=m,e.fromSegment=v,e.getApplication=b,e.loadLink=R,e.config=le,Object.defineProperty(e,"__esModule",{value:!0})}); | ||
//# sourceMappingURL=stratumn-agent-client.min.js.map |
(function (global, factory) { | ||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('httpplease/plugins/json'), require('httpplease')) : | ||
typeof define === 'function' && define.amd ? define(['exports', 'httpplease/plugins/json', 'httpplease'], factory) : | ||
(factory((global.StratumnAgentClient = global.StratumnAgentClient || {}),global.json,global.httpplease)); | ||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('httpplease/plugins/json'), require('httpplease')) : | ||
typeof define === 'function' && define.amd ? define(['exports', 'httpplease/plugins/json', 'httpplease'], factory) : | ||
(factory((global.StratumnAgentClient = global.StratumnAgentClient || {}),global.json,global.httpplease)); | ||
}(this, (function (exports,json,httpplease) { 'use strict'; | ||
@@ -61,2 +61,37 @@ | ||
/** | ||
* Calls a function that returns a Promise until a condition is reached | ||
* @param {function} condition - while condition is true body will keep being called | ||
* @param {function} body - a function that is repeatedly called while condition is true | ||
* @returns {Promise} a Promise that resolves when the condition is no longer true | ||
*/ | ||
function promiseWhile(condition, body) { | ||
return new Promise(function (resolve, reject) { | ||
function loop() { | ||
body().then(function () { | ||
// When the result of calling `condition` is no longer true, we are | ||
// done. | ||
if (!condition()) { | ||
resolve(); | ||
} else { | ||
loop(); | ||
} | ||
}).catch(reject); | ||
} | ||
// Start running the loop in the next tick so that this function is | ||
// completely async. It would be unexpected if `body` was called | ||
// synchronously the first time. | ||
setImmediate(loop); | ||
}); | ||
} | ||
/* | ||
Copyright (C) 2017 Stratumn SAS | ||
This Source Code Form is subject to the terms of the Mozilla Public | ||
License, v. 2.0. If a copy of the MPL was not distributed with this | ||
file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
*/ | ||
var request = httpplease.use(json); | ||
@@ -86,2 +121,125 @@ | ||
var asyncGenerator = function () { | ||
function AwaitValue(value) { | ||
this.value = value; | ||
} | ||
function AsyncGenerator(gen) { | ||
var front, back; | ||
function send(key, arg) { | ||
return new Promise(function (resolve, reject) { | ||
var request = { | ||
key: key, | ||
arg: arg, | ||
resolve: resolve, | ||
reject: reject, | ||
next: null | ||
}; | ||
if (back) { | ||
back = back.next = request; | ||
} else { | ||
front = back = request; | ||
resume(key, arg); | ||
} | ||
}); | ||
} | ||
function resume(key, arg) { | ||
try { | ||
var result = gen[key](arg); | ||
var value = result.value; | ||
if (value instanceof AwaitValue) { | ||
Promise.resolve(value.value).then(function (arg) { | ||
resume("next", arg); | ||
}, function (arg) { | ||
resume("throw", arg); | ||
}); | ||
} else { | ||
settle(result.done ? "return" : "normal", result.value); | ||
} | ||
} catch (err) { | ||
settle("throw", err); | ||
} | ||
} | ||
function settle(type, value) { | ||
switch (type) { | ||
case "return": | ||
front.resolve({ | ||
value: value, | ||
done: true | ||
}); | ||
break; | ||
case "throw": | ||
front.reject(value); | ||
break; | ||
default: | ||
front.resolve({ | ||
value: value, | ||
done: false | ||
}); | ||
break; | ||
} | ||
front = front.next; | ||
if (front) { | ||
resume(front.key, front.arg); | ||
} else { | ||
back = null; | ||
} | ||
} | ||
this._invoke = send; | ||
if (typeof gen.return !== "function") { | ||
this.return = undefined; | ||
} | ||
} | ||
if (typeof Symbol === "function" && Symbol.asyncIterator) { | ||
AsyncGenerator.prototype[Symbol.asyncIterator] = function () { | ||
return this; | ||
}; | ||
} | ||
AsyncGenerator.prototype.next = function (arg) { | ||
return this._invoke("next", arg); | ||
}; | ||
AsyncGenerator.prototype.throw = function (arg) { | ||
return this._invoke("throw", arg); | ||
}; | ||
AsyncGenerator.prototype.return = function (arg) { | ||
return this._invoke("return", arg); | ||
}; | ||
return { | ||
wrap: function (fn) { | ||
return function () { | ||
return new AsyncGenerator(fn.apply(this, arguments)); | ||
}; | ||
}, | ||
await: function (value) { | ||
return new AwaitValue(value); | ||
} | ||
}; | ||
}(); | ||
var toConsumableArray = function (arr) { | ||
if (Array.isArray(arr)) { | ||
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; | ||
return arr2; | ||
} else { | ||
return Array.from(arr); | ||
} | ||
}; | ||
/* | ||
@@ -95,10 +253,31 @@ Copyright (C) 2017 Stratumn SAS | ||
var DEFAULT_BATCH_SIZE = 20; | ||
function findSegments(agent) { | ||
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
return get(agent.url + '/segments' + makeQueryString(opts)).then(function (res) { | ||
return res.body.map(function (obj) { | ||
return segmentify(agent, obj); | ||
}); | ||
var options = Object.assign({}, opts); | ||
if (opts.limit === -1) { | ||
options.limit = options.batchSize || DEFAULT_BATCH_SIZE; | ||
delete options.batchSize; | ||
options.offset = 0; | ||
var segments = []; | ||
return promiseWhile(function () { | ||
return segments.length === options.limit; | ||
}, function () { | ||
return findSegments(agent, options).then(function (newSegments) { | ||
segments.push.apply(segments, toConsumableArray(newSegments)); | ||
options.offset += options.limit; | ||
}); | ||
}).then(function () { | ||
return segments; | ||
}); | ||
} | ||
return get(agent.url + '/segments' + makeQueryString(opts)).then(function (res) { | ||
return res.body.map(function (obj) { | ||
return segmentify(agent, obj); | ||
}); | ||
}); | ||
} | ||
@@ -105,0 +284,0 @@ |
{ | ||
"name": "stratumn-agent-client", | ||
"version": "1.6.0", | ||
"version": "1.7.1", | ||
"description": "Stratumn Indigo agent client library", | ||
@@ -5,0 +5,0 @@ "main": "lib/stratumn-agent-client.js", |
@@ -5,3 +5,3 @@ # Stratumn SDK for Javascript [ALPHA - incompatible with production] | ||
[![codecov](https://codecov.io/gh/stratumn/agent-client-js/branch/alpha/graph/badge.svg)](https://codecov.io/gh/stratumn/agent-client-js/branch/alpha) | ||
[![Build Status](https://david-dm.org/stratumn/agent-client-js.svg?branch=alpha)](https://david-dm.org/stratumn/agent-client-js) | ||
[![Build Status](https://david-dm.org/stratumn/agent-client-js.svg?branch=alpha)](https://david-dm.org/stratumn/agent-client-js) | ||
@@ -135,3 +135,4 @@ ## Installation | ||
- `offset`: offset of first returned segments | ||
- `limit`: limit number of returned segments | ||
- `limit`: limit number of returned segments, if -1 load all segments | ||
- `batchSize`: size of each batch when loading all segments (default 20) | ||
- `mapId`: return segments with specified map ID | ||
@@ -138,0 +139,0 @@ - `prevLinkHash`: return segments with specified previous link hash |
@@ -11,7 +11,27 @@ /* | ||
import makeQueryString from './makeQueryString'; | ||
import promiseWhile from './promiseWhile'; | ||
import { get } from './request'; | ||
const DEFAULT_BATCH_SIZE = 20; | ||
export default function findSegments(agent, opts = {}) { | ||
const options = Object.assign({}, opts); | ||
if (opts.limit === -1) { | ||
options.limit = options.batchSize || DEFAULT_BATCH_SIZE; | ||
delete options.batchSize; | ||
options.offset = 0; | ||
const segments = []; | ||
return promiseWhile( | ||
() => segments.length === options.limit, | ||
() => findSegments(agent, options) | ||
.then(newSegments => { | ||
segments.push(...newSegments); | ||
options.offset += options.limit; | ||
}) | ||
).then(() => segments); | ||
} | ||
return get(`${agent.url}/segments${makeQueryString(opts)}`) | ||
.then(res => res.body.map(obj => segmentify(agent, obj))); | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
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
Uses eval
Supply chain riskPackage uses dynamic code execution (e.g., eval()), which is a dangerous practice. This can prevent the code from running in certain environments and increases the risk that the code may contain exploits or malicious behavior.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
Unidentified License
License(Experimental) Something that seems like a license was found, but its contents could not be matched with a known license.
Found 1 instance 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
Unidentified License
License(Experimental) Something that seems like a license was found, but its contents could not be matched with a known license.
Found 1 instance in 1 package
298497
46
2494
269
2
2
9