-
Notifications
You must be signed in to change notification settings - Fork 67
/
prompt.ts
167 lines (150 loc) · 4.72 KB
/
prompt.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import * as Errors from '../errors'
import * as chalk from 'chalk'
import config from './config'
import deps from './deps'
export interface IPromptOptions {
prompt?: string;
type?: 'normal' | 'mask' | 'hide' | 'single';
timeout?: number;
/**
* Requires user input if true, otherwise allows empty input
*/
required?: boolean;
default?: string;
}
interface IPromptConfig {
name: string;
prompt: string;
type: 'normal' | 'mask' | 'hide' | 'single';
isTTY: boolean;
required: boolean;
default?: string;
timeout?: number;
}
function normal(options: IPromptConfig, retries = 100): Promise<string> {
if (retries < 0) throw new Error('no input')
return new Promise((resolve, reject) => {
let timer: NodeJS.Timer
if (options.timeout) {
timer = setTimeout(() => {
process.stdin.pause()
reject(new Error('Prompt timeout'))
}, options.timeout)
timer.unref()
}
process.stdin.setEncoding('utf8')
process.stderr.write(options.prompt)
process.stdin.resume()
process.stdin.once('data', b => {
if (timer) clearTimeout(timer)
process.stdin.pause()
const data: string = (typeof b === 'string' ? b : b.toString()).trim()
if (!options.default && options.required && data === '') {
resolve(normal(options, retries - 1))
} else {
resolve(data || options.default as string)
}
})
})
}
function getPrompt(name: string, type?: string, defaultValue?: string) {
let prompt = '> '
if (defaultValue && type === 'hide') {
defaultValue = '*'.repeat(defaultValue.length)
}
if (name && defaultValue) prompt = name + ' ' + chalk.yellow('[' + defaultValue + ']') + ': '
else if (name) prompt = `${name}: `
return prompt
}
async function single(options: IPromptConfig): Promise<string> {
const raw = process.stdin.isRaw
if (process.stdin.setRawMode) process.stdin.setRawMode(true)
options.required = options.required ?? false
const response = await normal(options)
if (process.stdin.setRawMode) process.stdin.setRawMode(Boolean(raw))
return response
}
function replacePrompt(prompt: string) {
process.stderr.write(deps.ansiEscapes.cursorHide + deps.ansiEscapes.cursorUp(1) + deps.ansiEscapes.cursorLeft + prompt +
deps.ansiEscapes.cursorDown(1) + deps.ansiEscapes.cursorLeft + deps.ansiEscapes.cursorShow)
}
function _prompt(name: string, inputOptions: Partial<IPromptOptions> = {}): Promise<string> {
const prompt = getPrompt(name, inputOptions.type, inputOptions.default)
const options: IPromptConfig = {
isTTY: Boolean(process.env.TERM !== 'dumb' && process.stdin.isTTY),
name,
prompt,
type: 'normal',
required: true,
default: '',
...inputOptions,
}
switch (options.type) {
case 'normal':
return normal(options)
case 'single':
return single(options)
case 'mask':
return deps.passwordPrompt(options.prompt, {
method: options.type,
required: options.required,
default: options.default,
}).then((value: string) => {
replacePrompt(getPrompt(name, 'hide', inputOptions.default))
return value
})
case 'hide':
return deps.passwordPrompt(options.prompt, {
method: options.type,
required: options.required,
default: options.default,
})
default:
throw new Error(`unexpected type ${options.type}`)
}
}
/**
* prompt for input
* @param name - prompt text
* @param options - @see IPromptOptions
* @returns void
*/
export function prompt(name: string, options: IPromptOptions = {}): Promise<string> {
return config.action.pauseAsync(() => {
return _prompt(name, options)
}, chalk.cyan('?'))
}
/**
* confirmation prompt (yes/no)
* @param message - confirmation text
* @returns Promise<boolean>
*/
export function confirm(message: string): Promise<boolean> {
return config.action.pauseAsync(async () => {
const confirm = async (): Promise<boolean> => {
const response = (await _prompt(message)).toLowerCase()
if (['n', 'no'].includes(response)) return false
if (['y', 'yes'].includes(response)) return true
return confirm()
}
return confirm()
}, chalk.cyan('?'))
}
/**
* "press anykey to continue"
* @param message - optional message to display to user
* @returns Promise<string>
*/
export async function anykey(message?: string): Promise<string> {
const tty = Boolean(process.stdin.setRawMode)
if (!message) {
message = tty ?
`Press any key to continue or ${chalk.yellow('q')} to exit` :
`Press enter to continue or ${chalk.yellow('q')} to exit`
}
const char = await prompt(message, {type: 'single', required: false})
if (tty) process.stderr.write('\n')
if (char === 'q') Errors.error('quit')
if (char === '\u0003') Errors.error('ctrl-c')
return char
}