diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index db26c39..a3864ca 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -3,7 +3,7 @@ export { default as GroupMultiSelectPrompt } from './prompts/group-multiselect'; export { default as MultiSelectPrompt } from './prompts/multi-select'; export { default as PasswordPrompt } from './prompts/password'; export { default as Prompt, isCancel } from './prompts/prompt'; -export type { State } from './prompts/prompt'; +export type { State, Validator } from './prompts/prompt'; export { default as SelectPrompt } from './prompts/select'; export { default as SelectKeyPrompt } from './prompts/select-key'; export { default as TextPrompt } from './prompts/text'; diff --git a/packages/core/src/prompts/prompt.ts b/packages/core/src/prompts/prompt.ts index 21ee007..b26de3a 100644 --- a/packages/core/src/prompts/prompt.ts +++ b/packages/core/src/prompts/prompt.ts @@ -38,11 +38,15 @@ const aliases = new Map([ ]); const keys = new Set(['up', 'down', 'left', 'right', 'space', 'enter']); +export interface Validator { + (value: Value): string | void | Promise; +} + export interface PromptOptions { render(this: Omit): string | void; placeholder?: string; initialValue?: any; - validate?: ((value: any) => string | void) | undefined; + validate?: Validator; input?: Readable; output?: Writable; debug?: boolean; @@ -153,7 +157,7 @@ export default class Prompt { this.subscribers.clear(); } - private onKeypress(char: string, key?: Key) { + private async onKeypress(char: string, key?: Key) { if (this.state === 'error') { this.state = 'active'; } @@ -172,7 +176,7 @@ export default class Prompt { if (key?.name === 'return') { if (this.opts.validate) { - const problem = this.opts.validate(this.value); + const problem = await this.opts.validate(this.value); if (problem) { this.error = problem; this.state = 'error'; diff --git a/packages/prompts/src/index.ts b/packages/prompts/src/index.ts index d10f34c..7b6f8c2 100644 --- a/packages/prompts/src/index.ts +++ b/packages/prompts/src/index.ts @@ -9,6 +9,7 @@ import { SelectPrompt, State, TextPrompt, + Validator, } from '@clack/core'; import isUnicodeSupported from 'is-unicode-supported'; import color from 'picocolors'; @@ -63,7 +64,7 @@ export interface TextOptions { placeholder?: string; defaultValue?: string; initialValue?: string; - validate?: (value: string) => string | void; + validate?: Validator; } export const text = (opts: TextOptions) => { return new TextPrompt({ @@ -99,7 +100,7 @@ export const text = (opts: TextOptions) => { export interface PasswordOptions { message: string; mask?: string; - validate?: (value: string) => string | void; + validate?: Validator; } export const password = (opts: PasswordOptions) => { return new PasswordPrompt({