@listr2/prompt-adapter-enquirer
Version:
Listr2 prompt adapter for enquirer.
93 lines (91 loc) • 2.52 kB
JavaScript
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
// src/prompt.ts
import { ListrPromptAdapter, ListrTaskEventType, ListrTaskState, PromptError } from "listr2";
var ListrEnquirerPromptAdapter = class extends ListrPromptAdapter {
static {
__name(this, "ListrEnquirerPromptAdapter");
}
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 seperately.
*/
async run(options, settings) {
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: /* @__PURE__ */ __name(() => {
this.error = new PromptError("Cancelled prompt.");
return true;
}, "onCancel"),
...option,
stdout: settings?.stdout ?? this.wrapper.stdout(ListrTaskEventType.PROMPT)
};
});
let enquirer;
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 (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;
}
if (options?.throw) {
this.prompt.cancel();
} else {
this.prompt.submit();
}
this.reportFailed();
}
};
export {
ListrEnquirerPromptAdapter
};