@decaf-ts/utils
Version:
module management utils for decaf-ts
1,942 lines (1,535 loc) • 1.47 MB
JavaScript
#!/usr/bin/env node
'use strict';
var require$$0 = require('kleur');
var require$$0$1 = require('readline');
var require$$3 = require('sisteransi');
var require$$2 = require('events');
var util$2 = require('util');
var fs = require('fs');
var path = require('path');
var child_process = require('child_process');
var https = require('https');
require('rollup');
require('@rollup/plugin-typescript');
require('@rollup/plugin-commonjs');
require('@rollup/plugin-node-resolve');
require('@rollup/plugin-json');
require('typescript');
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var prompts$3 = {};
var action$1;
var hasRequiredAction$1;
function requireAction$1 () {
if (hasRequiredAction$1) return action$1;
hasRequiredAction$1 = 1;
action$1 = (key, isSelect) => {
if (key.meta && key.name !== 'escape') return;
if (key.ctrl) {
if (key.name === 'a') return 'first';
if (key.name === 'c') return 'abort';
if (key.name === 'd') return 'abort';
if (key.name === 'e') return 'last';
if (key.name === 'g') return 'reset';
}
if (isSelect) {
if (key.name === 'j') return 'down';
if (key.name === 'k') return 'up';
}
if (key.name === 'return') return 'submit';
if (key.name === 'enter') return 'submit'; // ctrl + J
if (key.name === 'backspace') return 'delete';
if (key.name === 'delete') return 'deleteForward';
if (key.name === 'abort') return 'abort';
if (key.name === 'escape') return 'exit';
if (key.name === 'tab') return 'next';
if (key.name === 'pagedown') return 'nextPage';
if (key.name === 'pageup') return 'prevPage'; // TODO create home() in prompt types (e.g. TextPrompt)
if (key.name === 'home') return 'home'; // TODO create end() in prompt types (e.g. TextPrompt)
if (key.name === 'end') return 'end';
if (key.name === 'up') return 'up';
if (key.name === 'down') return 'down';
if (key.name === 'right') return 'right';
if (key.name === 'left') return 'left';
return false;
};
return action$1;
}
var strip$1;
var hasRequiredStrip$1;
function requireStrip$1 () {
if (hasRequiredStrip$1) return strip$1;
hasRequiredStrip$1 = 1;
strip$1 = str => {
const pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))'].join('|');
const RGX = new RegExp(pattern, 'g');
return typeof str === 'string' ? str.replace(RGX, '') : str;
};
return strip$1;
}
var clear$2;
var hasRequiredClear$1;
function requireClear$1 () {
if (hasRequiredClear$1) return clear$2;
hasRequiredClear$1 = 1;
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike) { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
const strip = requireStrip$1();
const _require = require$$3,
erase = _require.erase,
cursor = _require.cursor;
const width = str => [...strip(str)].length;
/**
* @param {string} prompt
* @param {number} perLine
*/
clear$2 = function (prompt, perLine) {
if (!perLine) return erase.line + cursor.to(0);
let rows = 0;
const lines = prompt.split(/\r?\n/);
var _iterator = _createForOfIteratorHelper(lines),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
let line = _step.value;
rows += 1 + Math.floor(Math.max(width(line) - 1, 0) / perLine);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return erase.lines(rows);
};
return clear$2;
}
var figures_1$1;
var hasRequiredFigures$1;
function requireFigures$1 () {
if (hasRequiredFigures$1) return figures_1$1;
hasRequiredFigures$1 = 1;
const main = {
arrowUp: '↑',
arrowDown: '↓',
arrowLeft: '←',
arrowRight: '→',
radioOn: '◉',
radioOff: '◯',
tick: '✔',
cross: '✖',
ellipsis: '…',
pointerSmall: '›',
line: '─',
pointer: '❯'
};
const win = {
arrowUp: main.arrowUp,
arrowDown: main.arrowDown,
arrowLeft: main.arrowLeft,
arrowRight: main.arrowRight,
radioOn: '(*)',
radioOff: '( )',
tick: '√',
cross: '×',
ellipsis: '...',
pointerSmall: '»',
line: '─',
pointer: '>'
};
const figures = process.platform === 'win32' ? win : main;
figures_1$1 = figures;
return figures_1$1;
}
var style$2;
var hasRequiredStyle$1;
function requireStyle$1 () {
if (hasRequiredStyle$1) return style$2;
hasRequiredStyle$1 = 1;
const c = require$$0;
const figures = requireFigures$1(); // rendering user input.
const styles = Object.freeze({
password: {
scale: 1,
render: input => '*'.repeat(input.length)
},
emoji: {
scale: 2,
render: input => '😃'.repeat(input.length)
},
invisible: {
scale: 0,
render: input => ''
},
default: {
scale: 1,
render: input => `${input}`
}
});
const render = type => styles[type] || styles.default; // icon to signalize a prompt.
const symbols = Object.freeze({
aborted: c.red(figures.cross),
done: c.green(figures.tick),
exited: c.yellow(figures.cross),
default: c.cyan('?')
});
const symbol = (done, aborted, exited) => aborted ? symbols.aborted : exited ? symbols.exited : done ? symbols.done : symbols.default; // between the question and the user's input.
const delimiter = completing => c.gray(completing ? figures.ellipsis : figures.pointerSmall);
const item = (expandable, expanded) => c.gray(expandable ? expanded ? figures.pointerSmall : '+' : figures.line);
style$2 = {
styles,
render,
symbols,
symbol,
delimiter,
item
};
return style$2;
}
var lines$1;
var hasRequiredLines$1;
function requireLines$1 () {
if (hasRequiredLines$1) return lines$1;
hasRequiredLines$1 = 1;
const strip = requireStrip$1();
/**
* @param {string} msg
* @param {number} perLine
*/
lines$1 = function (msg, perLine) {
let lines = String(strip(msg) || '').split(/\r?\n/);
if (!perLine) return lines.length;
return lines.map(l => Math.ceil(l.length / perLine)).reduce((a, b) => a + b);
};
return lines$1;
}
var wrap$1;
var hasRequiredWrap$1;
function requireWrap$1 () {
if (hasRequiredWrap$1) return wrap$1;
hasRequiredWrap$1 = 1;
/**
* @param {string} msg The message to wrap
* @param {object} opts
* @param {number|string} [opts.margin] Left margin
* @param {number} opts.width Maximum characters per line including the margin
*/
wrap$1 = (msg, opts = {}) => {
const tab = Number.isSafeInteger(parseInt(opts.margin)) ? new Array(parseInt(opts.margin)).fill(' ').join('') : opts.margin || '';
const width = opts.width;
return (msg || '').split(/\r?\n/g).map(line => line.split(/\s+/g).reduce((arr, w) => {
if (w.length + tab.length >= width || arr[arr.length - 1].length + w.length + 1 < width) arr[arr.length - 1] += ` ${w}`;else arr.push(`${tab}${w}`);
return arr;
}, [tab]).join('\n')).join('\n');
};
return wrap$1;
}
var entriesToDisplay$1;
var hasRequiredEntriesToDisplay$1;
function requireEntriesToDisplay$1 () {
if (hasRequiredEntriesToDisplay$1) return entriesToDisplay$1;
hasRequiredEntriesToDisplay$1 = 1;
/**
* Determine what entries should be displayed on the screen, based on the
* currently selected index and the maximum visible. Used in list-based
* prompts like `select` and `multiselect`.
*
* @param {number} cursor the currently selected entry
* @param {number} total the total entries available to display
* @param {number} [maxVisible] the number of entries that can be displayed
*/
entriesToDisplay$1 = (cursor, total, maxVisible) => {
maxVisible = maxVisible || total;
let startIndex = Math.min(total - maxVisible, cursor - Math.floor(maxVisible / 2));
if (startIndex < 0) startIndex = 0;
let endIndex = Math.min(startIndex + maxVisible, total);
return {
startIndex,
endIndex
};
};
return entriesToDisplay$1;
}
var util$1;
var hasRequiredUtil$1;
function requireUtil$1 () {
if (hasRequiredUtil$1) return util$1;
hasRequiredUtil$1 = 1;
util$1 = {
action: requireAction$1(),
clear: requireClear$1(),
style: requireStyle$1(),
strip: requireStrip$1(),
figures: requireFigures$1(),
lines: requireLines$1(),
wrap: requireWrap$1(),
entriesToDisplay: requireEntriesToDisplay$1()
};
return util$1;
}
var prompt$1;
var hasRequiredPrompt$1;
function requirePrompt$1 () {
if (hasRequiredPrompt$1) return prompt$1;
hasRequiredPrompt$1 = 1;
const readline = require$$0$1;
const _require = requireUtil$1(),
action = _require.action;
const EventEmitter = require$$2;
const _require2 = require$$3,
beep = _require2.beep,
cursor = _require2.cursor;
const color = require$$0;
/**
* Base prompt skeleton
* @param {Stream} [opts.stdin] The Readable stream to listen to
* @param {Stream} [opts.stdout] The Writable stream to write readline data to
*/
class Prompt extends EventEmitter {
constructor(opts = {}) {
super();
this.firstRender = true;
this.in = opts.stdin || process.stdin;
this.out = opts.stdout || process.stdout;
this.onRender = (opts.onRender || (() => void 0)).bind(this);
const rl = readline.createInterface({
input: this.in,
escapeCodeTimeout: 50
});
readline.emitKeypressEvents(this.in, rl);
if (this.in.isTTY) this.in.setRawMode(true);
const isSelect = ['SelectPrompt', 'MultiselectPrompt'].indexOf(this.constructor.name) > -1;
const keypress = (str, key) => {
let a = action(key, isSelect);
if (a === false) {
this._ && this._(str, key);
} else if (typeof this[a] === 'function') {
this[a](key);
} else {
this.bell();
}
};
this.close = () => {
this.out.write(cursor.show);
this.in.removeListener('keypress', keypress);
if (this.in.isTTY) this.in.setRawMode(false);
rl.close();
this.emit(this.aborted ? 'abort' : this.exited ? 'exit' : 'submit', this.value);
this.closed = true;
};
this.in.on('keypress', keypress);
}
fire() {
this.emit('state', {
value: this.value,
aborted: !!this.aborted,
exited: !!this.exited
});
}
bell() {
this.out.write(beep);
}
render() {
this.onRender(color);
if (this.firstRender) this.firstRender = false;
}
}
prompt$1 = Prompt;
return prompt$1;
}
var text$1;
var hasRequiredText$1;
function requireText$1 () {
if (hasRequiredText$1) return text$1;
hasRequiredText$1 = 1;
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
const color = require$$0;
const Prompt = requirePrompt$1();
const _require = require$$3,
erase = _require.erase,
cursor = _require.cursor;
const _require2 = requireUtil$1(),
style = _require2.style,
clear = _require2.clear,
lines = _require2.lines,
figures = _require2.figures;
/**
* TextPrompt Base Element
* @param {Object} opts Options
* @param {String} opts.message Message
* @param {String} [opts.style='default'] Render style
* @param {String} [opts.initial] Default value
* @param {Function} [opts.validate] Validate function
* @param {Stream} [opts.stdin] The Readable stream to listen to
* @param {Stream} [opts.stdout] The Writable stream to write readline data to
* @param {String} [opts.error] The invalid error label
*/
class TextPrompt extends Prompt {
constructor(opts = {}) {
super(opts);
this.transform = style.render(opts.style);
this.scale = this.transform.scale;
this.msg = opts.message;
this.initial = opts.initial || ``;
this.validator = opts.validate || (() => true);
this.value = ``;
this.errorMsg = opts.error || `Please Enter A Valid Value`;
this.cursor = Number(!!this.initial);
this.cursorOffset = 0;
this.clear = clear(``, this.out.columns);
this.render();
}
set value(v) {
if (!v && this.initial) {
this.placeholder = true;
this.rendered = color.gray(this.transform.render(this.initial));
} else {
this.placeholder = false;
this.rendered = this.transform.render(v);
}
this._value = v;
this.fire();
}
get value() {
return this._value;
}
reset() {
this.value = ``;
this.cursor = Number(!!this.initial);
this.cursorOffset = 0;
this.fire();
this.render();
}
exit() {
this.abort();
}
abort() {
this.value = this.value || this.initial;
this.done = this.aborted = true;
this.error = false;
this.red = false;
this.fire();
this.render();
this.out.write('\n');
this.close();
}
validate() {
var _this = this;
return _asyncToGenerator(function* () {
let valid = yield _this.validator(_this.value);
if (typeof valid === `string`) {
_this.errorMsg = valid;
valid = false;
}
_this.error = !valid;
})();
}
submit() {
var _this2 = this;
return _asyncToGenerator(function* () {
_this2.value = _this2.value || _this2.initial;
_this2.cursorOffset = 0;
_this2.cursor = _this2.rendered.length;
yield _this2.validate();
if (_this2.error) {
_this2.red = true;
_this2.fire();
_this2.render();
return;
}
_this2.done = true;
_this2.aborted = false;
_this2.fire();
_this2.render();
_this2.out.write('\n');
_this2.close();
})();
}
next() {
if (!this.placeholder) return this.bell();
this.value = this.initial;
this.cursor = this.rendered.length;
this.fire();
this.render();
}
moveCursor(n) {
if (this.placeholder) return;
this.cursor = this.cursor + n;
this.cursorOffset += n;
}
_(c, key) {
let s1 = this.value.slice(0, this.cursor);
let s2 = this.value.slice(this.cursor);
this.value = `${s1}${c}${s2}`;
this.red = false;
this.cursor = this.placeholder ? 0 : s1.length + 1;
this.render();
}
delete() {
if (this.isCursorAtStart()) return this.bell();
let s1 = this.value.slice(0, this.cursor - 1);
let s2 = this.value.slice(this.cursor);
this.value = `${s1}${s2}`;
this.red = false;
if (this.isCursorAtStart()) {
this.cursorOffset = 0;
} else {
this.cursorOffset++;
this.moveCursor(-1);
}
this.render();
}
deleteForward() {
if (this.cursor * this.scale >= this.rendered.length || this.placeholder) return this.bell();
let s1 = this.value.slice(0, this.cursor);
let s2 = this.value.slice(this.cursor + 1);
this.value = `${s1}${s2}`;
this.red = false;
if (this.isCursorAtEnd()) {
this.cursorOffset = 0;
} else {
this.cursorOffset++;
}
this.render();
}
first() {
this.cursor = 0;
this.render();
}
last() {
this.cursor = this.value.length;
this.render();
}
left() {
if (this.cursor <= 0 || this.placeholder) return this.bell();
this.moveCursor(-1);
this.render();
}
right() {
if (this.cursor * this.scale >= this.rendered.length || this.placeholder) return this.bell();
this.moveCursor(1);
this.render();
}
isCursorAtStart() {
return this.cursor === 0 || this.placeholder && this.cursor === 1;
}
isCursorAtEnd() {
return this.cursor === this.rendered.length || this.placeholder && this.cursor === this.rendered.length + 1;
}
render() {
if (this.closed) return;
if (!this.firstRender) {
if (this.outputError) this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns));
this.out.write(clear(this.outputText, this.out.columns));
}
super.render();
this.outputError = '';
this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.red ? color.red(this.rendered) : this.rendered].join(` `);
if (this.error) {
this.outputError += this.errorMsg.split(`\n`).reduce((a, l, i) => a + `\n${i ? ' ' : figures.pointerSmall} ${color.red().italic(l)}`, ``);
}
this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore + cursor.move(this.cursorOffset, 0));
}
}
text$1 = TextPrompt;
return text$1;
}
var select$1;
var hasRequiredSelect$1;
function requireSelect$1 () {
if (hasRequiredSelect$1) return select$1;
hasRequiredSelect$1 = 1;
const color = require$$0;
const Prompt = requirePrompt$1();
const _require = requireUtil$1(),
style = _require.style,
clear = _require.clear,
figures = _require.figures,
wrap = _require.wrap,
entriesToDisplay = _require.entriesToDisplay;
const _require2 = require$$3,
cursor = _require2.cursor;
/**
* SelectPrompt Base Element
* @param {Object} opts Options
* @param {String} opts.message Message
* @param {Array} opts.choices Array of choice objects
* @param {String} [opts.hint] Hint to display
* @param {Number} [opts.initial] Index of default value
* @param {Stream} [opts.stdin] The Readable stream to listen to
* @param {Stream} [opts.stdout] The Writable stream to write readline data to
* @param {Number} [opts.optionsPerPage=10] Max options to display at once
*/
class SelectPrompt extends Prompt {
constructor(opts = {}) {
super(opts);
this.msg = opts.message;
this.hint = opts.hint || '- Use arrow-keys. Return to submit.';
this.warn = opts.warn || '- This option is disabled';
this.cursor = opts.initial || 0;
this.choices = opts.choices.map((ch, idx) => {
if (typeof ch === 'string') ch = {
title: ch,
value: idx
};
return {
title: ch && (ch.title || ch.value || ch),
value: ch && (ch.value === undefined ? idx : ch.value),
description: ch && ch.description,
selected: ch && ch.selected,
disabled: ch && ch.disabled
};
});
this.optionsPerPage = opts.optionsPerPage || 10;
this.value = (this.choices[this.cursor] || {}).value;
this.clear = clear('', this.out.columns);
this.render();
}
moveCursor(n) {
this.cursor = n;
this.value = this.choices[n].value;
this.fire();
}
reset() {
this.moveCursor(0);
this.fire();
this.render();
}
exit() {
this.abort();
}
abort() {
this.done = this.aborted = true;
this.fire();
this.render();
this.out.write('\n');
this.close();
}
submit() {
if (!this.selection.disabled) {
this.done = true;
this.aborted = false;
this.fire();
this.render();
this.out.write('\n');
this.close();
} else this.bell();
}
first() {
this.moveCursor(0);
this.render();
}
last() {
this.moveCursor(this.choices.length - 1);
this.render();
}
up() {
if (this.cursor === 0) {
this.moveCursor(this.choices.length - 1);
} else {
this.moveCursor(this.cursor - 1);
}
this.render();
}
down() {
if (this.cursor === this.choices.length - 1) {
this.moveCursor(0);
} else {
this.moveCursor(this.cursor + 1);
}
this.render();
}
next() {
this.moveCursor((this.cursor + 1) % this.choices.length);
this.render();
}
_(c, key) {
if (c === ' ') return this.submit();
}
get selection() {
return this.choices[this.cursor];
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns));
super.render();
let _entriesToDisplay = entriesToDisplay(this.cursor, this.choices.length, this.optionsPerPage),
startIndex = _entriesToDisplay.startIndex,
endIndex = _entriesToDisplay.endIndex; // Print prompt
this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.done ? this.selection.title : this.selection.disabled ? color.yellow(this.warn) : color.gray(this.hint)].join(' '); // Print choices
if (!this.done) {
this.outputText += '\n';
for (let i = startIndex; i < endIndex; i++) {
let title,
prefix,
desc = '',
v = this.choices[i]; // Determine whether to display "more choices" indicators
if (i === startIndex && startIndex > 0) {
prefix = figures.arrowUp;
} else if (i === endIndex - 1 && endIndex < this.choices.length) {
prefix = figures.arrowDown;
} else {
prefix = ' ';
}
if (v.disabled) {
title = this.cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title);
prefix = (this.cursor === i ? color.bold().gray(figures.pointer) + ' ' : ' ') + prefix;
} else {
title = this.cursor === i ? color.cyan().underline(v.title) : v.title;
prefix = (this.cursor === i ? color.cyan(figures.pointer) + ' ' : ' ') + prefix;
if (v.description && this.cursor === i) {
desc = ` - ${v.description}`;
if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) {
desc = '\n' + wrap(v.description, {
margin: 3,
width: this.out.columns
});
}
}
}
this.outputText += `${prefix} ${title}${color.gray(desc)}\n`;
}
}
this.out.write(this.outputText);
}
}
select$1 = SelectPrompt;
return select$1;
}
var toggle$1;
var hasRequiredToggle$1;
function requireToggle$1 () {
if (hasRequiredToggle$1) return toggle$1;
hasRequiredToggle$1 = 1;
const color = require$$0;
const Prompt = requirePrompt$1();
const _require = requireUtil$1(),
style = _require.style,
clear = _require.clear;
const _require2 = require$$3,
cursor = _require2.cursor,
erase = _require2.erase;
/**
* TogglePrompt Base Element
* @param {Object} opts Options
* @param {String} opts.message Message
* @param {Boolean} [opts.initial=false] Default value
* @param {String} [opts.active='no'] Active label
* @param {String} [opts.inactive='off'] Inactive label
* @param {Stream} [opts.stdin] The Readable stream to listen to
* @param {Stream} [opts.stdout] The Writable stream to write readline data to
*/
class TogglePrompt extends Prompt {
constructor(opts = {}) {
super(opts);
this.msg = opts.message;
this.value = !!opts.initial;
this.active = opts.active || 'on';
this.inactive = opts.inactive || 'off';
this.initialValue = this.value;
this.render();
}
reset() {
this.value = this.initialValue;
this.fire();
this.render();
}
exit() {
this.abort();
}
abort() {
this.done = this.aborted = true;
this.fire();
this.render();
this.out.write('\n');
this.close();
}
submit() {
this.done = true;
this.aborted = false;
this.fire();
this.render();
this.out.write('\n');
this.close();
}
deactivate() {
if (this.value === false) return this.bell();
this.value = false;
this.render();
}
activate() {
if (this.value === true) return this.bell();
this.value = true;
this.render();
}
delete() {
this.deactivate();
}
left() {
this.deactivate();
}
right() {
this.activate();
}
down() {
this.deactivate();
}
up() {
this.activate();
}
next() {
this.value = !this.value;
this.fire();
this.render();
}
_(c, key) {
if (c === ' ') {
this.value = !this.value;
} else if (c === '1') {
this.value = true;
} else if (c === '0') {
this.value = false;
} else return this.bell();
this.render();
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns));
super.render();
this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.value ? this.inactive : color.cyan().underline(this.inactive), color.gray('/'), this.value ? color.cyan().underline(this.active) : this.active].join(' ');
this.out.write(erase.line + cursor.to(0) + this.outputText);
}
}
toggle$1 = TogglePrompt;
return toggle$1;
}
var datepart$1;
var hasRequiredDatepart$1;
function requireDatepart$1 () {
if (hasRequiredDatepart$1) return datepart$1;
hasRequiredDatepart$1 = 1;
class DatePart {
constructor({
token,
date,
parts,
locales
}) {
this.token = token;
this.date = date || new Date();
this.parts = parts || [this];
this.locales = locales || {};
}
up() {}
down() {}
next() {
const currentIdx = this.parts.indexOf(this);
return this.parts.find((part, idx) => idx > currentIdx && part instanceof DatePart);
}
setTo(val) {}
prev() {
let parts = [].concat(this.parts).reverse();
const currentIdx = parts.indexOf(this);
return parts.find((part, idx) => idx > currentIdx && part instanceof DatePart);
}
toString() {
return String(this.date);
}
}
datepart$1 = DatePart;
return datepart$1;
}
var meridiem$1;
var hasRequiredMeridiem$1;
function requireMeridiem$1 () {
if (hasRequiredMeridiem$1) return meridiem$1;
hasRequiredMeridiem$1 = 1;
const DatePart = requireDatepart$1();
class Meridiem extends DatePart {
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setHours((this.date.getHours() + 12) % 24);
}
down() {
this.up();
}
toString() {
let meridiem = this.date.getHours() > 12 ? 'pm' : 'am';
return /\A/.test(this.token) ? meridiem.toUpperCase() : meridiem;
}
}
meridiem$1 = Meridiem;
return meridiem$1;
}
var day$1;
var hasRequiredDay$1;
function requireDay$1 () {
if (hasRequiredDay$1) return day$1;
hasRequiredDay$1 = 1;
const DatePart = requireDatepart$1();
const pos = n => {
n = n % 10;
return n === 1 ? 'st' : n === 2 ? 'nd' : n === 3 ? 'rd' : 'th';
};
class Day extends DatePart {
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setDate(this.date.getDate() + 1);
}
down() {
this.date.setDate(this.date.getDate() - 1);
}
setTo(val) {
this.date.setDate(parseInt(val.substr(-2)));
}
toString() {
let date = this.date.getDate();
let day = this.date.getDay();
return this.token === 'DD' ? String(date).padStart(2, '0') : this.token === 'Do' ? date + pos(date) : this.token === 'd' ? day + 1 : this.token === 'ddd' ? this.locales.weekdaysShort[day] : this.token === 'dddd' ? this.locales.weekdays[day] : date;
}
}
day$1 = Day;
return day$1;
}
var hours$1;
var hasRequiredHours$1;
function requireHours$1 () {
if (hasRequiredHours$1) return hours$1;
hasRequiredHours$1 = 1;
const DatePart = requireDatepart$1();
class Hours extends DatePart {
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setHours(this.date.getHours() + 1);
}
down() {
this.date.setHours(this.date.getHours() - 1);
}
setTo(val) {
this.date.setHours(parseInt(val.substr(-2)));
}
toString() {
let hours = this.date.getHours();
if (/h/.test(this.token)) hours = hours % 12 || 12;
return this.token.length > 1 ? String(hours).padStart(2, '0') : hours;
}
}
hours$1 = Hours;
return hours$1;
}
var milliseconds$1;
var hasRequiredMilliseconds$1;
function requireMilliseconds$1 () {
if (hasRequiredMilliseconds$1) return milliseconds$1;
hasRequiredMilliseconds$1 = 1;
const DatePart = requireDatepart$1();
class Milliseconds extends DatePart {
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setMilliseconds(this.date.getMilliseconds() + 1);
}
down() {
this.date.setMilliseconds(this.date.getMilliseconds() - 1);
}
setTo(val) {
this.date.setMilliseconds(parseInt(val.substr(-this.token.length)));
}
toString() {
return String(this.date.getMilliseconds()).padStart(4, '0').substr(0, this.token.length);
}
}
milliseconds$1 = Milliseconds;
return milliseconds$1;
}
var minutes$1;
var hasRequiredMinutes$1;
function requireMinutes$1 () {
if (hasRequiredMinutes$1) return minutes$1;
hasRequiredMinutes$1 = 1;
const DatePart = requireDatepart$1();
class Minutes extends DatePart {
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setMinutes(this.date.getMinutes() + 1);
}
down() {
this.date.setMinutes(this.date.getMinutes() - 1);
}
setTo(val) {
this.date.setMinutes(parseInt(val.substr(-2)));
}
toString() {
let m = this.date.getMinutes();
return this.token.length > 1 ? String(m).padStart(2, '0') : m;
}
}
minutes$1 = Minutes;
return minutes$1;
}
var month$1;
var hasRequiredMonth$1;
function requireMonth$1 () {
if (hasRequiredMonth$1) return month$1;
hasRequiredMonth$1 = 1;
const DatePart = requireDatepart$1();
class Month extends DatePart {
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setMonth(this.date.getMonth() + 1);
}
down() {
this.date.setMonth(this.date.getMonth() - 1);
}
setTo(val) {
val = parseInt(val.substr(-2)) - 1;
this.date.setMonth(val < 0 ? 0 : val);
}
toString() {
let month = this.date.getMonth();
let tl = this.token.length;
return tl === 2 ? String(month + 1).padStart(2, '0') : tl === 3 ? this.locales.monthsShort[month] : tl === 4 ? this.locales.months[month] : String(month + 1);
}
}
month$1 = Month;
return month$1;
}
var seconds$1;
var hasRequiredSeconds$1;
function requireSeconds$1 () {
if (hasRequiredSeconds$1) return seconds$1;
hasRequiredSeconds$1 = 1;
const DatePart = requireDatepart$1();
class Seconds extends DatePart {
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setSeconds(this.date.getSeconds() + 1);
}
down() {
this.date.setSeconds(this.date.getSeconds() - 1);
}
setTo(val) {
this.date.setSeconds(parseInt(val.substr(-2)));
}
toString() {
let s = this.date.getSeconds();
return this.token.length > 1 ? String(s).padStart(2, '0') : s;
}
}
seconds$1 = Seconds;
return seconds$1;
}
var year$1;
var hasRequiredYear$1;
function requireYear$1 () {
if (hasRequiredYear$1) return year$1;
hasRequiredYear$1 = 1;
const DatePart = requireDatepart$1();
class Year extends DatePart {
constructor(opts = {}) {
super(opts);
}
up() {
this.date.setFullYear(this.date.getFullYear() + 1);
}
down() {
this.date.setFullYear(this.date.getFullYear() - 1);
}
setTo(val) {
this.date.setFullYear(val.substr(-4));
}
toString() {
let year = String(this.date.getFullYear()).padStart(4, '0');
return this.token.length === 2 ? year.substr(-2) : year;
}
}
year$1 = Year;
return year$1;
}
var dateparts$1;
var hasRequiredDateparts$1;
function requireDateparts$1 () {
if (hasRequiredDateparts$1) return dateparts$1;
hasRequiredDateparts$1 = 1;
dateparts$1 = {
DatePart: requireDatepart$1(),
Meridiem: requireMeridiem$1(),
Day: requireDay$1(),
Hours: requireHours$1(),
Milliseconds: requireMilliseconds$1(),
Minutes: requireMinutes$1(),
Month: requireMonth$1(),
Seconds: requireSeconds$1(),
Year: requireYear$1()
};
return dateparts$1;
}
var date$1;
var hasRequiredDate$1;
function requireDate$1 () {
if (hasRequiredDate$1) return date$1;
hasRequiredDate$1 = 1;
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
const color = require$$0;
const Prompt = requirePrompt$1();
const _require = requireUtil$1(),
style = _require.style,
clear = _require.clear,
figures = _require.figures;
const _require2 = require$$3,
erase = _require2.erase,
cursor = _require2.cursor;
const _require3 = requireDateparts$1(),
DatePart = _require3.DatePart,
Meridiem = _require3.Meridiem,
Day = _require3.Day,
Hours = _require3.Hours,
Milliseconds = _require3.Milliseconds,
Minutes = _require3.Minutes,
Month = _require3.Month,
Seconds = _require3.Seconds,
Year = _require3.Year;
const regex = /\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g;
const regexGroups = {
1: ({
token
}) => token.replace(/\\(.)/g, '$1'),
2: opts => new Day(opts),
// Day // TODO
3: opts => new Month(opts),
// Month
4: opts => new Year(opts),
// Year
5: opts => new Meridiem(opts),
// AM/PM // TODO (special)
6: opts => new Hours(opts),
// Hours
7: opts => new Minutes(opts),
// Minutes
8: opts => new Seconds(opts),
// Seconds
9: opts => new Milliseconds(opts) // Fractional seconds
};
const dfltLocales = {
months: 'January,February,March,April,May,June,July,August,September,October,November,December'.split(','),
monthsShort: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
weekdaysShort: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(',')
};
/**
* DatePrompt Base Element
* @param {Object} opts Options
* @param {String} opts.message Message
* @param {Number} [opts.initial] Index of default value
* @param {String} [opts.mask] The format mask
* @param {object} [opts.locales] The date locales
* @param {String} [opts.error] The error message shown on invalid value
* @param {Function} [opts.validate] Function to validate the submitted value
* @param {Stream} [opts.stdin] The Readable stream to listen to
* @param {Stream} [opts.stdout] The Writable stream to write readline data to
*/
class DatePrompt extends Prompt {
constructor(opts = {}) {
super(opts);
this.msg = opts.message;
this.cursor = 0;
this.typed = '';
this.locales = Object.assign(dfltLocales, opts.locales);
this._date = opts.initial || new Date();
this.errorMsg = opts.error || 'Please Enter A Valid Value';
this.validator = opts.validate || (() => true);
this.mask = opts.mask || 'YYYY-MM-DD HH:mm:ss';
this.clear = clear('', this.out.columns);
this.render();
}
get value() {
return this.date;
}
get date() {
return this._date;
}
set date(date) {
if (date) this._date.setTime(date.getTime());
}
set mask(mask) {
let result;
this.parts = [];
while (result = regex.exec(mask)) {
let match = result.shift();
let idx = result.findIndex(gr => gr != null);
this.parts.push(idx in regexGroups ? regexGroups[idx]({
token: result[idx] || match,
date: this.date,
parts: this.parts,
locales: this.locales
}) : result[idx] || match);
}
let parts = this.parts.reduce((arr, i) => {
if (typeof i === 'string' && typeof arr[arr.length - 1] === 'string') arr[arr.length - 1] += i;else arr.push(i);
return arr;
}, []);
this.parts.splice(0);
this.parts.push(...parts);
this.reset();
}
moveCursor(n) {
this.typed = '';
this.cursor = n;
this.fire();
}
reset() {
this.moveCursor(this.parts.findIndex(p => p instanceof DatePart));
this.fire();
this.render();
}
exit() {
this.abort();
}
abort() {
this.done = this.aborted = true;
this.error = false;
this.fire();
this.render();
this.out.write('\n');
this.close();
}
validate() {
var _this = this;
return _asyncToGenerator(function* () {
let valid = yield _this.validator(_this.value);
if (typeof valid === 'string') {
_this.errorMsg = valid;
valid = false;
}
_this.error = !valid;
})();
}
submit() {
var _this2 = this;
return _asyncToGenerator(function* () {
yield _this2.validate();
if (_this2.error) {
_this2.color = 'red';
_this2.fire();
_this2.render();
return;
}
_this2.done = true;
_this2.aborted = false;
_this2.fire();
_this2.render();
_this2.out.write('\n');
_this2.close();
})();
}
up() {
this.typed = '';
this.parts[this.cursor].up();
this.render();
}
down() {
this.typed = '';
this.parts[this.cursor].down();
this.render();
}
left() {
let prev = this.parts[this.cursor].prev();
if (prev == null) return this.bell();
this.moveCursor(this.parts.indexOf(prev));
this.render();
}
right() {
let next = this.parts[this.cursor].next();
if (next == null) return this.bell();
this.moveCursor(this.parts.indexOf(next));
this.render();
}
next() {
let next = this.parts[this.cursor].next();
this.moveCursor(next ? this.parts.indexOf(next) : this.parts.findIndex(part => part instanceof DatePart));
this.render();
}
_(c) {
if (/\d/.test(c)) {
this.typed += c;
this.parts[this.cursor].setTo(this.typed);
this.render();
}
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns));
super.render(); // Print prompt
this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.parts.reduce((arr, p, idx) => arr.concat(idx === this.cursor && !this.done ? color.cyan().underline(p.toString()) : p), []).join('')].join(' '); // Print error
if (this.error) {
this.outputText += this.errorMsg.split('\n').reduce((a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``);
}
this.out.write(erase.line + cursor.to(0) + this.outputText);
}
}
date$1 = DatePrompt;
return date$1;
}
var number$1;
var hasRequiredNumber$1;
function requireNumber$1 () {
if (hasRequiredNumber$1) return number$1;
hasRequiredNumber$1 = 1;
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
const color = require$$0;
const Prompt = requirePrompt$1();
const _require = require$$3,
cursor = _require.cursor,
erase = _require.erase;
const _require2 = requireUtil$1(),
style = _require2.style,
figures = _require2.figures,
clear = _require2.clear,
lines = _require2.lines;
const isNumber = /[0-9]/;
const isDef = any => any !== undefined;
const round = (number, precision) => {
let factor = Math.pow(10, precision);
return Math.round(number * factor) / factor;
};
/**
* NumberPrompt Base Element
* @param {Object} opts Options
* @param {String} opts.message Message
* @param {String} [opts.style='default'] Render style
* @param {Number} [opts.initial] Default value
* @param {Number} [opts.max=+Infinity] Max value
* @param {Number} [opts.min=-Infinity] Min value
* @param {Boolean} [opts.float=false] Parse input as floats
* @param {Number} [opts.round=2] Round floats to x decimals
* @param {Number} [opts.increment=1] Number to increment by when using arrow-keys
* @param {Function} [opts.validate] Validate function
* @param {Stream} [opts.stdin] The Readable stream to listen to
* @param {Stream} [opts.stdout] The Writable stream to write readline data to
* @param {String} [opts.error] The invalid error label
*/
class NumberPrompt extends Prompt {
constructor(opts = {}) {
super(opts);
this.transform = style.render(opts.style);
this.msg = opts.message;
this.initial = isDef(opts.initial) ? opts.initial : '';
this.float = !!opts.float;
this.round = opts.round || 2;
this.inc = opts.increment || 1;
this.min = isDef(opts.min) ? opts.min : -Infinity;
this.max = isDef(opts.max) ? opts.max : Infinity;
this.errorMsg = opts.error || `Please Enter A Valid Value`;
this.validator = opts.validate || (() => true);
this.color = `cyan`;
this.value = ``;
this.typed = ``;
this.lastHit = 0;
this.render();
}
set value(v) {
if (!v && v !== 0) {
this.placeholder = true;
this.rendered = color.gray(this.transform.render(`${this.initial}`));
this._value = ``;
} else {
this.placeholder = false;
this.rendered = this.transform.render(`${round(v, this.round)}`);
this._value = round(v, this.round);
}
this.fire();
}
get value() {
return this._value;
}
parse(x) {
return this.float ? parseFloat(x) : parseInt(x);
}
valid(c) {
return c === `-` || c === `.` && this.float || isNumber.test(c);
}
reset() {
this.typed = ``;
this.value = ``;
this.fire();
this.render();
}
exit() {
this.abort();
}
abort() {
let x = this.value;
this.value = x !== `` ? x : this.initial;
this.done = this.aborted = true;
this.error = false;
this.fire();
this.render();
this.out.write(`\n`);
this.close();
}
validate() {
var _this = this;
return _asyncToGenerator(function* () {
let valid = yield _this.validator(_this.value);
if (typeof valid === `string`) {
_this.errorMsg = valid;
valid = false;
}
_this.error = !valid;
})();
}
submit() {
var _this2 = this;
return _asyncToGenerator(function* () {
yield _this2.validate();
if (_this2.error) {
_this2.color = `red`;
_this2.fire();
_this2.render();
return;
}
let x = _this2.value;
_this2.value = x !== `` ? x : _this2.initial;
_this2.done = true;
_this2.aborted = false;
_this2.error = false;
_this2.fire();
_this2.render();
_this2.out.write(`\n`);
_this2.close();
})();
}
up() {
this.typed = ``;
if (this.value === '') {
this.value = this.min - this.inc;
}
if (this.value >= this.max) return this.bell();
this.value += this.inc;
this.color = `cyan`;
this.fire();
this.render();
}
down() {
this.typed = ``;
if (this.value === '') {
this.value = this.min + this.inc;
}
if (this.value <= this.min) return this.bell();
this.value -= this.inc;
this.color = `cyan`;
this.fire();
this.render();
}
delete() {
let val = this.value.toString();
if (val.length === 0) return this.bell();
this.value = this.parse(val = val.slice(0, -1)) || ``;
if (this.value !== '' && this.value < this.min) {
this.value = this.min;
}
this.color = `cyan`;
this.fire();
this.render();
}
next() {
this.value = this.initial;
this.fire();
this.render();
}
_(c, key) {
if (!this.valid(c)) return this.bell();
const now = Date.now();
if (now - this.lastHit > 1000) this.typed = ``; // 1s elapsed
this.typed += c;
this.lastHit = now;
this.color = `cyan`;
if (c === `.`) return this.fire();
this.value = Math.min(this.parse(this.typed), this.max);
if (this.value > this.max) this.value = this.max;
if (this.value < this.min) this.value = this.min;
this.fire();
this.render();
}
render() {
if (this.closed) return;
if (!this.firstRender) {
if (this.outputError) this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns));
this.out.write(clear(this.outputText, this.out.columns));
}
super.render();
this.outputError = ''; // Print prompt
this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), !this.done || !this.done && !this.placeholder ? color[this.color]().underline(this.rendered) : this.rendered].join(` `); // Print error
if (this.error) {
this.outputError += this.errorMsg.split(`\n`).reduce((a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``);
}
this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore);
}
}
number$1 = NumberPrompt;
return number$1;
}
var multiselect$1;
var hasRequiredMultiselect$1;
function requireMultiselect$1 () {
if (hasRequiredMultiselect$1) return multiselect$1;
hasRequiredMultiselect$1 = 1;
const color = require$$0;
const _require = require$$3,
cursor = _require.cursor;
const Prompt = requirePrompt$1();
const _require2 = requireUtil$1(),
clear = _require2.clear,
figures = _require2.figures,
style = _require2.style,
wrap = _require2.wrap,
entriesToDisplay = _require2.entriesToDisplay;
/**
* MultiselectPrompt Base Element
* @param {Object} opts Options
* @param {String} opts.message Message
* @param {Array} opts.choices Array of choice objects
* @param {String} [opts.hint] Hint to display
* @param {String} [opts.warn] Hint shown for disabled choices
* @param {Number} [opts.max] Max choices
* @param {Number} [opts.cursor=0] Cursor start position
* @param {Number} [opts.optionsPerPage=10] Max options to display at once
* @param {Stream} [opts.stdin] The Readable stream to listen to
* @param {Stream} [opts.stdout] The Writable stream to write readline data to
*/
class MultiselectPrompt extends Prompt {
constructor(opts = {}) {
super(opts);
this.msg = opts.message;
this.cursor = opts.cursor || 0;
this.scrollIndex = opts.cursor || 0;
this.hint = opts.hint || '';
this.warn = opts.warn || '- This option is disabled -';
this.minSelected = opts.min;
this.showMinError = false;
this.maxChoices = opts.max;
this.instructions = opts.instructions;
this.optionsPerPage = opts.optionsPerPage || 10;
this.value = opts.choices.map((ch, idx) => {
if (typeof ch === 'string') ch = {
title: ch,
value: idx
};
return {