diff --git a/src/ux/prompter.ts b/src/ux/prompter.ts index 85ceb6ab..8348b72a 100644 --- a/src/ux/prompter.ts +++ b/src/ux/prompter.ts @@ -7,6 +7,7 @@ import { prompt, QuestionCollection, Separator, ChoiceOptions, ChoiceBase } from 'inquirer'; import { Dictionary, Nullable, ensureString } from '@salesforce/ts-types'; +import { CliUx } from '@oclif/core'; export class Prompter { /** @@ -16,6 +17,33 @@ export class Prompter { const answers = await prompt(questions, initialAnswers); return answers; } + + /** + * Prompt user for information with a timeout (in milliseconds). See https://www.npmjs.com/package/inquirer for more. + */ + public async timedPrompt( + questions: Prompter.Questions, + ms = 10000, + initialAnswers?: Partial + ): Promise { + let id: NodeJS.Timeout; + const thePrompt = prompt(questions, initialAnswers); + const timeout = new Promise((_, reject) => { + id = setTimeout(() => { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + thePrompt.ui['activePrompt'].done(); + CliUx.ux.log(); + reject(new Error(`Timed out after ${ms} ms.`)); + }, ms).unref(); + }); + + return Promise.race([timeout, thePrompt]).then((result) => { + clearTimeout(id); + return result as T; + }); + } } export namespace Prompter {