UNPKG

@controlplane/cli

Version:

Control Plane Corporation CLI

91 lines 3.25 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ProgressBar = void 0; const helpers_1 = require("./helpers"); const cli_progress_1 = require("cli-progress"); class ProgressBar { constructor() { this.isActive = false; this.progressBar = new cli_progress_1.SingleBar({ format: '{bar} {percentage}% {speed}| {displayValue}/{displayTotal} {unit}', }, cli_progress_1.Presets.shades_grey); this.progressInterval = undefined; this.speed = ''; this.startTime = 0; this.lastUpdateTime = 0; this.lastValue = 0; this.totalReadableSize = { value: '', unit: 'Bytes' }; this.totalSize = 0; this.value = 0; this.valueReadableSize = { value: '', unit: 'Bytes' }; } // Public Methods // isComplete() { return this.value / this.totalSize === 1; } start(totalSize) { this.totalSize = totalSize; this.totalReadableSize = (0, helpers_1.humanReadableSize)(this.totalSize); this.progressBar.start(this.totalSize, 0, this.payload); this.isActive = true; // Start time for progress this.startTime = Date.now(); // Initialize last update parameters for instantaneous speed calculation this.lastUpdateTime = this.startTime; this.lastValue = 0; // Calculate the instantaneous speed in MB/s (using SI: 1 MB = 1,000,000 bytes) this.progressInterval = setInterval(() => { const now = Date.now(); const diffTimeSec = (now - this.lastUpdateTime) / 1000; const diffBytes = this.value - this.lastValue; let speedInMbPerSecond = 0; // Avoid dividing by zero if (diffTimeSec > 0) { speedInMbPerSecond = diffBytes / diffTimeSec / 1000000; } // Update the tracking values for the next interval this.lastUpdateTime = now; this.lastValue = this.value; this.speed = `| Speed: ${speedInMbPerSecond.toFixed(2)} MB/s `; this.render(); }, 1000); } stop() { if (!this.isActive) { return; } this.isActive = false; this.progressBar.stop(); clearInterval(this.progressInterval); } update(bytes) { this.value += bytes; // Skip updating progress bar if it hasn't started if (!this.isActive) { return; } // Update value readable size for display this.valueReadableSize = (0, helpers_1.humanReadableSize)(this.value); // Update the progress bar this.render(); // Stop if upload has completed if (this.value >= this.totalSize) { this.stop(); } } // Private Methods // render() { this.progressBar.update(this.value, this.payload); } // - Getters get payload() { return { speed: this.speed, displayValue: this.valueReadableSize.value, displayTotal: this.totalReadableSize.value, unit: this.totalReadableSize.unit, }; } } exports.ProgressBar = ProgressBar; //# sourceMappingURL=progress-bar.js.map