UNPKG

cordite-cli

Version:

a command line tool for accessing a Corda node running cordite cordapps or braid

99 lines (88 loc) 3.27 kB
/* * Copyright 2018, Cordite Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * The following routine `depromisfy` intercepts calls on a repl * unwrapping member invocations, a providing automatic handlers for * asynchronous functions that return promises * * The design is strictly based on the excellent `esprima` * parsing library, and its abstract syntax tree object model. * * @author fuzz */ const rewrite=require('./deepromise'); class DeepromiseRepl { constructor(replServer) { const that = {} that.replServer = replServer; that.oldEval = that.replServer.eval; that.replServer.eval = function (cmd, context, filename, callback) { try { // to support later versions of node if (cmd.startsWith('try {') && cmd.endsWith('catch {}')) { return that.oldEval(cmd, context, filename, callback); } const script = rewrite(cmd); that.oldEval(script, context, filename, (err, res) => { // Error response if (err) { return callback(err); } // Non-thenable response if (!res || typeof res.then != 'function') { return callback(null, res); } // Start listening for escape characters, to quit waiting on the promise var cancel = function (chunk, key) { replServer.outputStream.write('break.\n'); if (key.name === 'escape') { process.stdin.removeListener('keypress', cancel); callback(null, res); // Ensure we don't call the callback again callback = function () { }; } }; process.stdin.on('keypress', cancel); // Start a timer indicating that escape can be used to quit var hangTimer = setTimeout(function () { replServer.outputStream.write('Hit escape to stop waiting on promise\n'); }, 5000); res.then(function (val) { process.stdin.removeListener('keypress', cancel); clearTimeout(hangTimer); callback(null, val) }, function (err) { process.stdin.removeListener('keypress', cancel); clearTimeout(hangTimer); replServer.outputStream.write('Promise rejected: '); callback(err); }).then(null, function (uncaught) { // Rethrow uncaught exceptions process.nextTick(function () { throw uncaught; }); }); }); } catch (err) { callback(err); } } } } function deepromisify(replServer) { new DeepromiseRepl(replServer); } module.exports = deepromisify