xprogress 0.17.3 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js DELETED
@@ -1,1038 +0,0 @@
1
- "use strict";
2
-
3
- var _util = require("util");
4
-
5
- var _lodash = require("lodash");
6
-
7
- var _fs = require("fs");
8
-
9
- var _tty = _interopRequireDefault(require("tty"));
10
-
11
- var _events = _interopRequireDefault(require("events"));
12
-
13
- var _xbytes = _interopRequireDefault(require("xbytes"));
14
-
15
- var _stringd = _interopRequireDefault(require("stringd"));
16
-
17
- var _prettyMs = _interopRequireDefault(require("pretty-ms"));
18
-
19
- var _padRatio = _interopRequireDefault(require("pad-ratio"));
20
-
21
- var _stringdColors = _interopRequireDefault(require("stringd-colors"));
22
-
23
- var _speedometer = _interopRequireDefault(require("speedometer"));
24
-
25
- var _progressStream = _interopRequireDefault(require("progress-stream"));
26
-
27
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
28
-
29
- function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
30
-
31
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
32
-
33
- function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
34
-
35
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
36
-
37
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
38
-
39
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
40
-
41
- function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
42
-
43
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
44
-
45
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
46
-
47
- function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
48
-
49
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
50
-
51
- function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
52
-
53
- function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
54
-
55
- function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }
56
-
57
- function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
58
-
59
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
60
-
61
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
62
-
63
- 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); }
64
-
65
- 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; }
66
-
67
- function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
68
-
69
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
70
-
71
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
72
-
73
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
74
-
75
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
76
-
77
- var globOpts = {
78
- bar: {
79
- blank: '-',
80
- filler: '#',
81
- header: '',
82
- colorize: !0,
83
- separator: '',
84
- pulsateSkip: 15,
85
- pulsateLength: 15
86
- },
87
- label: 'Loading',
88
- clean: !1,
89
- // eslint-disable-next-line no-use-before-define
90
- length: 40,
91
- flipper: ['|', '/', '-', '\\'],
92
- pulsate: !1,
93
- template: '',
94
- variables: _objectSpread(_objectSpread({
95
- tag: function tag(_ref) {
96
- var _tag = _ref.tag;
97
- return _tag && typeof _tag !== 'function' ? "".concat(_tag, "\n") : '';
98
- }
99
- }, _stringdColors["default"].raw), {}, {
100
- 'color:bar:empty': ':{color:close}',
101
- 'color:bar:header': ':{color(green)}',
102
- 'color:bar:filled': ':{bgcolor(green)}:{color(black)}',
103
- 'color:bar:separator': ''
104
- }),
105
- forceFirst: !1
106
- };
107
-
108
- var defaultOptions = _objectSpread(_objectSpread({}, globOpts), {}, {
109
- template: ':{tag}[:{bar}] :{flipper} :{label} :3{percentage}% [:{completed}/:{total}]'
110
- });
111
-
112
- var streamOpts = _objectSpread(_objectSpread({}, globOpts), {}, {
113
- pulsate: false,
114
- progress: {
115
- time: 100,
116
- pulsate: false,
117
- infinite: !1,
118
- pulsateSkip: 15,
119
- pulsateLength: 15
120
- },
121
- template: [':{label}', ' |:{slot:bar}| [:3{slot:percentage}%] (:{slot:eta}) [:{speed}] [:{slot:size}/:{slot:size:total}]', ' [:{bar}] [:3{percentage}%] (:{eta}) [:{size}/:{size:total}]'],
122
- variables: _objectSpread(_objectSpread({}, globOpts.variables), {}, {
123
- eta: null,
124
- size: null,
125
- speed: null,
126
- progress: null,
127
- 'eta:raw': null,
128
- 'slot:bar': null,
129
- 'slot:blank': null,
130
- 'slot:eta': null,
131
- 'slot:eta:raw': null,
132
- 'slot:filler': null,
133
- 'slot:header': null,
134
- 'slot:size': null,
135
- 'slot:total': null,
136
- 'slot:runtime': null,
137
- 'slot:runtime:raw': null,
138
- 'slot:percentage': null,
139
- 'slot:size:total': null
140
- }),
141
- stageOpts: {}
142
- });
143
- /**
144
- * Get a persistent tty output stream
145
- * @returns {tty.WriteStream} The writable stream instance similar to `process.stdout`
146
- */
147
-
148
-
149
- function getPersistentStdout() {
150
- var self = getPersistentStdout;
151
- self.stdout = self.stdout && self.stdout.isTTY ? self.stdout : process.stdout.isTTY ? process.stdout : process.stderr.isTTY ? process.stderr : new _tty["default"].WriteStream((0, _fs.openSync)('/dev/tty', 'w'));
152
- return self.stdout;
153
- }
154
- /**
155
- * Get a current flipper
156
- * @param {Number} count Value that determines the flipper
157
- * @param {String|String[]} flippers String or (Array of strigs) of flippers
158
- */
159
-
160
-
161
- var flipper = function getFlipper() {
162
- function subflipper(count, flippers) {
163
- var manageInt = function manageInt(max, val) {
164
- return val > max ? manageInt(max, val - max) : val;
165
- };
166
-
167
- return flippers[manageInt(flippers.length, count) - 1];
168
- }
169
-
170
- return subflipper.count = 0, subflipper;
171
- }();
172
- /**
173
- * Parse a bar, returning a styled bar with a given percentage filled
174
- * @param {_defaultOptions} opts The options for the bar being parsed
175
- * @param {Number} fillable Maximum fillable slots
176
- * @param {Number} percentage Percentage filled
177
- * @param {Boolean} headers Whether or not to add headers to the bar
178
- */
179
-
180
-
181
- function parseBar(opts, fillable, percentage) {
182
- var headers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : !opts.pulsate;
183
- fillable = Math.round(fillable);
184
- var filled = Math.round(Math.min(100, percentage) / 100 * fillable);
185
- var empty = fillable - filled; // eslint-disable-next-line prefer-const
186
-
187
- var _opts$bar = opts.bar,
188
- filler = _opts$bar.filler,
189
- blank = _opts$bar.blank,
190
- header = _opts$bar.header;
191
-
192
- var _map = [filled, empty].map(Math.floor);
193
-
194
- var _map2 = _slicedToArray(_map, 2);
195
-
196
- filled = _map2[0];
197
- empty = _map2[1];
198
-
199
- var _map3 = [filler, blank].map(function (content) {
200
- return Array.isArray(content) || typeof content === 'string' ? content : '';
201
- });
202
-
203
- var _map4 = _slicedToArray(_map3, 2);
204
-
205
- filler = _map4[0];
206
- blank = _map4[1];
207
- return (0, _stringd["default"])([":{color:bar:filled}".concat(filler.repeat(filled)), ":{color:bar:header}".concat(headers ? header : ''), ":{color:bar:empty}".concat(blank.repeat(empty)), ''].join(':{color:close}:{bgcolor:close}'), opts.variables);
208
- }
209
-
210
- var xprettyMs = function (_) {
211
- return function (sec) {
212
- return Number.isFinite(sec) ? _(sec) : "\u221E";
213
- };
214
- }(_prettyMs["default"]);
215
- /**
216
- * Create a pulsate bar
217
- * @param {ProgressBar} bar The bar to be pulsated
218
- * @param {Array} slots Pulsate slots to be used
219
- * @param {number} skip Valuation for by how much to skip the bar
220
- * @param {string} sep The separator to be used on the bar
221
- */
222
-
223
-
224
- function pulsateBar(bar, slots, skip) {
225
- var sep = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
226
- if (slots[0].level + slots[1].level >= 100) slots[0].level = 100 - slots[1].level;
227
- var total = bar.length() - sep.length * 2;
228
- var stack = [].concat(_toConsumableArray(slots), [{
229
- level: 100 - (slots[0].level + slots[1].level),
230
- value: 0
231
- }]).map(function (_ref2) {
232
- var level = _ref2.level,
233
- value = _ref2.value;
234
- return {
235
- fillable: Math.round(level / 100 * total),
236
- percentage: value
237
- };
238
- });
239
- if (slots[0].level + slots[1].level === 100) slots[0].level = 0;else slots[0].level += skip;
240
- stack[stack.length - 1].fillable += total - Math.min(total, stack.reduce(function (max, _ref3) {
241
- var fillable = _ref3.fillable;
242
- return max + fillable;
243
- }, 0));
244
- return stack.map(function (_ref4) {
245
- var fillable = _ref4.fillable,
246
- percentage = _ref4.percentage;
247
- return parseBar(bar.opts, fillable, percentage, false);
248
- });
249
- }
250
-
251
- var ProgressGen = /*#__PURE__*/function (_EventEmitter) {
252
- _inherits(ProgressGen, _EventEmitter);
253
-
254
- var _super = _createSuper(ProgressGen);
255
-
256
- function ProgressGen() {
257
- _classCallCheck(this, ProgressGen);
258
-
259
- return _super.apply(this, arguments);
260
- }
261
-
262
- return ProgressGen;
263
- }(_events["default"]);
264
-
265
- var ProgressBar = /*#__PURE__*/function () {
266
- /**
267
- * Build a progress bar
268
- * @param {Number} total Max attainable value by the progressBar
269
- * @param {((size) => Number|Number[])|Number|Number[]} arr Allocation of slots by value
270
- * @param {_defaultOptions} opts Attachable options
271
- */
272
- function ProgressBar(total) {
273
- var arr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [total];
274
- var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
275
-
276
- _classCallCheck(this, ProgressBar);
277
-
278
- if (!(total && typeof total === 'number')) throw Error('<ProgressBar> must have a max integer value');
279
- if (typeof arr === 'function') arr = arr(total);
280
-
281
- if (_typeof(arr) === 'object' && !Array.isArray(arr)) {
282
- var _ref5 = [[total], arr];
283
- arr = _ref5[0];
284
- opts = _ref5[1];
285
- }
286
-
287
- this.opts = _objectSpread(_objectSpread(_objectSpread({}, defaultOptions), opts), {}, {
288
- bar: _objectSpread(_objectSpread({}, defaultOptions.bar), opts.bar),
289
- variables: _objectSpread(_objectSpread({}, defaultOptions.variables), opts.variables)
290
- });
291
- this.cores = {
292
- total: total,
293
- label: this.opts.label,
294
- append: [],
295
- length: this.opts.length,
296
- stdout: getPersistentStdout(),
297
- pulsateSlots: [[0, 0], [this.opts.bar.pulsateLength, 100]].map(function (_ref6) {
298
- var _ref7 = _slicedToArray(_ref6, 2),
299
- level = _ref7[0],
300
- value = _ref7[1];
301
-
302
- return {
303
- level: level,
304
- value: value
305
- };
306
- })
307
- };
308
- var self = this;
309
- this.slots = (0, _padRatio["default"])(arr, total, false).map(function (max) {
310
- return Object.defineProperties({
311
- max: max,
312
- done: 0
313
- }, {
314
- level: {
315
- get: function get() {
316
- return this.max / self.total() * 100;
317
- },
318
- configurable: true,
319
- enumerable: true
320
- },
321
- percentage: {
322
- get: function get() {
323
- return this.done / this.max * 100;
324
- },
325
- configurable: true,
326
- enumerable: true
327
- }
328
- });
329
- });
330
- delete this.opts.blot;
331
- delete this.opts.label;
332
- delete this.opts.append;
333
- delete this.opts.length;
334
- }
335
- /**
336
- * Label the progressbar while returning itself
337
- * @param {String} label The string label
338
- */
339
-
340
-
341
- _createClass(ProgressBar, [{
342
- key: "label",
343
- value: function label(_label) {
344
- return _label ? (this.cores.label = _label, this) : this.cores.label;
345
- }
346
- /**
347
- * Return or set the max length of the progressbar
348
- * @param {number} [value] The value to set the progressBar length to
349
- */
350
-
351
- }, {
352
- key: "length",
353
- value: function length(value) {
354
- var len = getPersistentStdout().columns;
355
- var core = this.cores.length;
356
-
357
- if (value && ['function', 'number'].includes(_typeof(value))) {
358
- this.cores.length = value;
359
- return this;
360
- }
361
-
362
- var ret;
363
- if (typeof core === 'function') ret = core(len);
364
- if (!ret && typeof core === 'number') ret = core < 0 ? len + core : Math.min(core, 100) / 100 * len;
365
- if (typeof ret !== 'number') throw new Error('length of the bar must be a valid number');
366
- return Math.floor(ret);
367
- }
368
- /**
369
- * Return or update the total level of the progressbar
370
- * @param {number} [value] The number to be added to the total level
371
- * @param {{}} [template] Template variable values to be included into core options
372
- */
373
-
374
- }, {
375
- key: "total",
376
- value: function total(value, template) {
377
- var _this = this;
378
-
379
- if (value && Number.isFinite(value)) {
380
- if (value < this.average().completed) throw new Error("<value> must not be lower than already completed value");
381
- this.slots.map(function (v, r) {
382
- return v.max = (r = v.max, v.max * value / _this.total()), v.done = v.done * v.max / r;
383
- });
384
- this.cores.total = Math.floor(value) ? value : 0;
385
- Object.assign(this.opts.template, template);
386
- return this;
387
- }
388
-
389
- return this.cores.total;
390
- }
391
- /**
392
- * Update the progressbar slots with certain percentages
393
- * - This will top up the current slots with the inputed values as opposed to `this.progress(levels)`
394
- * - The progressbar would be automatically drawn if [template] is provided
395
- * @param {Number|Number[]} levels Level(s) to update the slots with
396
- * @param {{}} [template] Template variable values to use on the drawn progress bar
397
- */
398
-
399
- }, {
400
- key: "tick",
401
- value: function tick(levels, template) {
402
- levels = typeof levels === 'number' ? Array(this.slots.length).fill(levels) : Array.isArray(levels) ? levels : Array(this.slots.length).fill(0);
403
- var res;
404
- return this.percentage(this.slots.map(function (slot, index) {
405
- return res = slot.percentage + Math.floor(levels[index]), res > 100 ? 100 : res;
406
- }), template);
407
- }
408
- /**
409
- * Update the progressbar slots with certain values
410
- * - This will top up the current slots with the inputed values as opposed to `this.progress(levels)`
411
- * - The progressbar would be automatically drawn if [template] is provided
412
- * @param {Number|Number[]} levels Level(s) to update the slots with
413
- * @param {{}} [template] Template variable values to use on the drawn progress bar
414
- */
415
-
416
- }, {
417
- key: "tickValue",
418
- value: function tickValue(levels, template) {
419
- levels = typeof levels === 'number' ? Array(this.slots.length).fill(levels) : Array.isArray(levels) ? levels : Array(this.slots.length).fill(0);
420
- return this.value(this.slots.map(function (slot, index) {
421
- return slot.done + Math.floor(levels[index]);
422
- }), template);
423
- }
424
- /**
425
- * Update the progressbar to a percentage
426
- * - The progressbar would be automatically drawn if [template] is provided
427
- * @param {number|number[]} index The index at which to replace percentage or an array of slot percentages
428
- * @param {number} [value] if (index::number) the percentage for the specified index
429
- * @param {{}} [template] Template variable values to use on the drawn progress bar
430
- * @example
431
- * > this.percentage(50, {}) // Update the entire bar to 50%
432
- * > this.percentage(1, 20, {}) // Set the percentage of the first slot to 20%
433
- * > this.percentage([40,20,70], {}) // Set the percentage of the slots according to array specification
434
- */
435
-
436
- }, {
437
- key: "percentage",
438
- value: function percentage(index, value, template) {
439
- if (this.isEnded) throw Error('This bar has been ended and is now immutable');
440
- var _ref8 = [function (input, msg) {
441
- if (!(Array.isArray(input) ? input : [input]).every(function (v) {
442
- return typeof v === 'number';
443
- })) throw new Error(msg);else return input;
444
- }, function (slots, val, i) {
445
- slots[i].done = parseType(val <= 0 || Math.floor(val) > 100 || val > 100 ? Math.floor(val) : val, "Percentage [".concat(val, "] must be in the range [0 < X < 100]")) / 100 * slots[i].max || slots[i].done;
446
- }],
447
- parseType = _ref8[0],
448
- inferParse = _ref8[1];
449
- var bars = [this].concat(_toConsumableArray(this.cores.append.reduce(function (a, v) {
450
- return v.inherit && a.push(v.bar), a;
451
- }, [])));
452
- if (arguments.length > 1 && value && _typeof(value) !== 'object') parseType([index, value <= 0 || Math.floor(value) > 100 || value > 100 ? Math.floor(value) : value], "<index> and <value> must be of type `number`, <number> must be in the range [0 < X < 100]"), bars.map(function (_ref9) {
453
- var slots = _ref9.slots;
454
- return slots[index].done = value / slots[index].max * 100 || slots[index].value;
455
- });else template = value, bars.map(function (_ref10) {
456
- var slots = _ref10.slots;
457
- return Array.isArray(index) ? index.map(function (val, i) {
458
- return inferParse(slots, val, i);
459
- }) : slots.map(function (_slot, i) {
460
- return inferParse(slots, index, i);
461
- });
462
- });
463
- return !template ? this : this.draw(template);
464
- }
465
- }, {
466
- key: "value",
467
- value: function value(index, _value, template) {
468
- function inferParse(slots, val, i) {
469
- if (val >= 0) {
470
- if (val <= slots[i].max) slots[i].done = val;else throw new Error("Slot index [".concat(i, "] is being updated with more than it can hold [").concat(val, " > ").concat(slots[i].max, "]"));
471
- } else throw new Error("Slot index [".concat(i, "] is being updated with [").concat(val, "] which is less than 0"));
472
- }
473
-
474
- var bars = [this].concat(_toConsumableArray(this.cores.append.reduce(function (a, v) {
475
- return v.inherit && a.push(v.bar), a;
476
- }, [])));
477
- if (arguments.length > 1 && _value && _typeof(_value) !== 'object') bars.map(function (_ref11) {
478
- var slots = _ref11.slots;
479
- return slots[index].done = _value || slots[index].done;
480
- });else template = _value, bars.map(function (_ref12) {
481
- var slots = _ref12.slots;
482
- return Array.isArray(index) ? index.map(function (val, i) {
483
- return inferParse(slots, val, i);
484
- }) : slots.map(function (_slot, i) {
485
- return inferParse(slots, index, i);
486
- });
487
- });
488
- return !template ? this : this.draw(template);
489
- }
490
- /**
491
- * Get an average round up of values in percentage and current progress compatred to the total
492
- * @param {Number} [fixedPoint] The fixed point at which to approximate average values to
493
- * @returns {{completed:number, remaining:number, percentage:number}}
494
- */
495
-
496
- }, {
497
- key: "average",
498
- value: function average(fixedPoint) {
499
- var completed = this.slots.reduce(function (a, b) {
500
- return a + b.done;
501
- }, 0);
502
- var percentage = completed / this.total() * 100;
503
- var remaining = this.total() - completed;
504
-
505
- var _map5 = [percentage, completed, remaining].map(function (value) {
506
- return fixedPoint ? parseFloat(value.toFixed(fixedPoint)) : value;
507
- });
508
-
509
- var _map6 = _slicedToArray(_map5, 3);
510
-
511
- percentage = _map6[0];
512
- completed = _map6[1];
513
- remaining = _map6[2];
514
- return {
515
- completed: completed,
516
- remaining: remaining,
517
- percentage: percentage
518
- };
519
- }
520
- /**
521
- * Draw the progressbar, apply template options to the template
522
- * @param {String|Object} [template] The template to use on the drawn progress bar or an array of predrawn progressbar from `this.constructBar` like `this.oldBar`
523
- */
524
-
525
- }, {
526
- key: "draw",
527
- value: function draw(template) {
528
- var result = Array.isArray(template) ? template : [].concat(_toConsumableArray(this.constructBar(template).split('\n')), _toConsumableArray(this.cores.append.map(function (block) {
529
- return block.bar.constructBar(block.inherit ? template : null);
530
- })));
531
- this.oldBar = result;
532
- this.print("bar".concat(result.length ? "+".concat(result.length - 1) : ''), result.join('\n'));
533
- this.hasBarredOnce = !0;
534
- return this;
535
- }
536
- }, {
537
- key: "constructBar",
538
- value: function constructBar(template) {
539
- var _this2 = this;
540
-
541
- var forcedFirst = [parseBar(this.opts, this.length() - this.opts.bar.header.length, this.average().percentage, this.opts.bar.header)];
542
- var bars = !this.opts.pulsate ? !this.opts.forceFirst ? function () {
543
- var total = Math.max(0, _this2.length() + [[_this2.opts.bar.header, 0], [_this2.opts.bar.separator, -1]].reduce(function (a, _ref13) {
544
- var _ref14 = _slicedToArray(_ref13, 2),
545
- v = _ref14[0],
546
- e = _ref14[1];
547
-
548
- return a - (v.length ? v.length * _this2.slots.length + e : 0);
549
- }, 0));
550
-
551
- var slotting = _this2.slots.map(function (_ref15) {
552
- var level = _ref15.level,
553
- percentage = _ref15.percentage;
554
- return {
555
- portion: Math.floor(level / 100 * total),
556
- percentage: percentage
557
- };
558
- });
559
-
560
- var slack = total - slotting.reduce(function (max, _ref16) {
561
- var portion = _ref16.portion;
562
- return max + portion;
563
- }, 0);
564
- slotting.slice(-1).pop().portion += slack;
565
- var result = slotting.map(function (_ref17) {
566
- var portion = _ref17.portion,
567
- percentage = _ref17.percentage;
568
- return parseBar(_this2.opts, portion, percentage);
569
- });
570
- return result;
571
- }() : forcedFirst : pulsateBar(this, this.cores.pulsateSlots, this.opts.bar.pulsateSkip, this.opts.bar.separator);
572
- var templateString = Array.isArray(this.opts.template) ? this.opts.template.join('\n') : this.opts.template;
573
- var average = this.average();
574
- return this.parseString(templateString, _objectSpread(_objectSpread({
575
- bar: bars.join(":{color:bar:separator}".concat(this.opts.bar.separator, ":{color:close}:{bgcolor:close}")),
576
- 'bar:complete': forcedFirst.join(''),
577
- label: this.label(),
578
- total: this.total(),
579
- flipper: flipper(flipper.count += 1, this.opts.flipper)
580
- }, average), {}, {
581
- percentage: average.percentage.toFixed(0)
582
- }, template));
583
- }
584
- }, {
585
- key: "parseString",
586
- value: function parseString(str, template) {
587
- var variables = _objectSpread({}, template = _objectSpread(_objectSpread({}, this.opts.variables), template));
588
-
589
- Object.entries(this.opts.variables).forEach(function (_ref18) {
590
- var _ref19 = _slicedToArray(_ref18, 2),
591
- spec = _ref19[0],
592
- content = _ref19[1];
593
-
594
- return typeof content === 'function' && content !== template[spec] && (template[spec] = content(template));
595
- });
596
- return (0, _stringd["default"])((0, _stringd["default"])(str, template), variables);
597
- }
598
- /**
599
- * Print a message after a bar `draw` interrupt
600
- * @param {'bar'|'end'} type Type of bar print or the first part of the printer
601
- * @param {any[]} content The contents to be formatted
602
- */
603
-
604
- }, {
605
- key: "print",
606
- value: function print(type) {
607
- var self = this;
608
- type = (0, _util.format)(type);
609
- if (!self.cores.stdout.isTTY) throw Error("Can't draw or print progressBar interrupts with piped output");
610
-
611
- var cleanWrite = function cleanWrite(arr, dontClean) {
612
- var addons = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
613
- var ending = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
614
-
615
- if (!dontClean) {
616
- self.cores.stdout.moveCursor(0, -addons);
617
- self.cores.stdout.cursorTo(0);
618
- self.cores.stdout.clearScreenDown();
619
- }
620
-
621
- self.cores.stdout.write("".concat(dontClean && ending && addons ? '\n' : '').concat(self.parseString(_util.format.apply(void 0, _toConsumableArray(arr))).replace(self.opts.bar.colorize ? '' : /\x1b\[\d+m/g, '')));
622
- };
623
-
624
- var addonPack;
625
- var addons = this.hasBarredOnce && !this.justLogged ? this.oldBar.length - 1 : 0;
626
-
627
- for (var _len = arguments.length, content = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
628
- content[_key - 1] = arguments[_key];
629
- }
630
-
631
- this.justLogged = type === 'bar' && content.length === 1 ? !!cleanWrite(content, this.justLogged, addons) : (addonPack = type.match(/^bar\+(\d+)/)) !== null ? !!cleanWrite(content, this.justLogged, this.hasBarredOnce ? addonPack[1] : addons) : type === 'end' ? !!cleanWrite(content, !this.opts.clean, addons, true) : !cleanWrite([type.startsWith(':') && "".concat(type.slice(1)) || type].concat(content, ['\n']), this.justLogged, addons);
632
- if (this.justLogged && this.hasBarredOnce) this.draw(this.oldBar);
633
- return this;
634
- }
635
- /**
636
- * End the bar irrespective of progress, optionally with a message.
637
- * @param {any[]} [message] The message to be printed to `stdout` right before ending the bar
638
- */
639
-
640
- }, {
641
- key: "end",
642
- value: function end() {
643
- if (!this.isEnded) {
644
- for (var _len2 = arguments.length, message = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
645
- message[_key2] = arguments[_key2];
646
- }
647
-
648
- if (message.length) this.print.apply(this, ['end'].concat(message));
649
- this.isEnded = !0;
650
- }
651
-
652
- return this;
653
- }
654
- /**
655
- * Drain all slots in the progressbar to 0
656
- */
657
-
658
- }, {
659
- key: "drain",
660
- value: function drain(slotID) {
661
- if (slotID) this.slots[slotID].done = 0;else this.slots.map(function (slot) {
662
- return slot.done = 0, slot;
663
- });
664
- return this;
665
- }
666
- /**
667
- * Drop the chain, return void
668
- */
669
- // eslint-disable-next-line class-methods-use-this
670
-
671
- }, {
672
- key: "drop",
673
- value: function drop() {}
674
- /**
675
- * Append the specified bar after `this`
676
- * @param {ProgressBar} bar The bar to be appended
677
- * @param {Boolean} inherit Whether or not to inherit bar templates from `this`
678
- */
679
-
680
- }, {
681
- key: "append",
682
- value: function append(bar) {
683
- var inherit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : !1;
684
- if (!ProgressBar.isBar(bar) && !bar.opts.template) throw Error('The Parameter <bar> is not a progressbar or a hanger');
685
- this.cores.append.push({
686
- bar: bar,
687
- inherit: inherit
688
- });
689
- bar.cores.isKid = !0;
690
- return this;
691
- }
692
- /**
693
- * Check if the bar or a slot is complete
694
- * @param {Number} [slot] The slot to be checked for completion
695
- */
696
-
697
- }, {
698
- key: "isComplete",
699
- value: function isComplete(slot) {
700
- if (slot && !this.slots[slot]) throw Error("Value in <slot>:".concat(slot, " has no slot reference"));
701
- return slot ? this.slots[slot].max === this.slots[slot].done : this.average().remaining === 0;
702
- }
703
- /**
704
- * Find out the progressbar is appended to another
705
- */
706
-
707
- }, {
708
- key: "slotStreamify",
709
-
710
- /**
711
- * Prepare a raw generator for use
712
- * @param {(slots:Number, total?:Number) => String} actor The performing function
713
- * @returns {Generator} New ProgressBar Generator
714
- * @yields The through instance or a cache model of the ProgressBar
715
- */
716
- value: function* slotStreamify(actor, args) {
717
- for (var level = -1; (level += 1) <= (this.opts.progress.infinite ? Infinity : this.slots.length);) {
718
- args = yield !level ? this : ((0, _lodash.merge)(this.opts, args[1]), actor(Math.floor(level - 1), args[0], this.opts.progress.infinite));
719
- }
720
- }
721
- }, {
722
- key: "isChild",
723
- get: function get() {
724
- return !!this.cores.isKid;
725
- }
726
- /**
727
- * Check if the progressbar is active.
728
- * - Activity is determined when the progressbar is not complete
729
- */
730
-
731
- }, {
732
- key: "isActive",
733
- get: function get() {
734
- return !this.isComplete();
735
- }
736
- /**
737
- * Check if the bar is fresh.
738
- * - Equivalent of `this.isActive && !this.average().value`
739
- */
740
-
741
- }, {
742
- key: "isFresh",
743
- get: function get() {
744
- return this.isActive && !this.average().completed;
745
- }
746
- /**
747
- * Check if the provided progressbar is an instance of `this`
748
- * @param {ProgressBar} bar The progressbar to be checked
749
- */
750
-
751
- }], [{
752
- key: "isBar",
753
- value: function isBar(bar) {
754
- return bar instanceof ProgressBar;
755
- }
756
- /**
757
- * Check if the provided progressbar is an stream instance of `this`
758
- * @param {ProgressBar} bar The progressbar to be checked
759
- */
760
-
761
- }, {
762
- key: "isBarStream",
763
- value: function isBarStream(barStream) {
764
- return !!barStream && ProgressBar.isBar(barStream.bar) && barStream instanceof _events["default"] && [barStream.read, barStream.write].every(function (slot) {
765
- return typeof slot === 'function';
766
- });
767
- }
768
- /**
769
- * Check if the provided object is a stream progressbar generator
770
- * @param {any} bar The progressbar to be checked
771
- */
772
-
773
- }, {
774
- key: "isBarGen",
775
- value: function isBarGen(barStream) {
776
- return !!barStream && ProgressBar.isBar(barStream.bar) && barStream instanceof _events["default"] && typeof barStream.next === 'function';
777
- }
778
- /**
779
- * Check if the provided object is related to any instances created by this script
780
- * @param {any} bar The progressbar to be checked
781
- */
782
-
783
- }, {
784
- key: "isBarRelated",
785
- value: function isBarRelated(barStream) {
786
- return ProgressBar.isBar(barStream) || ProgressBar.isBarStream(barStream) || ProgressBar.isBarGen(barStream);
787
- }
788
- /**
789
- * Calculate slot levels by number of slots
790
- * @param {number} len Each slot length, inferrable if ratio doesn't make 100 or pop-able if over 100
791
- */
792
-
793
- }, {
794
- key: "slotsByCount",
795
- value: function slotsByCount(len) {
796
- return function (size) {
797
- return (0, _padRatio["default"])(Array(len).fill(size / len), size, false);
798
- };
799
- }
800
- /**
801
- * Calculate slot levels by size
802
- * @param {number} size Maximum possible total size
803
- * @param {number[]} percentages Each slot length, inferrable if ratio doesn't make 100 or pop-able if over 100
804
- */
805
-
806
- }, {
807
- key: "slotsByPercentage",
808
- value: function slotsByPercentage(percentages) {
809
- return function (size) {
810
- return (0, _padRatio["default"])(percentages.map(function (_size) {
811
- return _size / 100 * size;
812
- }), size);
813
- };
814
- }
815
- /**
816
- * Create a streamified bar for use with generators
817
- * @param {Number} total Total attainable value of bytes in <N>
818
- * @param {Number|Number[]} slots Number of slots in <%>
819
- * @param {_streamOpts} [opts] Options for the bar
820
- * @param {(bar:ProgressBar,slotLevel:Number,template:{}) => void} [actor] The actor for every yield
821
- */
822
-
823
- }, {
824
- key: "stream",
825
- value: function stream(total, slots, opts, actor) {
826
- // if (typeof slots === 'function') [slots, opts, actor] = [, {}, slots];
827
- if (typeof opts === 'function') {
828
- var _ref20 = [{}, opts];
829
- opts = _ref20[0];
830
- actor = _ref20[1];
831
- }
832
-
833
- if (_typeof(slots) === 'object' & !Array.isArray(slots)) {
834
- var _ref21 = [, slots];
835
- slots = _ref21[0];
836
- opts = _ref21[1];
837
- }
838
-
839
- opts = _objectSpread(_objectSpread(_objectSpread({}, total === Infinity ? {
840
- pulsate: !0,
841
- template: ':{tag}[:{bar}] [:{flipper}] :{label} (:{slot:runtime}) :{slot:size}'
842
- } : {}), opts), slots === Infinity ? (slots = total, {
843
- progress: {
844
- infinite: !0
845
- }
846
- }) : {});
847
- var progressBar = new ProgressBar(total, slots, opts);
848
- return ProgressBar.streamify(progressBar, actor, opts);
849
- }
850
- /**
851
- * Streamify a bar for use with generators
852
- * @param {ProgressBar} bar The bar to be used
853
- * @param {(bar:ProgressBar, slotLevel:Number, template:() => {completed:number, remaining:number, percentage:number}) => void} [actor] The actor for every yield
854
- * @param {_streamOpts} [opts] Options for the bar
855
- * @returns {{next(size: Number, opts: _streamOpts):NodeJS.WritableStream, bar:ProgressBar}} Returned function from `ProgressBar.streamify`
856
- */
857
-
858
- }, {
859
- key: "streamify",
860
- value: function streamify(bar, actor, opts) {
861
- if (_typeof(actor) === 'object') {
862
- var _ref22 = [, actor];
863
- actor = _ref22[0];
864
- opts = _ref22[1];
865
- }
866
-
867
- bar.opts = (0, _lodash.merge)({}, bar.opts, streamOpts, opts);
868
- bar.opts.template = opts.template || streamOpts.template;
869
- var _ref23 = [[[0, 0], [bar.opts.progress.pulsateLength || bar.opts.bar.pulsateLength, 100]].map(function (_ref24) {
870
- var _ref25 = _slicedToArray(_ref24, 2),
871
- level = _ref25[0],
872
- value = _ref25[1];
873
-
874
- return {
875
- level: level,
876
- value: value
877
- };
878
- }), bar.opts.progress.pulsateSkip || bar.opts.bar.pulsateSkip],
879
- pulsateSlots = _ref23[0],
880
- pulsateSkips = _ref23[1];
881
-
882
- var _defaultUnit;
883
-
884
- var progressGen = new ProgressGen();
885
-
886
- var buildBytesWith = function buildBytesWith(bytes) {
887
- var byteOpts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
888
- return function (props, data) {
889
- return _xbytes["default"].createRelativeSizer(data && (data.args[0] || data.matched.unit) || _defaultUnit, {
890
- iec: data && 'iec' in data.matched ? data.matched.iec === 'true' : byteOpts.iec || !1,
891
- bits: data && 'bits' in data.matched ? data.matched.bits === 'true' : byteOpts.bits || !1,
892
- fixed: data && 'fixed' in data.matched ? parseInt(data.matched.fixed, 10) : byteOpts.fixed || 2,
893
- "short": data && 'short' in data.matched ? data.matched["short"] === 'true' : byteOpts["short"] || !0,
894
- space: data && 'space' in data.matched ? data.matched.space === 'true' : byteOpts.space || !0,
895
- sticky: data && 'sticky' in data.matched ? data.matched.sticky === 'true' : byteOpts.sticky || !1
896
- })(typeof bytes === 'function' ? bytes(props) : bytes);
897
- };
898
- };
899
-
900
- var buildSpeedWith = function buildSpeedWith(speed) {
901
- return function (_, data) {
902
- return "".concat(buildBytesWith(speed, {
903
- iec: !1,
904
- bits: !0,
905
- fixed: 2,
906
- "short": !0,
907
- space: !1,
908
- sticky: !1
909
- })(_, data)).concat(data && data.matched.metric || 'ps');
910
- };
911
- };
912
-
913
- var totalSpeed = (0, _speedometer["default"])(5000);
914
- var streamGenerator = bar.slotStreamify(function (slotIndex, total, infinite) {
915
- var max = !infinite ? Math.round(bar.slots[slotIndex].level / 100 * bar.total()) : Infinity;
916
- total = typeof total === 'function' ? total(bar) : total || max;
917
- if (!infinite && total > max) throw Error("<size> slot must not be greater than maximum possible size for the slot [".concat(max, "], consider using infinite slots"));
918
- var through = (0, _progressStream["default"])(_objectSpread({
919
- length: total
920
- }, bar.opts.progress)).on('progress', function (progress) {
921
- var speed = totalSpeed(progress.delta);
922
-
923
- if (bar.isEnded) {
924
- through.emit('error', Error('The <bar> being used has been ended'));
925
- return;
926
- }
927
-
928
- (actor || function (_bar, args, template) {
929
- return _bar.value.apply(_bar, _toConsumableArray(args)).draw(template);
930
- })(bar, bar.opts.progress.infinite ? [progress.delta + bar.average().completed] : [slotIndex, progress.transferred], {
931
- eta: function eta() {
932
- return xprettyMs(1000 * bar.average().remaining / speed);
933
- },
934
- size: buildBytesWith(function () {
935
- return bar.average().completed;
936
- }),
937
- speed: buildSpeedWith(speed),
938
- 'speed:raw': speed,
939
- 'slot:speed': buildSpeedWith(progress.speed),
940
- 'slot:speed:raw': progress.speed,
941
- progress: progress,
942
- 'eta:raw': function etaRaw() {
943
- return Math.round(bar.average().remaining / speed);
944
- },
945
- 'slot:bar': function slotBar() {
946
- return bar.opts.progress.pulsate ? pulsateBar(bar, pulsateSlots, pulsateSkips, bar.opts.bar.separator).join('') : function () {
947
- var header = bar.opts.bar['slot:header'] || bar.opts.bar.header;
948
- var filler = bar.opts.bar['slot:filler'] || bar.opts.bar.filler;
949
- var blank = bar.opts.bar['slot:blank'] || bar.opts.bar.blank;
950
- return parseBar((0, _lodash.merge)({}, bar.opts, {
951
- bar: {
952
- header: header,
953
- filler: filler,
954
- blank: blank
955
- }
956
- }), bar.length() - (header || '').length, progress.percentage);
957
- }();
958
- },
959
- 'slot:eta': xprettyMs(1000 * progress.eta),
960
- 'slot:eta:raw': progress.eta,
961
- 'slot:size': buildBytesWith(progress.transferred),
962
- 'slot:size:raw': progress.transferred,
963
- 'size:total': buildBytesWith(function () {
964
- return bar.total();
965
- }),
966
- 'slot:runtime': xprettyMs(1000 * progress.runtime),
967
- 'slot:runtime:raw': progress.runtime,
968
- 'slot:percentage': progress.percentage.toFixed(0),
969
- 'slot:size:total': buildBytesWith(progress.length),
970
- 'slot:size:total:raw': progress.length
971
- });
972
- [through, progressGen].map(function (emitter) {
973
- return emitter.emit('tick', {
974
- progress: progress,
975
- bar: bar
976
- });
977
- });
978
- }).on('end', function () {
979
- return bar.isComplete() ? progressGen.emit('complete', bar) : null, progressGen.emit('end', bar);
980
- }).once('error', function (error) {
981
- return bar.end(":{color(red)}[Bar Error]:{color:close} An Error occurred\n".concat(error));
982
- }); // through.emit = (tr => (...args) => (bar.print('tr>', args[0]), tr.call(through, ...args)))(through.emit)
983
-
984
- return through.bar = bar, through;
985
- });
986
- return Object.assign(progressGen, {
987
- /**
988
- * Get the next PassThrough instance
989
- * @param {number} [size] Size for the next chunk (Omittable)
990
- * @param {_streamOpts} [options] Bar options
991
- * @returns {NodeJS.WritableStream} Returned function from `ProgressBar.streamify`
992
- */
993
- next: function next(size, options) {
994
- return streamGenerator.next(_toConsumableArray(typeof size === 'number' ? [size, options] : [, size])).value;
995
- },
996
-
997
- /**
998
- * End the bar irrespective of progress, optionally with a message.
999
- * @param {any[]} [message] The message to be printed to `stdout` right before ending the bar
1000
- * @returns {ProgressBar} The ProgressBar
1001
- */
1002
- end: function end() {
1003
- return bar.end.apply(bar, arguments);
1004
- },
1005
-
1006
- /**
1007
- * Print a message after a bar `draw` interrupt
1008
- * @param {any[]} message The message to printed
1009
- * @returns {ProgressBar} The ProgressBar
1010
- */
1011
- print: function print() {
1012
- return bar.print.apply(bar, arguments);
1013
- },
1014
-
1015
- /**
1016
- * Set the default unit
1017
- * @param {xbytes.AllUnitStacks} unit Preferred unit representation
1018
- * @returns {ProgressBar} The ProgressBar
1019
- */
1020
- defaultUnit: function defaultUnit(unit) {
1021
- if (!_xbytes["default"].isUnit(unit)) throw new Error("Invalid ByteString unit: ".concat(unit));
1022
- _defaultUnit = unit;
1023
- return this;
1024
- },
1025
-
1026
- /**
1027
- * The ProgressBar Instance
1028
- * @type {ProgressBar} The ProgresBar
1029
- */
1030
- bar: streamGenerator.next().value
1031
- });
1032
- }
1033
- }]);
1034
-
1035
- return ProgressBar;
1036
- }();
1037
-
1038
- module.exports = ProgressBar;