| 1 | var readline = require('readline')
|
|---|
| 2 | var Promise = require('any-promise')
|
|---|
| 3 | var objectAssign = require('object-assign')
|
|---|
| 4 | var Interface = readline.Interface
|
|---|
| 5 |
|
|---|
| 6 | function wrapCompleter (completer) {
|
|---|
| 7 | if (completer.length === 2) return completer
|
|---|
| 8 |
|
|---|
| 9 | return function (line, cb) {
|
|---|
| 10 | var result = completer(line)
|
|---|
| 11 |
|
|---|
| 12 | if (typeof result.then !== 'function') {
|
|---|
| 13 | return cb(null, result)
|
|---|
| 14 | }
|
|---|
| 15 |
|
|---|
| 16 | result.catch(cb).then(function (result) {
|
|---|
| 17 | process.nextTick(function () { cb(null, result) })
|
|---|
| 18 | })
|
|---|
| 19 | }
|
|---|
| 20 | }
|
|---|
| 21 |
|
|---|
| 22 | function InterfaceAsPromised (input, output, completer, terminal) {
|
|---|
| 23 | if (arguments.length === 1) {
|
|---|
| 24 | var options = input
|
|---|
| 25 |
|
|---|
| 26 | if (typeof options.completer === 'function') {
|
|---|
| 27 | options = objectAssign({}, options, {
|
|---|
| 28 | completer: wrapCompleter(options.completer)
|
|---|
| 29 | })
|
|---|
| 30 | }
|
|---|
| 31 |
|
|---|
| 32 | Interface.call(this, options)
|
|---|
| 33 | } else {
|
|---|
| 34 | if (typeof completer === 'function') {
|
|---|
| 35 | completer = wrapCompleter(completer)
|
|---|
| 36 | }
|
|---|
| 37 |
|
|---|
| 38 | Interface.call(this, input, output, completer, terminal)
|
|---|
| 39 | }
|
|---|
| 40 | }
|
|---|
| 41 |
|
|---|
| 42 | InterfaceAsPromised.prototype = Object.create(Interface.prototype)
|
|---|
| 43 |
|
|---|
| 44 | InterfaceAsPromised.prototype.question = function (question, callback) {
|
|---|
| 45 | if (typeof callback === 'function') {
|
|---|
| 46 | return Interface.prototype.question.call(this, question, callback)
|
|---|
| 47 | }
|
|---|
| 48 |
|
|---|
| 49 | var self = this
|
|---|
| 50 | return new Promise(function (resolve) {
|
|---|
| 51 | Interface.prototype.question.call(self, question, resolve)
|
|---|
| 52 | })
|
|---|
| 53 | }
|
|---|
| 54 |
|
|---|
| 55 | objectAssign(exports, readline, {
|
|---|
| 56 | Interface: InterfaceAsPromised,
|
|---|
| 57 | createInterface: function (input, output, completer, terminal) {
|
|---|
| 58 | if (arguments.length === 1) {
|
|---|
| 59 | return new InterfaceAsPromised(input)
|
|---|
| 60 | }
|
|---|
| 61 |
|
|---|
| 62 | return new InterfaceAsPromised(input, output, completer, terminal)
|
|---|
| 63 | }
|
|---|
| 64 | })
|
|---|