index.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. 'use strict';
  2. const readline = require('readline');
  3. const chalk = require('chalk');
  4. const cliCursor = require('cli-cursor');
  5. const cliSpinners = require('cli-spinners');
  6. const logSymbols = require('log-symbols');
  7. const stripAnsi = require('strip-ansi');
  8. const wcwidth = require('wcwidth');
  9. const isInteractive = require('is-interactive');
  10. const MuteStream = require('mute-stream');
  11. const TEXT = Symbol('text');
  12. const PREFIX_TEXT = Symbol('prefixText');
  13. const ASCII_ETX_CODE = 0x03; // Ctrl+C emits this code
  14. class StdinDiscarder {
  15. constructor() {
  16. this.requests = 0;
  17. this.mutedStream = new MuteStream();
  18. this.mutedStream.pipe(process.stdout);
  19. this.mutedStream.mute();
  20. const self = this;
  21. this.ourEmit = function (event, data, ...args) {
  22. const {stdin} = process;
  23. if (self.requests > 0 || stdin.emit === self.ourEmit) {
  24. if (event === 'keypress') { // Fixes readline behavior
  25. return;
  26. }
  27. if (event === 'data' && data.includes(ASCII_ETX_CODE)) {
  28. process.emit('SIGINT');
  29. }
  30. Reflect.apply(self.oldEmit, this, [event, data, ...args]);
  31. } else {
  32. Reflect.apply(process.stdin.emit, this, [event, data, ...args]);
  33. }
  34. };
  35. }
  36. start() {
  37. this.requests++;
  38. if (this.requests === 1) {
  39. this.realStart();
  40. }
  41. }
  42. stop() {
  43. if (this.requests <= 0) {
  44. throw new Error('`stop` called more times than `start`');
  45. }
  46. this.requests--;
  47. if (this.requests === 0) {
  48. this.realStop();
  49. }
  50. }
  51. realStart() {
  52. // No known way to make it work reliably on Windows
  53. if (process.platform === 'win32') {
  54. return;
  55. }
  56. this.rl = readline.createInterface({
  57. input: process.stdin,
  58. output: this.mutedStream
  59. });
  60. this.rl.on('SIGINT', () => {
  61. if (process.listenerCount('SIGINT') === 0) {
  62. process.emit('SIGINT');
  63. } else {
  64. this.rl.close();
  65. process.kill(process.pid, 'SIGINT');
  66. }
  67. });
  68. }
  69. realStop() {
  70. if (process.platform === 'win32') {
  71. return;
  72. }
  73. this.rl.close();
  74. this.rl = undefined;
  75. }
  76. }
  77. let stdinDiscarder;
  78. class Ora {
  79. constructor(options) {
  80. if (!stdinDiscarder) {
  81. stdinDiscarder = new StdinDiscarder();
  82. }
  83. if (typeof options === 'string') {
  84. options = {
  85. text: options
  86. };
  87. }
  88. this.options = {
  89. text: '',
  90. color: 'cyan',
  91. stream: process.stderr,
  92. discardStdin: true,
  93. ...options
  94. };
  95. this.spinner = this.options.spinner;
  96. this.color = this.options.color;
  97. this.hideCursor = this.options.hideCursor !== false;
  98. this.interval = this.options.interval || this.spinner.interval || 100;
  99. this.stream = this.options.stream;
  100. this.id = undefined;
  101. this.isEnabled = typeof this.options.isEnabled === 'boolean' ? this.options.isEnabled : isInteractive({stream: this.stream});
  102. this.isSilent = typeof this.options.isSilent === 'boolean' ? this.options.isSilent : false;
  103. // Set *after* `this.stream`
  104. this.text = this.options.text;
  105. this.prefixText = this.options.prefixText;
  106. this.linesToClear = 0;
  107. this.indent = this.options.indent;
  108. this.discardStdin = this.options.discardStdin;
  109. this.isDiscardingStdin = false;
  110. }
  111. get indent() {
  112. return this._indent;
  113. }
  114. set indent(indent = 0) {
  115. if (!(indent >= 0 && Number.isInteger(indent))) {
  116. throw new Error('The `indent` option must be an integer from 0 and up');
  117. }
  118. this._indent = indent;
  119. }
  120. _updateInterval(interval) {
  121. if (interval !== undefined) {
  122. this.interval = interval;
  123. }
  124. }
  125. get spinner() {
  126. return this._spinner;
  127. }
  128. set spinner(spinner) {
  129. this.frameIndex = 0;
  130. if (typeof spinner === 'object') {
  131. if (spinner.frames === undefined) {
  132. throw new Error('The given spinner must have a `frames` property');
  133. }
  134. this._spinner = spinner;
  135. } else if (process.platform === 'win32') {
  136. this._spinner = cliSpinners.line;
  137. } else if (spinner === undefined) {
  138. // Set default spinner
  139. this._spinner = cliSpinners.dots;
  140. } else if (cliSpinners[spinner]) {
  141. this._spinner = cliSpinners[spinner];
  142. } else {
  143. throw new Error(`There is no built-in spinner named '${spinner}'. See https://github.com/sindresorhus/cli-spinners/blob/master/spinners.json for a full list.`);
  144. }
  145. this._updateInterval(this._spinner.interval);
  146. }
  147. get text() {
  148. return this[TEXT];
  149. }
  150. get prefixText() {
  151. return this[PREFIX_TEXT];
  152. }
  153. get isSpinning() {
  154. return this.id !== undefined;
  155. }
  156. getFullPrefixText(prefixText = this[PREFIX_TEXT], postfix = ' ') {
  157. if (typeof prefixText === 'string') {
  158. return prefixText + postfix;
  159. }
  160. if (typeof prefixText === 'function') {
  161. return prefixText() + postfix;
  162. }
  163. return '';
  164. }
  165. updateLineCount() {
  166. const columns = this.stream.columns || 80;
  167. const fullPrefixText = this.getFullPrefixText(this.prefixText, '-');
  168. this.lineCount = stripAnsi(fullPrefixText + '--' + this[TEXT]).split('\n').reduce((count, line) => {
  169. return count + Math.max(1, Math.ceil(wcwidth(line) / columns));
  170. }, 0);
  171. }
  172. set text(value) {
  173. this[TEXT] = value;
  174. this.updateLineCount();
  175. }
  176. set prefixText(value) {
  177. this[PREFIX_TEXT] = value;
  178. this.updateLineCount();
  179. }
  180. get isEnabled() {
  181. return this._isEnabled && !this.isSilent;
  182. }
  183. set isEnabled(value) {
  184. if (typeof value !== 'boolean') {
  185. throw new TypeError('The `isEnabled` option must be a boolean');
  186. }
  187. this._isEnabled = value;
  188. }
  189. get isSilent() {
  190. return this._isSilent;
  191. }
  192. set isSilent(value) {
  193. if (typeof value !== 'boolean') {
  194. throw new TypeError('The `isSilent` option must be a boolean');
  195. }
  196. this._isSilent = value;
  197. }
  198. frame() {
  199. const {frames} = this.spinner;
  200. let frame = frames[this.frameIndex];
  201. if (this.color) {
  202. frame = chalk[this.color](frame);
  203. }
  204. this.frameIndex = ++this.frameIndex % frames.length;
  205. const fullPrefixText = (typeof this.prefixText === 'string' && this.prefixText !== '') ? this.prefixText + ' ' : '';
  206. const fullText = typeof this.text === 'string' ? ' ' + this.text : '';
  207. return fullPrefixText + frame + fullText;
  208. }
  209. clear() {
  210. if (!this.isEnabled || !this.stream.isTTY) {
  211. return this;
  212. }
  213. for (let i = 0; i < this.linesToClear; i++) {
  214. if (i > 0) {
  215. this.stream.moveCursor(0, -1);
  216. }
  217. this.stream.clearLine();
  218. this.stream.cursorTo(this.indent);
  219. }
  220. this.linesToClear = 0;
  221. return this;
  222. }
  223. render() {
  224. if (this.isSilent) {
  225. return this;
  226. }
  227. this.clear();
  228. this.stream.write(this.frame());
  229. this.linesToClear = this.lineCount;
  230. return this;
  231. }
  232. start(text) {
  233. if (text) {
  234. this.text = text;
  235. }
  236. if (this.isSilent) {
  237. return this;
  238. }
  239. if (!this.isEnabled) {
  240. if (this.text) {
  241. this.stream.write(`- ${this.text}\n`);
  242. }
  243. return this;
  244. }
  245. if (this.isSpinning) {
  246. return this;
  247. }
  248. if (this.hideCursor) {
  249. cliCursor.hide(this.stream);
  250. }
  251. if (this.discardStdin && process.stdin.isTTY) {
  252. this.isDiscardingStdin = true;
  253. stdinDiscarder.start();
  254. }
  255. this.render();
  256. this.id = setInterval(this.render.bind(this), this.interval);
  257. return this;
  258. }
  259. stop() {
  260. if (!this.isEnabled) {
  261. return this;
  262. }
  263. clearInterval(this.id);
  264. this.id = undefined;
  265. this.frameIndex = 0;
  266. this.clear();
  267. if (this.hideCursor) {
  268. cliCursor.show(this.stream);
  269. }
  270. if (this.discardStdin && process.stdin.isTTY && this.isDiscardingStdin) {
  271. stdinDiscarder.stop();
  272. this.isDiscardingStdin = false;
  273. }
  274. return this;
  275. }
  276. succeed(text) {
  277. return this.stopAndPersist({symbol: logSymbols.success, text});
  278. }
  279. fail(text) {
  280. return this.stopAndPersist({symbol: logSymbols.error, text});
  281. }
  282. warn(text) {
  283. return this.stopAndPersist({symbol: logSymbols.warning, text});
  284. }
  285. info(text) {
  286. return this.stopAndPersist({symbol: logSymbols.info, text});
  287. }
  288. stopAndPersist(options = {}) {
  289. if (this.isSilent) {
  290. return this;
  291. }
  292. const prefixText = options.prefixText || this.prefixText;
  293. const text = options.text || this.text;
  294. const fullText = (typeof text === 'string') ? ' ' + text : '';
  295. this.stop();
  296. this.stream.write(`${this.getFullPrefixText(prefixText, ' ')}${options.symbol || ' '}${fullText}\n`);
  297. return this;
  298. }
  299. }
  300. const oraFactory = function (options) {
  301. return new Ora(options);
  302. };
  303. module.exports = oraFactory;
  304. module.exports.promise = (action, options) => {
  305. // eslint-disable-next-line promise/prefer-await-to-then
  306. if (typeof action.then !== 'function') {
  307. throw new TypeError('Parameter `action` must be a Promise');
  308. }
  309. const spinner = new Ora(options);
  310. spinner.start();
  311. (async () => {
  312. try {
  313. await action;
  314. spinner.succeed();
  315. } catch (_) {
  316. spinner.fail();
  317. }
  318. })();
  319. return spinner;
  320. };