UNPKG

@listr2/prompt-adapter-enquirer

Version:

Listr2 prompt adapter for enquirer.

82 lines (80 loc) 2.28 kB
import { ListrPromptAdapter, ListrTaskEventType, ListrTaskState, PromptError } from "listr2"; //#region src/prompt.ts var ListrEnquirerPromptAdapter = class extends ListrPromptAdapter { error; prompt; /** * Get the current running instance of `enquirer`. */ get instance() { return this.prompt; } /** * Create a new prompt with `enquirer`. * * `enquirer` is a peer dependency that must be installed separately. */ async run(options, settings) { /* istanbul ignore next */ if (!Array.isArray(options)) options = [{ ...options, name: "default" }]; else if (options.length === 1) options = options.map((option) => { return { ...option, name: "default" }; }); options = options.map((option) => { return { onCancel: () => { this.error = new PromptError("Cancelled prompt."); return true; }, ...option, stdout: settings?.stdout ?? this.wrapper.stdout(ListrTaskEventType.PROMPT) }; }); let enquirer; /* istanbul ignore next */ if (settings?.enquirer) enquirer = settings.enquirer; else try { enquirer = await import("enquirer").then((imported) => imported.default ? new imported.default() : new imported()); } catch { this.reportFailed(); throw new PromptError("Enquirer is a optional peer dependency that must be installed separately."); } this.reportStarted(); this.task.on(ListrTaskEventType.STATE, (event) => { if (event === ListrTaskState.SKIPPED && this.prompt && !this.error) this.cancel({ throw: false }); }); let response; try { response = await enquirer.once("prompt", (prompt) => this.prompt = prompt).prompt(options); } catch (e) { this.reportFailed(); if (e?.message?.includes("readline was closed") && this.error) throw this.error; if (this.error) throw this.error; throw e; } this.reportCompleted(); if (options.length === 1) return response.default; else return response; } /** * Cancel the ongoing prompt. */ cancel(options) { if (!this.prompt || this.error) return; try { if (options?.throw) this.prompt.cancel(); else this.prompt.submit(); } catch (error) { if (!error?.message?.includes("readline was closed")) throw error; } this.reportFailed(); } }; //#endregion export { ListrEnquirerPromptAdapter };