UNPKG

jaysonic

Version:

A feature rich JSON-RPC 1.0/2.0 compliant client and server library

516 lines (431 loc) 19.9 kB
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var EventEmitter = require("events"); var _require = require("../util/format"), formatResponse = _require.formatResponse; var JsonRpcServerProtocol = require("./protocol/base"); /** * Creates an instance of JsonRpcServerFactory * @extends events */ var JsonRpcServerFactory = /*#__PURE__*/function (_EventEmitter) { _inherits(JsonRpcServerFactory, _EventEmitter); var _super = _createSuper(JsonRpcServerFactory); /** * @param {object} options * @param {Object} [options.host] Host IP to open server with * @param {Object} [options.port] Host port to open server with * @param {Number} [options.version=2] JSON-RPC version to use (1|2) * @param {String} [options.delimiter="\n"] Delimiter to use for [JsonRpcServerProtocol]{@link JsonRpcServerProtocol} * @param {Boolean} [options.exlusive=false] disallow port sharing * @property {object} methods Key value pairs of server method to function call * @property {array} clients List of client connections which are instances of [JsonRpcServerProtocol]{@link JsonRpcServerProtocol} * @property {boolean} listening Inidicates if the server is currently listening * @property {Object} protocol Instance of [JsonRpcServerProtocol]{@link JsonRpcServerProtocol} to use for client connections */ function JsonRpcServerFactory(options) { var _this; _classCallCheck(this, JsonRpcServerFactory); _this = _super.call(this); if (!(_assertThisInitialized(_this) instanceof JsonRpcServerFactory)) { return _possibleConstructorReturn(_this, new JsonRpcServerFactory(options)); } var defaults = { host: "127.0.0.1", port: 8100, exclusive: false, version: 2, delimiter: "\n" }; _this.options = _objectSpread(_objectSpread({}, defaults), options || {}); _this.methods = {}; _this.clients = []; _this.listening = false; _this.protocol = JsonRpcServerProtocol; return _this; } /** * Start listening for client connections to server. * * Calls [setServer]{@link JsonRpcServerFactory#setServer} and [buildProtocol]{@link JsonRpcServerFactory#buildProtocol}. * * Establishes `error` and `close` listeners. * * @returns {Promise} Resolves host and port address for server. */ _createClass(JsonRpcServerFactory, [{ key: "listen", value: function listen() { var _this2 = this; return new Promise(function (resolve, reject) { if (_this2.listening) { // not having this caused MaxEventListeners error return reject(Error("server already listening")); } var _this2$options = _this2.options, host = _this2$options.host, port = _this2$options.port, exclusive = _this2$options.exclusive; _this2.setServer(); _this2.server.listen({ host: host, port: port, exclusive: exclusive }); _this2._setupListeners(reject); _this2.server.on("listening", function () { _this2.listening = true; _this2.buildProtocol(); resolve({ host: _this2.server.address().address, port: _this2.server.address().port }); }); }); } /** * Establishes the client connection using the protocol instance * and adds the newly connected client to `this.clients`. * * Registers the event to call `clientDisconnected` when a client a closes the connection * * @abstract * @example * const pcol = JsonRpcServerProtocol() * pcol.clientConnected() * this.clients.push(pcol) */ }, { key: "buildProtocol", value: function buildProtocol() { throw new Error("function must be overwritten in subclass"); } /** * Set the `server` property for the server factory * @abstract * @example * this.server = new net.Server() */ }, { key: "setServer", value: function setServer() { throw new Error("function must be overwritten in subclass"); } /** * Setup the `error` and `close` events for the factory and server. * * Calls [JsonRpcServerFactory]{@link JsonRpcServerFactory#_removeClients} when server closes * and sets `listening` to false * * @param {function} cb Callback to invoke if server receives an `error` event * @private */ }, { key: "_setupListeners", value: function _setupListeners(cb) { var _this3 = this; this.server.on("error", cb); this.server.on("close", function () { _this3.listening = false; _this3._removeClients(); }); } /** * Closes the server connection and kicks all connected clients. * * Sets `listening` property to `false`. * * @returns {Promise} Will reject if any error was present */ }, { key: "close", value: function close() { var _this4 = this; this.listening = false; return new Promise(function (resolve, reject) { _this4._removeClients(); _this4.server.close(function (error) { if (error) { reject(error); } resolve(); }); }); } /** * Kicks all connected clients. * * Removes all entries from `this.clients` * * @private */ }, { key: "_removeClients", value: function _removeClients() { var _iterator = _createForOfIteratorHelper(this.clients), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var pcol = _step.value; pcol.client.destroy(); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } this.clients = []; } /** * Register a method and associated function with the server. * * The function will be called when a client makes a request to this method. * * @param {string} name Name of method * @param {function} cb Function to call when client makes request to method */ }, { key: "method", value: function method(name, cb) { this.methods[name] = cb; } /** * Call function when notification with event name comes in. * * @param {string} method Method name to listen for notification * @param {function} cb Name of callback function fired when method event comes in * * @example * function world(){ * return 'foo' * } * server.onNotify("hello", world) */ }, { key: "onNotify", value: function onNotify(method, cb) { this.on(method, cb); } /** * Remove function name from listening for notifications. * * @param {string} method Method name to remove * @param {function} cb Name of the callback function to remove * * @example * function world(){ * return 'foo' * } * server.removeOnNotify("hello", world) */ }, { key: "removeOnNotify", value: function removeOnNotify(method, cb) { this.removeListener(method, cb); } /** * Remove all functions listening for notification. * * @param {string} method Method name to remove events for */ }, { key: "removeAllOnNotify", value: function removeAllOnNotify(method) { this.removeAllListeners(method); } /** * @param {Array.<Array.<string, Array|object>>} notifications Array of notifications * @returns {boolean[]|Error[]} Returns list of error objects if there was an error sending to any client. * Returns true if the entire data was sent successfully * Returns false if all or part of the data was not sent to the client. * * @example * server.notify([ * ["hello", ["world"]], * ["foo", {"bar": "baz"}] * ]) */ }, { key: "notify", value: function notify(notifications) { var _this5 = this; if (notifications.length === 0 || !Array.isArray(notifications)) { throw new Error("Invalid arguments"); } var responses = this._getNotificationResponses(notifications); var response; if (responses.length === 1) { response = formatResponse(responses[0]); } else { // batch notification responses response = "["; responses.forEach(function (res, idx) { response += formatResponse(res); response += idx === responses.length - 1 ? "" : ","; }); response += "]"; response = JSON.stringify(JSON.parse(response)) + this.options.delimiter; } if (this.clients.length === 0) { return [Error("No clients connected")]; } return this.clients.map(function (pcol) { try { return _this5.sendNotification(pcol.client, response); } catch (e) { // possibly client disconnected return e; } }); } /** * Send notification to client * * @param {class} client Client instance * @param {string} response Stringified JSON-RPC message to sent to client * @throws Will throw an error if client is not defined */ }, { key: "sendNotification", value: function sendNotification(client, response) { return client.write(response); } /** * Generate objects for notifications to send to client * * @param {Array.<string, Array>} notifications Array of notifications to send to client. * @returns {JSON} Returns a valid JSON-RPC response object * @private */ }, { key: "_getNotificationResponses", value: function _getNotificationResponses(notifications) { var _this6 = this; return notifications.map(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), method = _ref2[0], params = _ref2[1]; if (!method && !params || !method && params) { throw new Error("Unable to generate a response object"); } var response = { method: method, params: params, delimiter: _this6.options.delimiter }; if (_this6.options.version === 2) { response.jsonrpc = "2.0"; } return response; }); } /** * Called when client receives a `connection` event. * * @param {JsonRpcServerProtocol} pcol A {@link JsonRpcServerProtocol} instance * @returns {JsonRpcServerProtocol.client} Returns a client for a given `JsonRpcServerProtocol` instance */ }, { key: "clientConnected", value: function clientConnected(pcol) { return pcol.client; } /** * Called when client disconnects from server. * * If overwriting, its recommended to call {@link JsonRpcServerFactory._removeFromArray} manually * to ensure `this.clients` is cleaned up * * Calls `this._removeFromArray` and removes disconnected client from `this.clients` list * * @param {JsonRpcServerProtocol} pcol A {@link JsonRpcServerProtocol} instance * @returns {object|error} Returns an object of {host, port} for the given protocol instance, or {error} * if there was an error retrieving the client */ }, { key: "clientDisconnected", value: function clientDisconnected(pcol) { return this._removeFromArray(pcol, this.clients); } /** * Removes item from the given list * * @param {*} item Any item in the list * @param {array} array The array to remove the item from * @returns {*|error} Returns the item that was removed from the array or {error} * */ }, { key: "_removeFromArray", value: function _removeFromArray(item, array) { var itemIndex = array.findIndex(function (c) { return c === item; }); if (itemIndex === -1) { return { error: "Unable to remove ".concat(JSON.stringify(item)) }; } var _array$splice = array.splice(itemIndex, 1), _array$splice2 = _slicedToArray(_array$splice, 1), removedItem = _array$splice2[0]; return removedItem; } /** * Returns a list of all server class methods which start with 'handle'. * * @param {object} toCheck The object get prototype function names from * @private */ }, { key: "_getAllFuncs", value: function _getAllFuncs(toCheck) { return Object.getOwnPropertyNames(Object.getPrototypeOf(toCheck)).filter(function (e, i, arr) { if (e !== arr[i + 1] && typeof toCheck[e] === "function" && e.startsWith("handle")) { return true; } return false; }); } }]); return JsonRpcServerFactory; }(EventEmitter); module.exports = JsonRpcServerFactory; /** * HTTP server constructor * @type HttpServerFactory * @static */ JsonRpcServerFactory.http = require("./http"); /** * TCP server constructor * @type TcpServerFactory * @static */ JsonRpcServerFactory.tcp = require("./tcp"); /** * WS server constructor * @type WsServerFactory * @static */ JsonRpcServerFactory.ws = require("./ws");