diff --git a/lib/commands/init.js b/lib/commands/init.js index 1847e19a9560f..f42a613a2ca71 100644 --- a/lib/commands/init.js +++ b/lib/commands/init.js @@ -6,7 +6,7 @@ const npa = require('npm-package-arg') const libexec = require('libnpmexec') const mapWorkspaces = require('@npmcli/map-workspaces') const PackageJson = require('@npmcli/package-json') -const { log, output } = require('proc-log') +const { log, output, input } = require('proc-log') const updateWorkspaces = require('../utils/update-workspaces.js') const BaseCommand = require('../base-cmd.js') @@ -148,8 +148,6 @@ class Init extends BaseCommand { } async template (path = process.cwd()) { - log.pause() - const initFile = this.npm.config.get('init-module') if (!this.npm.config.get('yes') && !this.npm.config.get('force')) { output.standard([ @@ -167,7 +165,8 @@ class Init extends BaseCommand { } try { - const data = await initJson(path, initFile, this.npm.config) + const data = await input.start(() => initJson(path, initFile, this.npm.config)) + .finally(() => output.standard('')) log.silly('package data', data) return data } catch (er) { @@ -176,8 +175,6 @@ class Init extends BaseCommand { } else { throw er } - } finally { - log.resume() } } diff --git a/lib/utils/display.js b/lib/utils/display.js index 299edc797aaf3..f69c6baba5c95 100644 --- a/lib/utils/display.js +++ b/lib/utils/display.js @@ -1,5 +1,5 @@ const proggy = require('proggy') -const { log, output, META } = require('proc-log') +const { log, output, input, META } = require('proc-log') const { explain } = require('./explain-eresolve.js') const { formatWithOptions } = require('./format') @@ -137,6 +137,9 @@ class Display { // Handlers are set immediately so they can buffer all events process.on('log', this.#logHandler) process.on('output', this.#outputHandler) + process.on('input', this.#inputHandler) + + this.#progress = new Progress({ stream: stderr }) } off () { @@ -146,9 +149,9 @@ class Display { process.off('output', this.#outputHandler) this.#outputState.buffer.length = 0 - if (this.#progress) { - this.#progress.stop() - } + process.off('input', this.#inputHandler) + + this.#progress.off() } get chalk () { @@ -171,6 +174,7 @@ class Display { unicode, }) { this.#command = command + // get createSupportsColor from chalk directly if this lands // https://github.com/chalk/chalk/pull/600 const [{ Chalk }, { createSupportsColor }] = await Promise.all([ @@ -201,18 +205,18 @@ class Display { // Emit resume event on the logs which will flush output log.resume() output.flush() - this.#startProgress({ progress, unicode }) + this.#progress.load({ + unicode, + enabled: !!progress && !this.#silent, + }) } // STREAM WRITES // Write formatted and (non-)colorized output to streams - #stdoutWrite (options, ...args) { - this.#stdout.write(formatWithOptions({ colors: this.#stdoutColor, ...options }, ...args)) - } - - #stderrWrite (options, ...args) { - this.#stderr.write(formatWithOptions({ colors: this.#stderrColor, ...options }, ...args)) + #write (stream, options, ...args) { + const colors = stream === this.#stdout ? this.#stdoutColor : this.#stderrColor + this.#progress.write(stream, formatWithOptions({ colors, ...options }, ...args)) } // HANDLERS @@ -289,16 +293,31 @@ class Display { this.#writeOutput(level, meta, ...args) }) + #inputHandler = withMeta((level, meta, ...args) => { + if (level === input.KEYS.start) { + log.pause() + this.#outputState.buffering = true + this.#progress.pause() + return + } + + if (level === input.KEYS.end) { + log.resume() + output.flush() + this.#progress.resume() + } + }) + // OUTPUT #writeOutput (level, meta, ...args) { if (level === output.KEYS.standard) { - this.#stdoutWrite({}, ...args) + this.#write(this.#stdout, {}, ...args) return } if (level === output.KEYS.error) { - this.#stderrWrite({}, ...args) + this.#write(this.#stderr, {}, ...args) } } @@ -344,22 +363,102 @@ class Display { this.#logColors[level](level), title ? this.#logColors.title(title) : null, ] - this.#stderrWrite({ prefix }, ...args) - } else if (this.#progress) { - // TODO: make this display a single log line of filtered messages + this.#write(this.#stderr, { prefix }, ...args) } } +} + +class Progress { + // Taken from https://github.com/sindresorhus/cli-spinners + // MIT License + // Copyright (c) Sindre Sorhus (https://sindresorhus.com) + static dots = { duration: 80, frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] } + static lines = { duration: 130, frames: ['-', '\\', '|', '/'] } + + #stream + #spinner + #client + #enabled = false + + #frameIndex = 0 + #lastUpdate = 0 + #interval + + #initialTimeout + + constructor ({ stream }) { + this.#client = proggy.createClient({ normalize: true }) + this.#stream = stream + } - // PROGRESS + load ({ enabled, unicode }) { + this.#enabled = enabled + this.#spinner = unicode ? Progress.dots : Progress.lines + this.#delayRender(500) + } - #startProgress ({ progress, unicode }) { - if (!progress || this.#silent) { + off () { + this.#clear() + } + + pause () { + this.#clear({ clearLine: true }) + } + + #clear ({ clearLine } = {}) { + if (!this.#enabled) { + return + } + clearTimeout(this.#initialTimeout) + clearInterval(this.#interval) + this.#frameIndex = 0 + this.#lastUpdate = 0 + this.#stream.cursorTo(0) + if (clearLine) { + this.#stream.clearLine(1) + } + } + + resume () { + this.#delayRender(10) + } + + write (stream, str) { + if (!this.#enabled) { + return stream.write(str) + } + this.#stream.cursorTo(0) + stream.write(str) + this.#render() + } + + #delayRender (ms) { + this.#initialTimeout = setTimeout(() => { + this.#initialTimeout = null + this.#render() + }, ms) + this.#initialTimeout.unref() + } + + #render () { + if (!this.#enabled || this.#initialTimeout) { return } - this.#progress = proggy.createClient({ normalize: true }) - // TODO: implement proggy trackers in arborist/doctor - // TODO: listen to progress events here and build progress UI - // TODO: see deprecated gauge package for what unicode chars were used + this.#renderFrame(Date.now() - this.#lastUpdate >= this.#spinner.duration) + clearInterval(this.#interval) + this.#interval = setInterval(() => this.#renderFrame(true), this.#spinner.duration) + } + + #renderFrame (next) { + if (next) { + this.#lastUpdate = Date.now() + this.#frameIndex++ + if (this.#frameIndex >= this.#spinner.frames.length) { + this.#frameIndex = 0 + } + } + this.#stream.cursorTo(0) + this.#stream.write(this.#spinner.frames[this.#frameIndex]) } } diff --git a/lib/utils/open-url-prompt.js b/lib/utils/open-url-prompt.js index 261cf370da6bd..27f0b3023c99f 100644 --- a/lib/utils/open-url-prompt.js +++ b/lib/utils/open-url-prompt.js @@ -1,5 +1,5 @@ const readline = require('readline') -const { output } = require('proc-log') +const { output, input } = require('proc-log') const open = require('./open-url.js') function print (npm, title, url) { @@ -34,7 +34,7 @@ const promptOpen = async (npm, url, title, prompt, emitter) => { output: process.stdout, }) - const tryOpen = await new Promise(resolve => { + const tryOpen = await input.start(() => new Promise(resolve => { rl.on('SIGINT', () => { rl.close() resolve('SIGINT') @@ -47,13 +47,12 @@ const promptOpen = async (npm, url, title, prompt, emitter) => { if (emitter && emitter.addListener) { emitter.addListener('abort', () => { rl.close() - - // clear the prompt line - output.standard('') - resolve(false) }) } + })).finally(() => { + // clear the prompt line + output.standard('') }) if (tryOpen === 'SIGINT') { diff --git a/lib/utils/read-user-info.js b/lib/utils/read-user-info.js index b2cd7374c17c3..dcd19bb6d14c1 100644 --- a/lib/utils/read-user-info.js +++ b/lib/utils/read-user-info.js @@ -1,6 +1,6 @@ const { read } = require('read') const userValidate = require('npm-user-validate') -const { log } = require('proc-log') +const { log, input, output } = require('proc-log') exports.otp = readOTP exports.password = readPassword @@ -16,12 +16,14 @@ const passwordPrompt = 'npm password: ' const usernamePrompt = 'npm username: ' const emailPrompt = 'email (this IS public): ' +const procLogRead = (...args) => input.start(() => read(...args).finally(() => output.standard(''))) + function readOTP (msg = otpPrompt, otp, isRetry) { if (isRetry && otp && /^[\d ]+$|^[A-Fa-f0-9]{64,64}$/.test(otp)) { return otp.replace(/\s+/g, '') } - return read({ prompt: msg, default: otp || '' }) + return procLogRead({ prompt: msg, default: otp || '' }) .then((rOtp) => readOTP(msg, rOtp, true)) } @@ -30,7 +32,7 @@ function readPassword (msg = passwordPrompt, password, isRetry) { return password } - return read({ prompt: msg, silent: true, default: password || '' }) + return procLogRead({ prompt: msg, silent: true, default: password || '' }) .then((rPassword) => readPassword(msg, rPassword, true)) } @@ -44,7 +46,7 @@ function readUsername (msg = usernamePrompt, username, isRetry) { } } - return read({ prompt: msg, default: username || '' }) + return procLogRead({ prompt: msg, default: username || '' }) .then((rUsername) => readUsername(msg, rUsername, true)) } @@ -58,6 +60,6 @@ function readEmail (msg = emailPrompt, email, isRetry) { } } - return read({ prompt: msg, default: email || '' }) + return procLogRead({ prompt: msg, default: email || '' }) .then((username) => readEmail(msg, username, true)) } diff --git a/tap-snapshots/test/lib/utils/open-url-prompt.js.test.cjs b/tap-snapshots/test/lib/utils/open-url-prompt.js.test.cjs index cf5feed44cc37..a0af353917772 100644 --- a/tap-snapshots/test/lib/utils/open-url-prompt.js.test.cjs +++ b/tap-snapshots/test/lib/utils/open-url-prompt.js.test.cjs @@ -8,6 +8,7 @@ exports[`test/lib/utils/open-url-prompt.js TAP does not error when opener can not find command > Outputs extra Browser unavailable message and url 1`] = ` npm home: https://www.npmjs.com + Browser unavailable. Please open the URL manually: https://www.npmjs.com ` diff --git a/test/lib/utils/read-user-info.js b/test/lib/utils/read-user-info.js index 854277783bb6b..91f798d2bef5d 100644 --- a/test/lib/utils/read-user-info.js +++ b/test/lib/utils/read-user-info.js @@ -1,39 +1,41 @@ const t = require('tap') +const procLog = require('proc-log') const tmock = require('../../fixtures/tmock') let readOpts = null let readResult = null -const read = { read: async (opts) => { - readOpts = opts - return readResult -} } - -const npmUserValidate = { - username: (username) => { - if (username === 'invalid') { - return new Error('invalid username') - } - - return null - }, - email: (email) => { - if (email.startsWith('invalid')) { - return new Error('invalid email') - } - - return null - }, -} - let logMsg = null + const readUserInfo = tmock(t, '{LIB}/utils/read-user-info.js', { - read, + read: { + read: async (opts) => { + readOpts = opts + return readResult + }, + }, 'proc-log': { + ...procLog, log: { + ...procLog.log, warn: (msg) => logMsg = msg, }, }, - 'npm-user-validate': npmUserValidate, + 'npm-user-validate': { + username: (username) => { + if (username === 'invalid') { + return new Error('invalid username') + } + + return null + }, + email: (email) => { + if (email.startsWith('invalid')) { + return new Error('invalid email') + } + + return null + }, + }, }) t.beforeEach(() => { diff --git a/workspaces/libnpmexec/lib/index.js b/workspaces/libnpmexec/lib/index.js index 944f34b01c237..b9934516a4155 100644 --- a/workspaces/libnpmexec/lib/index.js +++ b/workspaces/libnpmexec/lib/index.js @@ -4,7 +4,7 @@ const { mkdir } = require('fs/promises') const Arborist = require('@npmcli/arborist') const ciInfo = require('ci-info') const crypto = require('crypto') -const { log } = require('proc-log') +const { log, input, output } = require('proc-log') const npa = require('npm-package-arg') const pacote = require('pacote') const { read } = require('read') @@ -242,26 +242,26 @@ const exec = async (opts) => { if (add.length) { if (!yes) { - const missingPackages = add.map(a => `${a.replace(/@$/, '')}`) + const addList = add.map(a => `${a.replace(/@$/, '')}`) + // set -n to always say no if (yes === false) { // Error message lists missing package(s) when process is canceled /* eslint-disable-next-line max-len */ - throw new Error(`npx canceled due to missing packages and no YES option: ${JSON.stringify(missingPackages)}`) + throw new Error(`npx canceled due to missing packages and no YES option: ${JSON.stringify(addList)}`) } if (noTTY() || ciInfo.isCI) { - log.warn('exec', `The following package${ - add.length === 1 ? ' was' : 's were' - } not found and will be installed: ${ - add.map((pkg) => pkg.replace(/@$/, '')).join(', ') - }`) + log.warn('exec', + /* eslint-disable-next-line max-len */ + `The following package${add.length === 1 ? ' was' : 's were'} not found and will be installed:`, + addList.join(', ') + ) } else { - const addList = missingPackages.join('\n') + '\n' - const prompt = `Need to install the following packages:\n${ - addList - }Ok to proceed? ` - const confirm = await read({ prompt, default: 'y' }) + /* eslint-disable-next-line max-len */ + const prompt = `Need to install the following packages:\n${addList.join('\n')}\nOk to proceed? ` + const confirm = await input.start(() => read({ prompt, default: 'y' })) + .finally(() => output.standard('')) if (confirm.trim().toLowerCase().charAt(0) !== 'y') { throw new Error('canceled') }