jsonrpc-ts-client
Advanced tools
Comparing version 0.1.18 to 0.1.19
@@ -914,74 +914,2 @@ 'use strict'; | ||
var isObject = function isObject(v) { | ||
return v !== null && typeof v === "object"; | ||
}; | ||
var hasProperties = function hasProperties(obj) { | ||
for (var _len = arguments.length, keys = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | ||
keys[_key - 1] = arguments[_key]; | ||
} | ||
return !!obj && keys.every(function (key) { | ||
var hasKey = Object.prototype.hasOwnProperty.call(obj, key); | ||
return hasKey; | ||
}); | ||
}; | ||
var isJsonRpcResponseError = function isJsonRpcResponseError(value) { | ||
return "error" in value && value.error !== null; | ||
}; | ||
var InvalidJsonRpcResponseError = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(InvalidJsonRpcResponseError, _Error); | ||
function InvalidJsonRpcResponseError(message) { | ||
return _Error.call(this, "Your server spec must conform to: https://www.jsonrpc.org/specification. " + message) || this; | ||
} | ||
return InvalidJsonRpcResponseError; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
/** | ||
* Validate the basic structure of the JSON:RPC reply | ||
*/ | ||
function assertJsonRpcReply(v) { | ||
if (!isObject(v)) { | ||
throw new InvalidJsonRpcResponseError("Response is not object, got: " + JSON.stringify(v, undefined, 2)); | ||
} | ||
if (!hasProperties(v, "jsonrpc")) { | ||
throw new InvalidJsonRpcResponseError("Invalid response " + JSON.stringify(v, undefined, 2)); | ||
} | ||
if (hasProperties(v, "result", "error")) { | ||
if (v.result && v.error) { | ||
throw new InvalidJsonRpcResponseError("Result and error member should not exist together (https://www.jsonrpc.org/specification#5)"); | ||
} | ||
} | ||
if (hasProperties(v, "error")) { | ||
if (!isObject(v.error)) { | ||
throw new InvalidJsonRpcResponseError('"error" field should be object'); | ||
} | ||
if (!hasProperties(v.error, "code", "message")) { | ||
throw new InvalidJsonRpcResponseError("invalid \"error\" field shape: " + JSON.stringify(v.error, undefined, 2)); | ||
} | ||
} | ||
} | ||
function assertJsonRpcReplyBatch(v) { | ||
if (!Array.isArray(v)) { | ||
throw new InvalidJsonRpcResponseError("Batch response should be an array"); | ||
} | ||
v.forEach(assertJsonRpcReply); | ||
} | ||
var JsonRpcCall = function JsonRpcCall(method, params, id) { | ||
this.method = void 0; | ||
this.params = void 0; | ||
this.id = void 0; | ||
this.jsonrpc = "2.0"; | ||
this.method = method; | ||
this.params = params; | ||
this.id = id; | ||
}; | ||
var EitherApi = /*#__PURE__*/function () { | ||
@@ -1091,2 +1019,77 @@ function EitherApi() {} | ||
var isObject = function isObject(v) { | ||
return v !== null && typeof v === "object"; | ||
}; | ||
var hasProperties = function hasProperties(obj) { | ||
for (var _len = arguments.length, keys = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | ||
keys[_key - 1] = arguments[_key]; | ||
} | ||
return !!obj && keys.every(function (key) { | ||
var hasKey = Object.prototype.hasOwnProperty.call(obj, key); | ||
return hasKey; | ||
}); | ||
}; | ||
var isJsonRpcResponseError = function isJsonRpcResponseError(value) { | ||
return "error" in value && value.error !== null; | ||
}; | ||
var InvalidJsonRpcResponseError = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(InvalidJsonRpcResponseError, _Error); | ||
function InvalidJsonRpcResponseError(message) { | ||
return _Error.call(this, "Your server spec must conform to: https://www.jsonrpc.org/specification. " + message) || this; | ||
} | ||
return InvalidJsonRpcResponseError; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
/** | ||
* Validate the basic structure of the JSON:RPC reply | ||
*/ | ||
function assertJsonRpcReply(v) { | ||
if (!isObject(v)) { | ||
throw new InvalidJsonRpcResponseError("Response is not object, got: " + JSON.stringify(v, undefined, 2)); | ||
} | ||
if (!hasProperties(v, "jsonrpc")) { | ||
throw new InvalidJsonRpcResponseError("Invalid response " + JSON.stringify(v, undefined, 2)); | ||
} | ||
if (hasProperties(v, "result", "error")) { | ||
if (v.result && v.error) { | ||
throw new InvalidJsonRpcResponseError("Result and error member should not exist together (https://www.jsonrpc.org/specification#5)"); | ||
} | ||
} | ||
if (hasProperties(v, "error")) { | ||
if (!isObject(v.error)) { | ||
throw new InvalidJsonRpcResponseError('"error" field should be object'); | ||
} | ||
if (!hasProperties(v.error, "code", "message")) { | ||
throw new InvalidJsonRpcResponseError("invalid \"error\" field shape: " + JSON.stringify(v.error, undefined, 2)); | ||
} | ||
} | ||
} | ||
function assertJsonRpcReplyBatch(v) { | ||
if (!Array.isArray(v)) { | ||
throw new InvalidJsonRpcResponseError("Batch response should be an array"); | ||
} | ||
v.forEach(assertJsonRpcReply); | ||
} | ||
var JsonRpcCall = function JsonRpcCall(method, params, id) { | ||
this.method = void 0; | ||
this.params = void 0; | ||
this.id = void 0; | ||
this.jsonrpc = "2.0"; | ||
this.method = method; | ||
this.params = params; | ||
this.id = id; | ||
}; | ||
var jsonRpcResponseToEither = function jsonRpcResponseToEither(response) { | ||
return isJsonRpcResponseError(response) ? new ErrorResponse(response.error) : new SuccessResponse(response.result); | ||
}; | ||
/* run via npm test DEBUG=jsonrpc-ts-client etc */ | ||
@@ -1140,9 +1143,4 @@ | ||
var _jsonRpcResponseToEither = /*#__PURE__*/_classPrivateFieldLooseKey("jsonRpcResponseToEither"); | ||
var JsonRpcClient = /*#__PURE__*/function () { | ||
function JsonRpcClient(opts) { | ||
Object.defineProperty(this, _jsonRpcResponseToEither, { | ||
value: _jsonRpcResponseToEither2 | ||
}); | ||
Object.defineProperty(this, _buildAxiosClient, { | ||
@@ -1167,3 +1165,6 @@ value: _buildAxiosClient2 | ||
/** | ||
* Execute a JSON-RPC Method call. | ||
/** | ||
* Execute a single JSON-RPC request. | ||
* @link https://www.jsonrpc.org/specification#request_object | ||
* | ||
* @param method - JSON-RPC Method (e.g 'getUser') | ||
@@ -1202,5 +1203,4 @@ * @param params - Data that will be sent in the request body to the JSON-RPC endpoint | ||
assertJsonRpcReply(axiosData); | ||
debug(axiosResponse); // typing this is _hard_ with conditional types, and not especially useful here. | ||
response = _classPrivateFieldLooseBase(this, _jsonRpcResponseToEither)[_jsonRpcResponseToEither](axiosData); | ||
debug(axiosResponse); | ||
response = jsonRpcResponseToEither(axiosData); | ||
return _context.abrupt("return", response); | ||
@@ -1253,3 +1253,3 @@ | ||
debug(axiosResponse); | ||
response = axiosData.map(_classPrivateFieldLooseBase(this, _jsonRpcResponseToEither)[_jsonRpcResponseToEither]); | ||
response = axiosData.map(jsonRpcResponseToEither); | ||
return _context2.abrupt("return", response); | ||
@@ -1292,6 +1292,2 @@ | ||
function _jsonRpcResponseToEither2(axiosData) { | ||
return isJsonRpcResponseError(axiosData) ? new ErrorResponse(axiosData.error) : new SuccessResponse(axiosData.result); | ||
} | ||
exports.ApiClientConfig = ApiClientConfig; | ||
@@ -1298,0 +1294,0 @@ exports.InvalidJsonRpcResponseError = InvalidJsonRpcResponseError; |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("axios"),r=require("debug");function e(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var n=e(t),o=e(r);function i(t,r,e,n,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void e(t)}c.done?r(u):Promise.resolve(u).then(n,o)}function a(t){return function(){var r=this,e=arguments;return new Promise((function(n,o){var a=t.apply(r,e);function c(t){i(a,n,o,c,u,"next",t)}function u(t){i(a,n,o,c,u,"throw",t)}c(void 0)}))}}function c(t,r){t.prototype=Object.create(r.prototype),t.prototype.constructor=t,s(t,r)}function u(t){return u=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},u(t)}function s(t,r){return s=Object.setPrototypeOf||function(t,r){return t.__proto__=r,t},s(t,r)}function f(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function h(t,r,e){return h=f()?Reflect.construct:function(t,r,e){var n=[null];n.push.apply(n,r);var o=new(Function.bind.apply(t,n));return e&&s(o,e.prototype),o},h.apply(null,arguments)}function l(t){var r="function"==typeof Map?new Map:void 0;return l=function(t){if(null===t||-1===Function.toString.call(t).indexOf("[native code]"))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==r){if(r.has(t))return r.get(t);r.set(t,e)}function e(){return h(t,arguments,u(this).constructor)}return e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),s(e,t)},l(t)}var p=0;function d(t){return"__private_"+p+++"_"+t}function v(t,r){if(!Object.prototype.hasOwnProperty.call(t,r))throw new TypeError("attempted to use private field on non-instance");return t}var y={exports:{}};!function(t){var r=function(t){var r,e=Object.prototype,n=e.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},i=o.iterator||"@@iterator",a=o.asyncIterator||"@@asyncIterator",c=o.toStringTag||"@@toStringTag";function u(t,r,e){return Object.defineProperty(t,r,{value:e,enumerable:!0,configurable:!0,writable:!0}),t[r]}try{u({},"")}catch(t){u=function(t,r,e){return t[r]=e}}function s(t,r,e,n){var o=Object.create((r&&r.prototype instanceof y?r:y).prototype),i=new F(n||[]);return o._invoke=function(t,r,e){var n=h;return function(o,i){if(n===p)throw new Error("Generator is already running");if(n===d){if("throw"===o)throw i;return R()}for(e.method=o,e.arg=i;;){var a=e.delegate;if(a){var c=L(a,e);if(c){if(c===v)continue;return c}}if("next"===e.method)e.sent=e._sent=e.arg;else if("throw"===e.method){if(n===h)throw n=d,e.arg;e.dispatchException(e.arg)}else"return"===e.method&&e.abrupt("return",e.arg);n=p;var u=f(t,r,e);if("normal"===u.type){if(n=e.done?d:l,u.arg===v)continue;return{value:u.arg,done:e.done}}"throw"===u.type&&(n=d,e.method="throw",e.arg=u.arg)}}}(t,e,i),o}function f(t,r,e){try{return{type:"normal",arg:t.call(r,e)}}catch(t){return{type:"throw",arg:t}}}t.wrap=s;var h="suspendedStart",l="suspendedYield",p="executing",d="completed",v={};function y(){}function w(){}function g(){}var m={};u(m,i,(function(){return this}));var b=Object.getPrototypeOf,x=b&&b(b(G([])));x&&x!==e&&n.call(x,i)&&(m=x);var O=g.prototype=y.prototype=Object.create(m);function j(t){["next","throw","return"].forEach((function(r){u(t,r,(function(t){return this._invoke(r,t)}))}))}function E(t,r){function e(o,i,a,c){var u=f(t[o],t,i);if("throw"!==u.type){var s=u.arg,h=s.value;return h&&"object"==typeof h&&n.call(h,"__await")?r.resolve(h.__await).then((function(t){e("next",t,a,c)}),(function(t){e("throw",t,a,c)})):r.resolve(h).then((function(t){s.value=t,a(s)}),(function(t){return e("throw",t,a,c)}))}c(u.arg)}var o;this._invoke=function(t,n){function i(){return new r((function(r,o){e(t,n,r,o)}))}return o=o?o.then(i,i):i()}}function L(t,e){var n=t.iterator[e.method];if(n===r){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=r,L(t,e),"throw"===e.method))return v;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return v}var o=f(n,t.iterator,e.arg);if("throw"===o.type)return e.method="throw",e.arg=o.arg,e.delegate=null,v;var i=o.arg;return i?i.done?(e[t.resultName]=i.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=r),e.delegate=null,v):i:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,v)}function _(t){var r={tryLoc:t[0]};1 in t&&(r.catchLoc=t[1]),2 in t&&(r.finallyLoc=t[2],r.afterLoc=t[3]),this.tryEntries.push(r)}function P(t){var r=t.completion||{};r.type="normal",delete r.arg,t.completion=r}function F(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(_,this),this.reset(!0)}function G(t){if(t){var e=t[i];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,a=function e(){for(;++o<t.length;)if(n.call(t,o))return e.value=t[o],e.done=!1,e;return e.value=r,e.done=!0,e};return a.next=a}}return{next:R}}function R(){return{value:r,done:!0}}return w.prototype=g,u(O,"constructor",g),u(g,"constructor",w),w.displayName=u(g,c,"GeneratorFunction"),t.isGeneratorFunction=function(t){var r="function"==typeof t&&t.constructor;return!!r&&(r===w||"GeneratorFunction"===(r.displayName||r.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,g):(t.__proto__=g,u(t,c,"GeneratorFunction")),t.prototype=Object.create(O),t},t.awrap=function(t){return{__await:t}},j(E.prototype),u(E.prototype,a,(function(){return this})),t.AsyncIterator=E,t.async=function(r,e,n,o,i){void 0===i&&(i=Promise);var a=new E(s(r,e,n,o),i);return t.isGeneratorFunction(e)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},j(O),u(O,c,"Generator"),u(O,i,(function(){return this})),u(O,"toString",(function(){return"[object Generator]"})),t.keys=function(t){var r=[];for(var e in t)r.push(e);return r.reverse(),function e(){for(;r.length;){var n=r.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},t.values=G,F.prototype={constructor:F,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=r,this.done=!1,this.delegate=null,this.method="next",this.arg=r,this.tryEntries.forEach(P),!t)for(var e in this)"t"===e.charAt(0)&&n.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=r)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function o(n,o){return c.type="throw",c.arg=t,e.next=n,o&&(e.method="next",e.arg=r),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),s=n.call(a,"finallyLoc");if(u&&s){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!s)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,r){for(var e=this.tryEntries.length-1;e>=0;--e){var o=this.tryEntries[e];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=r&&r<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=r,i?(this.method="next",this.next=i.finallyLoc,v):this.complete(a)},complete:function(t,r){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&r&&(this.next=r),v},finish:function(t){for(var r=this.tryEntries.length-1;r>=0;--r){var e=this.tryEntries[r];if(e.finallyLoc===t)return this.complete(e.completion,e.afterLoc),P(e),v}},catch:function(t){for(var r=this.tryEntries.length-1;r>=0;--r){var e=this.tryEntries[r];if(e.tryLoc===t){var n=e.completion;if("throw"===n.type){var o=n.arg;P(e)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:G(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=r),v}},t}(t.exports);try{regeneratorRuntime=r}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}}(y);var w=y.exports,g=function(t){return null!==t&&"object"==typeof t},m=function(t){for(var r=arguments.length,e=new Array(r>1?r-1:0),n=1;n<r;n++)e[n-1]=arguments[n];return!!t&&e.every((function(r){return Object.prototype.hasOwnProperty.call(t,r)}))},b=function(t){function r(r){return t.call(this,"Your server spec must conform to: https://www.jsonrpc.org/specification. "+r)||this}return c(r,t),r}(l(Error));function x(t){if(!g(t))throw new b("Response is not object, got: "+JSON.stringify(t,void 0,2));if(!m(t,"jsonrpc"))throw new b("Invalid response "+JSON.stringify(t,void 0,2));if(m(t,"result","error")&&t.result&&t.error)throw new b("Result and error member should not exist together (https://www.jsonrpc.org/specification#5)");if(m(t,"error")){if(!g(t.error))throw new b('"error" field should be object');if(!m(t.error,"code","message"))throw new b('invalid "error" field shape: '+JSON.stringify(t.error,void 0,2))}}function O(t){if(!Array.isArray(t))throw new b("Batch response should be an array");t.forEach(x)}var j=function(t,r,e){this.method=void 0,this.params=void 0,this.id=void 0,this.jsonrpc="2.0",this.method=t,this.params=r,this.id=e},E=function(){function t(){}var r=t.prototype;return r.map=function(t){switch(this.type){case"error":return new _(this.error);case"success":return new L(t(this.result))}},r.ap=function(t){switch(this.type){case"error":return new _(this.error);case"success":return t.isSuccess()?t.result(this.result):this.ap(t)}},r.isError=function(){return"error"===this.type},r.isSuccess=function(){return!this.isError()},r.onSuccess=function(t){return this.isSuccess()&&t(this.result),this},r.onError=function(t){return this.isError()&&t(this.error),this},r.unsafeCoerce=function(){if(this.isError())throw this.error;return this.result},t}(),L=function(t){function r(r){var e;return(e=t.call(this)||this).result=void 0,e.type="success",e.result=r,e}return c(r,t),r}(E),_=function(t){function r(r){var e;return(e=t.call(this)||this).error=void 0,e.type="error",e.error=r,e}return c(r,t),r}(E),P=o.default("jsonrpc-ts-client"),F=function(){var t=r.prototype;function r(t){this.url=void 0,this.headers=void 0,this.idGeneratorFn=void 0,this.url=t.url,this.headers=t.headers,this.idGeneratorFn=t.idGeneratorFn}return t.validate=function(){if(!this.url)throw new Error("no url set.")},t.merge=function(t){t.url&&(this.url=t.url),t.idGeneratorFn&&(this.idGeneratorFn=t.idGeneratorFn),t.headers&&(t.headers=this.headers),this.validate()},r}(),G=d("client"),R=d("buildAxiosClient"),S=d("jsonRpcResponseToEither"),N=function(){function t(t){Object.defineProperty(this,S,{value:T}),Object.defineProperty(this,R,{value:k}),Object.defineProperty(this,G,{writable:!0,value:void 0}),this.config=void 0,this.config=new F(t),v(this,G)[G]=v(this,R)[R](this.config)}var r=t.prototype;return r.exec=function(){var t=a(w.mark((function t(r,e,n,o){var i,a,c,u,s,f;return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,o&&(this.config.merge(o),v(this,G)[G]=v(this,R)[R](this.config)),c=new j(r,e,n||(null==(i=(a=this.config).idGeneratorFn)?void 0:i.call(a))),t.next=5,v(this,G)[G]({method:"post",data:c});case 5:return x(s=(u=t.sent).data),P(u),f=v(this,S)[S](s),t.abrupt("return",f);case 13:throw t.prev=13,t.t0=t.catch(0),P(t.t0),t.t0;case 17:case"end":return t.stop()}}),t,this,[[0,13]])})));return function(r,e,n,o){return t.apply(this,arguments)}}(),r.execBatch=function(){var t=a(w.mark((function t(r){var e,n,o,i,a=this;return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,e=r.map((function(t){return new j(t.method,t.params,t.id||(null==a.config.idGeneratorFn?void 0:a.config.idGeneratorFn()))})),t.next=4,v(this,G)[G]({method:"post",data:e});case 4:return O(o=(n=t.sent).data),P(n),i=o.map(v(this,S)[S]),t.abrupt("return",i);case 12:throw t.prev=12,t.t0=t.catch(0),P(t.t0),t.t0;case 16:case"end":return t.stop()}}),t,this,[[0,12]])})));return function(r){return t.apply(this,arguments)}}(),t}();function k(t){return n.default.create({baseURL:t.url,headers:t.headers,validateStatus:function(){return!0}})}function T(t){return"error"in(r=t)&&null!==r.error?new _(t.error):new L(t.result);var r}exports.ApiClientConfig=F,exports.InvalidJsonRpcResponseError=b,exports.JsonRpcCall=j,exports.JsonRpcClient=N,exports.default=N; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("axios"),r=require("debug");function e(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var n=e(t),o=e(r);function i(t,r,e,n,o,i,a){try{var u=t[i](a),c=u.value}catch(t){return void e(t)}u.done?r(c):Promise.resolve(c).then(n,o)}function a(t){return function(){var r=this,e=arguments;return new Promise((function(n,o){var a=t.apply(r,e);function u(t){i(a,n,o,u,c,"next",t)}function c(t){i(a,n,o,u,c,"throw",t)}u(void 0)}))}}function u(t,r){t.prototype=Object.create(r.prototype),t.prototype.constructor=t,s(t,r)}function c(t){return c=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},c(t)}function s(t,r){return s=Object.setPrototypeOf||function(t,r){return t.__proto__=r,t},s(t,r)}function f(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function h(t,r,e){return h=f()?Reflect.construct:function(t,r,e){var n=[null];n.push.apply(n,r);var o=new(Function.bind.apply(t,n));return e&&s(o,e.prototype),o},h.apply(null,arguments)}function l(t){var r="function"==typeof Map?new Map:void 0;return l=function(t){if(null===t||-1===Function.toString.call(t).indexOf("[native code]"))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==r){if(r.has(t))return r.get(t);r.set(t,e)}function e(){return h(t,arguments,c(this).constructor)}return e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),s(e,t)},l(t)}var p=0;function d(t){return"__private_"+p+++"_"+t}function v(t,r){if(!Object.prototype.hasOwnProperty.call(t,r))throw new TypeError("attempted to use private field on non-instance");return t}var y={exports:{}};!function(t){var r=function(t){var r,e=Object.prototype,n=e.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},i=o.iterator||"@@iterator",a=o.asyncIterator||"@@asyncIterator",u=o.toStringTag||"@@toStringTag";function c(t,r,e){return Object.defineProperty(t,r,{value:e,enumerable:!0,configurable:!0,writable:!0}),t[r]}try{c({},"")}catch(t){c=function(t,r,e){return t[r]=e}}function s(t,r,e,n){var o=Object.create((r&&r.prototype instanceof y?r:y).prototype),i=new F(n||[]);return o._invoke=function(t,r,e){var n=h;return function(o,i){if(n===p)throw new Error("Generator is already running");if(n===d){if("throw"===o)throw i;return S()}for(e.method=o,e.arg=i;;){var a=e.delegate;if(a){var u=L(a,e);if(u){if(u===v)continue;return u}}if("next"===e.method)e.sent=e._sent=e.arg;else if("throw"===e.method){if(n===h)throw n=d,e.arg;e.dispatchException(e.arg)}else"return"===e.method&&e.abrupt("return",e.arg);n=p;var c=f(t,r,e);if("normal"===c.type){if(n=e.done?d:l,c.arg===v)continue;return{value:c.arg,done:e.done}}"throw"===c.type&&(n=d,e.method="throw",e.arg=c.arg)}}}(t,e,i),o}function f(t,r,e){try{return{type:"normal",arg:t.call(r,e)}}catch(t){return{type:"throw",arg:t}}}t.wrap=s;var h="suspendedStart",l="suspendedYield",p="executing",d="completed",v={};function y(){}function w(){}function g(){}var m={};c(m,i,(function(){return this}));var b=Object.getPrototypeOf,x=b&&b(b(G([])));x&&x!==e&&n.call(x,i)&&(m=x);var O=g.prototype=y.prototype=Object.create(m);function E(t){["next","throw","return"].forEach((function(r){c(t,r,(function(t){return this._invoke(r,t)}))}))}function j(t,r){function e(o,i,a,u){var c=f(t[o],t,i);if("throw"!==c.type){var s=c.arg,h=s.value;return h&&"object"==typeof h&&n.call(h,"__await")?r.resolve(h.__await).then((function(t){e("next",t,a,u)}),(function(t){e("throw",t,a,u)})):r.resolve(h).then((function(t){s.value=t,a(s)}),(function(t){return e("throw",t,a,u)}))}u(c.arg)}var o;this._invoke=function(t,n){function i(){return new r((function(r,o){e(t,n,r,o)}))}return o=o?o.then(i,i):i()}}function L(t,e){var n=t.iterator[e.method];if(n===r){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=r,L(t,e),"throw"===e.method))return v;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return v}var o=f(n,t.iterator,e.arg);if("throw"===o.type)return e.method="throw",e.arg=o.arg,e.delegate=null,v;var i=o.arg;return i?i.done?(e[t.resultName]=i.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=r),e.delegate=null,v):i:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,v)}function _(t){var r={tryLoc:t[0]};1 in t&&(r.catchLoc=t[1]),2 in t&&(r.finallyLoc=t[2],r.afterLoc=t[3]),this.tryEntries.push(r)}function P(t){var r=t.completion||{};r.type="normal",delete r.arg,t.completion=r}function F(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(_,this),this.reset(!0)}function G(t){if(t){var e=t[i];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var o=-1,a=function e(){for(;++o<t.length;)if(n.call(t,o))return e.value=t[o],e.done=!1,e;return e.value=r,e.done=!0,e};return a.next=a}}return{next:S}}function S(){return{value:r,done:!0}}return w.prototype=g,c(O,"constructor",g),c(g,"constructor",w),w.displayName=c(g,u,"GeneratorFunction"),t.isGeneratorFunction=function(t){var r="function"==typeof t&&t.constructor;return!!r&&(r===w||"GeneratorFunction"===(r.displayName||r.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,g):(t.__proto__=g,c(t,u,"GeneratorFunction")),t.prototype=Object.create(O),t},t.awrap=function(t){return{__await:t}},E(j.prototype),c(j.prototype,a,(function(){return this})),t.AsyncIterator=j,t.async=function(r,e,n,o,i){void 0===i&&(i=Promise);var a=new j(s(r,e,n,o),i);return t.isGeneratorFunction(e)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},E(O),c(O,u,"Generator"),c(O,i,(function(){return this})),c(O,"toString",(function(){return"[object Generator]"})),t.keys=function(t){var r=[];for(var e in t)r.push(e);return r.reverse(),function e(){for(;r.length;){var n=r.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},t.values=G,F.prototype={constructor:F,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=r,this.done=!1,this.delegate=null,this.method="next",this.arg=r,this.tryEntries.forEach(P),!t)for(var e in this)"t"===e.charAt(0)&&n.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=r)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function o(n,o){return u.type="throw",u.arg=t,e.next=n,o&&(e.method="next",e.arg=r),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var c=n.call(a,"catchLoc"),s=n.call(a,"finallyLoc");if(c&&s){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(c){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!s)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,r){for(var e=this.tryEntries.length-1;e>=0;--e){var o=this.tryEntries[e];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=r&&r<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=r,i?(this.method="next",this.next=i.finallyLoc,v):this.complete(a)},complete:function(t,r){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&r&&(this.next=r),v},finish:function(t){for(var r=this.tryEntries.length-1;r>=0;--r){var e=this.tryEntries[r];if(e.finallyLoc===t)return this.complete(e.completion,e.afterLoc),P(e),v}},catch:function(t){for(var r=this.tryEntries.length-1;r>=0;--r){var e=this.tryEntries[r];if(e.tryLoc===t){var n=e.completion;if("throw"===n.type){var o=n.arg;P(e)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:G(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=r),v}},t}(t.exports);try{regeneratorRuntime=r}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=r:Function("r","regeneratorRuntime = r")(r)}}(y);var w=y.exports,g=function(){function t(){}var r=t.prototype;return r.map=function(t){switch(this.type){case"error":return new b(this.error);case"success":return new m(t(this.result))}},r.ap=function(t){switch(this.type){case"error":return new b(this.error);case"success":return t.isSuccess()?t.result(this.result):this.ap(t)}},r.isError=function(){return"error"===this.type},r.isSuccess=function(){return!this.isError()},r.onSuccess=function(t){return this.isSuccess()&&t(this.result),this},r.onError=function(t){return this.isError()&&t(this.error),this},r.unsafeCoerce=function(){if(this.isError())throw this.error;return this.result},t}(),m=function(t){function r(r){var e;return(e=t.call(this)||this).result=void 0,e.type="success",e.result=r,e}return u(r,t),r}(g),b=function(t){function r(r){var e;return(e=t.call(this)||this).error=void 0,e.type="error",e.error=r,e}return u(r,t),r}(g),x=function(t){return null!==t&&"object"==typeof t},O=function(t){for(var r=arguments.length,e=new Array(r>1?r-1:0),n=1;n<r;n++)e[n-1]=arguments[n];return!!t&&e.every((function(r){return Object.prototype.hasOwnProperty.call(t,r)}))},E=function(t){function r(r){return t.call(this,"Your server spec must conform to: https://www.jsonrpc.org/specification. "+r)||this}return u(r,t),r}(l(Error));function j(t){if(!x(t))throw new E("Response is not object, got: "+JSON.stringify(t,void 0,2));if(!O(t,"jsonrpc"))throw new E("Invalid response "+JSON.stringify(t,void 0,2));if(O(t,"result","error")&&t.result&&t.error)throw new E("Result and error member should not exist together (https://www.jsonrpc.org/specification#5)");if(O(t,"error")){if(!x(t.error))throw new E('"error" field should be object');if(!O(t.error,"code","message"))throw new E('invalid "error" field shape: '+JSON.stringify(t.error,void 0,2))}}function L(t){if(!Array.isArray(t))throw new E("Batch response should be an array");t.forEach(j)}var _=function(t,r,e){this.method=void 0,this.params=void 0,this.id=void 0,this.jsonrpc="2.0",this.method=t,this.params=r,this.id=e},P=function(t){return"error"in(r=t)&&null!==r.error?new b(t.error):new m(t.result);var r},F=o.default("jsonrpc-ts-client"),G=function(){var t=r.prototype;function r(t){this.url=void 0,this.headers=void 0,this.idGeneratorFn=void 0,this.url=t.url,this.headers=t.headers,this.idGeneratorFn=t.idGeneratorFn}return t.validate=function(){if(!this.url)throw new Error("no url set.")},t.merge=function(t){t.url&&(this.url=t.url),t.idGeneratorFn&&(this.idGeneratorFn=t.idGeneratorFn),t.headers&&(t.headers=this.headers),this.validate()},r}(),S=d("client"),R=d("buildAxiosClient"),N=function(){function t(t){Object.defineProperty(this,R,{value:k}),Object.defineProperty(this,S,{writable:!0,value:void 0}),this.config=void 0,this.config=new G(t),v(this,S)[S]=v(this,R)[R](this.config)}var r=t.prototype;return r.exec=function(){var t=a(w.mark((function t(r,e,n,o){var i,a,u,c,s,f;return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,o&&(this.config.merge(o),v(this,S)[S]=v(this,R)[R](this.config)),u=new _(r,e,n||(null==(i=(a=this.config).idGeneratorFn)?void 0:i.call(a))),t.next=5,v(this,S)[S]({method:"post",data:u});case 5:return j(s=(c=t.sent).data),F(c),f=P(s),t.abrupt("return",f);case 13:throw t.prev=13,t.t0=t.catch(0),F(t.t0),t.t0;case 17:case"end":return t.stop()}}),t,this,[[0,13]])})));return function(r,e,n,o){return t.apply(this,arguments)}}(),r.execBatch=function(){var t=a(w.mark((function t(r){var e,n,o,i,a=this;return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,e=r.map((function(t){return new _(t.method,t.params,t.id||(null==a.config.idGeneratorFn?void 0:a.config.idGeneratorFn()))})),t.next=4,v(this,S)[S]({method:"post",data:e});case 4:return L(o=(n=t.sent).data),F(n),i=o.map(P),t.abrupt("return",i);case 12:throw t.prev=12,t.t0=t.catch(0),F(t.t0),t.t0;case 16:case"end":return t.stop()}}),t,this,[[0,12]])})));return function(r){return t.apply(this,arguments)}}(),t}();function k(t){return n.default.create({baseURL:t.url,headers:t.headers,validateStatus:function(){return!0}})}exports.ApiClientConfig=G,exports.InvalidJsonRpcResponseError=E,exports.JsonRpcCall=_,exports.JsonRpcClient=N,exports.default=N; | ||
//# sourceMappingURL=jsonrpc-ts-client.cjs.production.min.js.map |
@@ -905,74 +905,2 @@ import axios from 'axios'; | ||
var isObject = function isObject(v) { | ||
return v !== null && typeof v === "object"; | ||
}; | ||
var hasProperties = function hasProperties(obj) { | ||
for (var _len = arguments.length, keys = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | ||
keys[_key - 1] = arguments[_key]; | ||
} | ||
return !!obj && keys.every(function (key) { | ||
var hasKey = Object.prototype.hasOwnProperty.call(obj, key); | ||
return hasKey; | ||
}); | ||
}; | ||
var isJsonRpcResponseError = function isJsonRpcResponseError(value) { | ||
return "error" in value && value.error !== null; | ||
}; | ||
var InvalidJsonRpcResponseError = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(InvalidJsonRpcResponseError, _Error); | ||
function InvalidJsonRpcResponseError(message) { | ||
return _Error.call(this, "Your server spec must conform to: https://www.jsonrpc.org/specification. " + message) || this; | ||
} | ||
return InvalidJsonRpcResponseError; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
/** | ||
* Validate the basic structure of the JSON:RPC reply | ||
*/ | ||
function assertJsonRpcReply(v) { | ||
if (!isObject(v)) { | ||
throw new InvalidJsonRpcResponseError("Response is not object, got: " + JSON.stringify(v, undefined, 2)); | ||
} | ||
if (!hasProperties(v, "jsonrpc")) { | ||
throw new InvalidJsonRpcResponseError("Invalid response " + JSON.stringify(v, undefined, 2)); | ||
} | ||
if (hasProperties(v, "result", "error")) { | ||
if (v.result && v.error) { | ||
throw new InvalidJsonRpcResponseError("Result and error member should not exist together (https://www.jsonrpc.org/specification#5)"); | ||
} | ||
} | ||
if (hasProperties(v, "error")) { | ||
if (!isObject(v.error)) { | ||
throw new InvalidJsonRpcResponseError('"error" field should be object'); | ||
} | ||
if (!hasProperties(v.error, "code", "message")) { | ||
throw new InvalidJsonRpcResponseError("invalid \"error\" field shape: " + JSON.stringify(v.error, undefined, 2)); | ||
} | ||
} | ||
} | ||
function assertJsonRpcReplyBatch(v) { | ||
if (!Array.isArray(v)) { | ||
throw new InvalidJsonRpcResponseError("Batch response should be an array"); | ||
} | ||
v.forEach(assertJsonRpcReply); | ||
} | ||
var JsonRpcCall = function JsonRpcCall(method, params, id) { | ||
this.method = void 0; | ||
this.params = void 0; | ||
this.id = void 0; | ||
this.jsonrpc = "2.0"; | ||
this.method = method; | ||
this.params = params; | ||
this.id = id; | ||
}; | ||
var EitherApi = /*#__PURE__*/function () { | ||
@@ -1082,2 +1010,77 @@ function EitherApi() {} | ||
var isObject = function isObject(v) { | ||
return v !== null && typeof v === "object"; | ||
}; | ||
var hasProperties = function hasProperties(obj) { | ||
for (var _len = arguments.length, keys = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | ||
keys[_key - 1] = arguments[_key]; | ||
} | ||
return !!obj && keys.every(function (key) { | ||
var hasKey = Object.prototype.hasOwnProperty.call(obj, key); | ||
return hasKey; | ||
}); | ||
}; | ||
var isJsonRpcResponseError = function isJsonRpcResponseError(value) { | ||
return "error" in value && value.error !== null; | ||
}; | ||
var InvalidJsonRpcResponseError = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(InvalidJsonRpcResponseError, _Error); | ||
function InvalidJsonRpcResponseError(message) { | ||
return _Error.call(this, "Your server spec must conform to: https://www.jsonrpc.org/specification. " + message) || this; | ||
} | ||
return InvalidJsonRpcResponseError; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
/** | ||
* Validate the basic structure of the JSON:RPC reply | ||
*/ | ||
function assertJsonRpcReply(v) { | ||
if (!isObject(v)) { | ||
throw new InvalidJsonRpcResponseError("Response is not object, got: " + JSON.stringify(v, undefined, 2)); | ||
} | ||
if (!hasProperties(v, "jsonrpc")) { | ||
throw new InvalidJsonRpcResponseError("Invalid response " + JSON.stringify(v, undefined, 2)); | ||
} | ||
if (hasProperties(v, "result", "error")) { | ||
if (v.result && v.error) { | ||
throw new InvalidJsonRpcResponseError("Result and error member should not exist together (https://www.jsonrpc.org/specification#5)"); | ||
} | ||
} | ||
if (hasProperties(v, "error")) { | ||
if (!isObject(v.error)) { | ||
throw new InvalidJsonRpcResponseError('"error" field should be object'); | ||
} | ||
if (!hasProperties(v.error, "code", "message")) { | ||
throw new InvalidJsonRpcResponseError("invalid \"error\" field shape: " + JSON.stringify(v.error, undefined, 2)); | ||
} | ||
} | ||
} | ||
function assertJsonRpcReplyBatch(v) { | ||
if (!Array.isArray(v)) { | ||
throw new InvalidJsonRpcResponseError("Batch response should be an array"); | ||
} | ||
v.forEach(assertJsonRpcReply); | ||
} | ||
var JsonRpcCall = function JsonRpcCall(method, params, id) { | ||
this.method = void 0; | ||
this.params = void 0; | ||
this.id = void 0; | ||
this.jsonrpc = "2.0"; | ||
this.method = method; | ||
this.params = params; | ||
this.id = id; | ||
}; | ||
var jsonRpcResponseToEither = function jsonRpcResponseToEither(response) { | ||
return isJsonRpcResponseError(response) ? new ErrorResponse(response.error) : new SuccessResponse(response.result); | ||
}; | ||
/* run via npm test DEBUG=jsonrpc-ts-client etc */ | ||
@@ -1131,9 +1134,4 @@ | ||
var _jsonRpcResponseToEither = /*#__PURE__*/_classPrivateFieldLooseKey("jsonRpcResponseToEither"); | ||
var JsonRpcClient = /*#__PURE__*/function () { | ||
function JsonRpcClient(opts) { | ||
Object.defineProperty(this, _jsonRpcResponseToEither, { | ||
value: _jsonRpcResponseToEither2 | ||
}); | ||
Object.defineProperty(this, _buildAxiosClient, { | ||
@@ -1158,3 +1156,6 @@ value: _buildAxiosClient2 | ||
/** | ||
* Execute a JSON-RPC Method call. | ||
/** | ||
* Execute a single JSON-RPC request. | ||
* @link https://www.jsonrpc.org/specification#request_object | ||
* | ||
* @param method - JSON-RPC Method (e.g 'getUser') | ||
@@ -1193,5 +1194,4 @@ * @param params - Data that will be sent in the request body to the JSON-RPC endpoint | ||
assertJsonRpcReply(axiosData); | ||
debug(axiosResponse); // typing this is _hard_ with conditional types, and not especially useful here. | ||
response = _classPrivateFieldLooseBase(this, _jsonRpcResponseToEither)[_jsonRpcResponseToEither](axiosData); | ||
debug(axiosResponse); | ||
response = jsonRpcResponseToEither(axiosData); | ||
return _context.abrupt("return", response); | ||
@@ -1244,3 +1244,3 @@ | ||
debug(axiosResponse); | ||
response = axiosData.map(_classPrivateFieldLooseBase(this, _jsonRpcResponseToEither)[_jsonRpcResponseToEither]); | ||
response = axiosData.map(jsonRpcResponseToEither); | ||
return _context2.abrupt("return", response); | ||
@@ -1283,7 +1283,3 @@ | ||
function _jsonRpcResponseToEither2(axiosData) { | ||
return isJsonRpcResponseError(axiosData) ? new ErrorResponse(axiosData.error) : new SuccessResponse(axiosData.result); | ||
} | ||
export { ApiClientConfig, InvalidJsonRpcResponseError, JsonRpcCall, JsonRpcClient, JsonRpcClient as default }; | ||
//# sourceMappingURL=jsonrpc-ts-client.esm.js.map |
import { JsonRpcError, JsonRpcParams } from "./utils/jsonrpc"; | ||
import { Either } from "./utils/either"; | ||
import { GetElementByIndex } from "./utils/ts"; | ||
import { GetElementByIndex, MapEither } from "./utils/ts"; | ||
export interface JsonRpcCreateConfig { | ||
@@ -33,3 +33,15 @@ url: string; | ||
declare type EmptyObject = Record<string, never>; | ||
declare type KeyofOrDefault<T> = T extends EmptyObject ? string : keyof T; | ||
declare type GetParamsFromContract<Api extends JsonRpcApi, Method extends keyof Api> = Parameters<Api[Method]>[0]; | ||
declare type GetResponseFromContract<Api extends JsonRpcApi, Method extends keyof Api> = ReturnType<Api[Method]>; | ||
declare type GetAllCalls<Api extends JsonRpcApi> = { | ||
[Method in keyof Api]: Call<Api, Method>; | ||
}[keyof Api]; | ||
declare type Call<Api extends JsonRpcApi, Method extends keyof Api> = { | ||
method: Method; | ||
params?: GetParamsFromContract<Api, Method>; | ||
id?: string; | ||
}; | ||
declare type GetAllResponses<Api extends JsonRpcApi, Calls extends readonly Call<any, any>[]> = { | ||
[Index in keyof Calls]: Either<JsonRpcError, ReturnType<GetElementByIndex<Api, GetElementByIndex<Calls[Index], "method">>>>; | ||
}; | ||
/** | ||
@@ -42,12 +54,15 @@ * Instantiate this class to make requests to a JSON-RPC endpoint (or endpoints). | ||
constructor(opts: JsonRpcCreateConfig); | ||
exec<M extends keyof Api = any>(method: M, params: GetParamsFromContract<Api, M>, id?: string, configOverrides?: Partial<JsonRpcCreateConfig>): Promise<Either<JsonRpcError, GetResponseFromContract<Api, M>>>; | ||
exec<Response>(method: Api extends EmptyObject ? string : never, // maybe add a branded type?? | ||
params?: JsonRpcParams, id?: string, configOverrides?: Partial<JsonRpcCreateConfig>): Promise<Either<JsonRpcError, Response>>; | ||
/** | ||
* Execute a JSON-RPC Method call. | ||
* @param method - JSON-RPC Method (e.g 'getUser') | ||
* @param params - Data that will be sent in the request body to the JSON-RPC endpoint | ||
* @param id - Request ID | ||
* @param configOverrides - Override the base client configurations | ||
* Execute a batch JSON-RPC request. | ||
* @link https://www.jsonrpc.org/specification#batch | ||
* | ||
* @param calls - an array of calls | ||
* @example execBatch([{ method: 'getFoo', params: {fooId: 123}}, { method: 'getBar'}]) | ||
*/ | ||
exec<ApiResponse, M extends KeyofOrDefault<Api> = any>(method: M, params: Api extends EmptyObject ? JsonRpcParams : Parameters<GetElementByIndex<Api, M>>[0], id?: string, configOverrides?: Partial<JsonRpcCreateConfig>): Promise<Either<JsonRpcError, Api extends EmptyObject ? ApiResponse : ReturnType<GetElementByIndex<Api, M>>>>; | ||
execBatch<Result extends [...unknown[]]>(calls: JsonRpcClientCallOptions[]): Promise<{ [Index in keyof Result]: Either<JsonRpcError, GetElementByIndex<Result, Index>>; }>; | ||
execBatch<Calls extends readonly GetAllCalls<Api>[]>(calls: Calls): Promise<GetAllResponses<Api, Calls>>; | ||
execBatch<Result extends unknown[]>(calls: Call<JsonRpcApi, string>[]): Promise<MapEither<Result>>; | ||
} | ||
export {}; |
@@ -0,1 +1,2 @@ | ||
import { Either } from "./either"; | ||
export interface JsonRpcError { | ||
@@ -30,7 +31,8 @@ code: number; | ||
method: string; | ||
params: Params; | ||
params?: Params | undefined; | ||
id?: string | undefined; | ||
jsonrpc: string; | ||
constructor(method: string, params: Params, id?: string | undefined); | ||
constructor(method: string, params?: Params | undefined, id?: string | undefined); | ||
} | ||
export declare const jsonRpcResponseToEither: <T>(response: JsonRpcResponse<T>) => Either<JsonRpcError, T>; | ||
export {}; |
{ | ||
"version": "0.1.18", | ||
"version": "0.1.19", | ||
"license": "MIT", | ||
@@ -4,0 +4,0 @@ "main": "dist/index.js", |
@@ -55,20 +55,4 @@ ### Warning: this is in alpha. | ||
## ID Generation | ||
Generate IDs automatically, and/or override or set them on a per-request basis. | ||
```ts | ||
import JSONRPC from 'jsonrpc-ts-client' | ||
import uuid from 'uuid' | ||
const client = new JSONRPC({ | ||
... | ||
idGeneratorFn: uuid.v4, | ||
}) | ||
// Override generate IDs | ||
const response = await client.exec<UserDto>('my_method', { userId: 123 }, 'MY_OVERRIDING_ID'); // sends payload {jsonrpc: '2.0', id: 'MY_OVERRIDING_ID', params: ...} | ||
``` | ||
## Batch Support | ||
## API Contract Declaration Support (Recommended option) | ||
You can make [batch requests](https://www.jsonrpc.org/specification#batch) per the JSON-RPC specification. | ||
@@ -79,18 +63,3 @@ ```ts | ||
const client = new JSONRPC({ | ||
url: 'https://foo.com/jsonrpc' | ||
}) | ||
const responses = await client.execBatch<[UserDto, ConfigDto]>([ | ||
{ method: "get_user", params: { userId: 123 }, id: "foo" }, | ||
{ method: "get_config" }, | ||
]); | ||
``` | ||
## API Contract Declaration Support (experimental) | ||
```ts | ||
import JSONRPC from 'jsonrpc-ts-client' | ||
type MyApiContract = { | ||
@@ -115,2 +84,43 @@ getUser: (params: UserParamsDto) => UserDto; | ||
``` | ||
/** batch support **/ | ||
const [user, config] = await client.execBatch([ | ||
{ method: "getUser", params: { userId: 123 } }, | ||
{ method: "getConfig" }, | ||
] as const | ||
); | ||
if (user.isSuccess()) { | ||
console.log(user.name) | ||
console.log(user.id) | ||
} | ||
if (config.isSuccesss()) { | ||
console.log(config.foo) | ||
} | ||
``` | ||
## ID Generation | ||
Generate IDs automatically, and/or override or set them on a per-request basis. | ||
```ts | ||
import JSONRPC from 'jsonrpc-ts-client' | ||
import uuid from 'uuid' | ||
// automatically generate IDs on each request | ||
const client = new JSONRPC({ | ||
... | ||
idGeneratorFn: uuid.v4, | ||
}) | ||
// override your generated IDs at any time... | ||
const response = await client.exec( 'my_method', { userId: 123 }, 'MY_OVERRIDING_ID'); | ||
// => {jsonrpc: '2.0', id: 'MY_OVERRIDING_ID', params: { userId: 123 } } | ||
``` | ||
@@ -6,9 +6,8 @@ import axios, { AxiosError, AxiosInstance, AxiosResponse } from "axios"; | ||
assertJsonRpcReplyBatch, | ||
isJsonRpcResponseError, | ||
JsonRpcCall, | ||
JsonRpcError, | ||
JsonRpcParams, | ||
JsonRpcResponse, | ||
jsonRpcResponseToEither, | ||
} from "./utils/jsonrpc"; | ||
import { Either, ErrorResponse, SuccessResponse } from "./utils/either"; | ||
import { Either } from "./utils/either"; | ||
import { GetElementByIndex, MapEither } from "./utils/ts"; | ||
@@ -71,8 +70,37 @@ | ||
type KeyofOrDefault<T> = T extends EmptyObject ? string : keyof T; | ||
type GetParamsFromContract< | ||
Api extends JsonRpcApi, | ||
Method extends keyof Api | ||
> = Parameters<Api[Method]>[0]; | ||
type GetResponseFromContract< | ||
Api extends JsonRpcApi, | ||
Method extends keyof Api | ||
> = ReturnType<Api[Method]>; | ||
type GetAllCalls<Api extends JsonRpcApi> = { | ||
[Method in keyof Api]: Call<Api, Method>; | ||
}[keyof Api]; | ||
type Call<Api extends JsonRpcApi, Method extends keyof Api> = { | ||
method: Method; | ||
params?: GetParamsFromContract<Api, Method>; | ||
id?: string; | ||
}; | ||
type GetAllResponses< | ||
Api extends JsonRpcApi, | ||
Calls extends readonly Call<any, any>[] | ||
> = { | ||
[Index in keyof Calls]: Either< | ||
JsonRpcError, | ||
ReturnType< | ||
GetElementByIndex<Api, GetElementByIndex<Calls[Index], "method">> | ||
> | ||
>; | ||
}; | ||
/** | ||
* Instantiate this class to make requests to a JSON-RPC endpoint (or endpoints). | ||
*/ | ||
export class JsonRpcClient<Api extends JsonRpcApi = EmptyObject> { | ||
@@ -98,12 +126,21 @@ #client: AxiosInstance; | ||
#jsonRpcResponseToEither<T>( | ||
axiosData: JsonRpcResponse<T> | ||
): Either<JsonRpcError, T> { | ||
return isJsonRpcResponseError(axiosData) | ||
? new ErrorResponse(axiosData.error) | ||
: new SuccessResponse(axiosData.result); | ||
} | ||
async exec<M extends keyof Api = any>( | ||
method: M, | ||
params: GetParamsFromContract<Api, M>, | ||
id?: string, | ||
configOverrides?: Partial<JsonRpcCreateConfig> | ||
): Promise<Either<JsonRpcError, GetResponseFromContract<Api, M>>>; | ||
async exec<Response>( | ||
method: Api extends EmptyObject ? string : never, // maybe add a branded type?? | ||
params?: JsonRpcParams, | ||
id?: string, | ||
configOverrides?: Partial<JsonRpcCreateConfig> | ||
): Promise<Either<JsonRpcError, Response>>; | ||
/** | ||
* Execute a JSON-RPC Method call. | ||
/** | ||
* Execute a single JSON-RPC request. | ||
* @link https://www.jsonrpc.org/specification#request_object | ||
* | ||
* @param method - JSON-RPC Method (e.g 'getUser') | ||
@@ -114,17 +151,8 @@ * @param params - Data that will be sent in the request body to the JSON-RPC endpoint | ||
*/ | ||
async exec<ApiResponse, M extends KeyofOrDefault<Api> = any>( | ||
method: M, | ||
params: Api extends EmptyObject | ||
? JsonRpcParams | ||
: Parameters<GetElementByIndex<Api, M>>[0], | ||
async exec( | ||
method: string, | ||
params: JsonRpcParams, | ||
id?: string, | ||
configOverrides?: Partial<JsonRpcCreateConfig> | ||
): Promise< | ||
Either< | ||
JsonRpcError, | ||
Api extends EmptyObject | ||
? ApiResponse | ||
: ReturnType<GetElementByIndex<Api, M>> | ||
> | ||
> { | ||
) { | ||
try { | ||
@@ -149,8 +177,7 @@ if (configOverrides) { | ||
const axiosData = axiosResponse.data; | ||
assertJsonRpcReply<ApiResponse>(axiosData); | ||
assertJsonRpcReply<any>(axiosData); | ||
debug(axiosResponse); | ||
// typing this is _hard_ with conditional types, and not especially useful here. | ||
const response = this.#jsonRpcResponseToEither(axiosData) as any; | ||
const response = jsonRpcResponseToEither(axiosData); | ||
return response; | ||
@@ -163,5 +190,18 @@ } catch (err) { | ||
async execBatch<Result extends [...unknown[]]>( | ||
calls: JsonRpcClientCallOptions[] | ||
) { | ||
/** | ||
* Execute a batch JSON-RPC request. | ||
* @link https://www.jsonrpc.org/specification#batch | ||
* | ||
* @param calls - an array of calls | ||
* @example execBatch([{ method: 'getFoo', params: {fooId: 123}}, { method: 'getBar'}]) | ||
*/ | ||
async execBatch<Calls extends readonly GetAllCalls<Api>[]>( | ||
calls: Calls | ||
): Promise<GetAllResponses<Api, Calls>>; | ||
async execBatch<Result extends unknown[]>( | ||
calls: Call<JsonRpcApi, string>[] | ||
): Promise<MapEither<Result>>; | ||
async execBatch(calls: Call<any, any>[]): Promise<unknown[]> { | ||
try { | ||
@@ -172,3 +212,3 @@ const data = calls.map( | ||
el.method, | ||
el.params, | ||
el.params as JsonRpcParams, | ||
el.id || this.config.idGeneratorFn?.() | ||
@@ -189,5 +229,3 @@ ) | ||
const response = axiosData.map( | ||
this.#jsonRpcResponseToEither | ||
) as MapEither<Result>; | ||
const response = axiosData.map(jsonRpcResponseToEither); | ||
return response; | ||
@@ -194,0 +232,0 @@ } catch (err) { |
@@ -0,1 +1,2 @@ | ||
import { Either, ErrorResponse, SuccessResponse } from "./either"; | ||
import { hasProperties, isObject } from "./exists"; | ||
@@ -93,5 +94,13 @@ | ||
public method: string, | ||
public params: Params, | ||
public params?: Params, | ||
public id?: string | ||
) {} | ||
} | ||
export const jsonRpcResponseToEither = <T>( | ||
response: JsonRpcResponse<T> | ||
): Either<JsonRpcError, T> => { | ||
return isJsonRpcResponseError(response) | ||
? new ErrorResponse(response.error) | ||
: new SuccessResponse(response.result); | ||
}; |
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
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
301049
26
2870
124