import type Enquirer from 'enquirer' ; import { PromptInstance , PromptOptions , PromptSettings } from './prompt.interface' ; import { ListrEventType } from '@constants/event.constants' ; import { ListrTaskState } from '@constants/state.constants' ; import { PromptError } from '@interfaces/listr-error.interface' ; import { TaskWrapper } from '@lib/task-wrapper' ; param this param options param settings export async function createPrompt ( this , options , settings ? ) { let cancelCallback ; if ( settings ?. cancelCallback ) { cancelCallback = settings . cancelCallback ; } else { cancelCallback = defaultCancelCallback ; } if ( ! Array . isArray ( options ) ) { options = [ { ... options , name : 'default' } ] ; } else if ( options . length === 1 ) { options = options . reduce ( ( o , option ) => { return [ ... o , Object . assign ( option , { name : 'default' } ) ] ; } , [ ] ) ; } options = options . reduce ( ( o , option ) => { return [ ... o , Object . assign ( option , { stdout : this instanceof TaskWrapper ? settings ?. stdout ?? this . stdout ( ) : process . stdout , onCancel : cancelCallback . bind ( this , settings ) } ) ] ; } , [ ] ) ; let enquirer ; if ( settings ?. enquirer ) { enquirer = settings . enquirer ; } else { try { enquirer = new ( await import ( 'enquirer' ) ) . default ( ) ; } catch ( e ) { this . task . prompt = new PromptError ( 'Enquirer is a peer dependency that must be installed separately.' ) ; throw new Error ( e ) ; } } if ( this instanceof TaskWrapper ) { enquirer . on ( 'prompt' , ( prompt ) => this . task . prompt = prompt ) ; enquirer . on ( 'submit' , ( ) => this . task . prompt = undefined ) ; this . task . subscribe ( ( event ) => { if ( event . type === ListrEventType . STATE && event . data === ListrTaskState . SKIPPED ) { if ( this . task . prompt && ! ( this . task . prompt instanceof PromptError ) ) { this . task . prompt . submit ( ) ; } } } ) ; } const response = ( await enquirer . prompt ( options as any ) ) as any ; if ( options . length === 1 ) { return response . default ; } else { return response ; } } export function destroyPrompt ( this , throwError = false ) { if ( ! this . task . prompt || this . task . prompt instanceof PromptError ) { return ; } if ( throwError ) { this . task . prompt . cancel ( ) ; } else { this . task . prompt . submit ( ) ; } } function defaultCancelCallback ( this , settings ) { const errorMsg = 'Cancelled prompt.' ; if ( this instanceof TaskWrapper ) { this . task . prompt = new PromptError ( errorMsg ) ; } else if ( settings ?. error !== false ) { throw new Error ( errorMsg ) ; } else { return errorMsg ; } }