node/deps/npm/lib/utils/open-url-prompt.js
npm CLI robot 1cc37c4355
deps: upgrade npm to 10.3.0
PR-URL: https://github.com/nodejs/node/pull/51431
Reviewed-By: Luke Karrys <luke@lukekarrys.com>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com>
2024-02-15 12:02:32 +01:00

69 lines
1.4 KiB
JavaScript

const readline = require('readline')
const open = require('./open-url.js')
function print (npm, title, url) {
const json = npm.config.get('json')
const message = json ? JSON.stringify({ title, url }) : `${title}:\n${url}`
npm.output(message)
}
// Prompt to open URL in browser if possible
const promptOpen = async (npm, url, title, prompt, emitter) => {
const browser = npm.config.get('browser')
const isInteractive = process.stdin.isTTY === true && process.stdout.isTTY === true
try {
if (!/^https?:$/.test(new URL(url).protocol)) {
throw new Error()
}
} catch (_) {
throw new Error('Invalid URL: ' + url)
}
print(npm, title, url)
if (browser === false || !isInteractive) {
return
}
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
const tryOpen = await new Promise(resolve => {
rl.on('SIGINT', () => {
rl.close()
resolve('SIGINT')
})
rl.question(prompt, () => {
resolve(true)
})
if (emitter && emitter.addListener) {
emitter.addListener('abort', () => {
rl.close()
// clear the prompt line
npm.output('')
resolve(false)
})
}
})
if (tryOpen === 'SIGINT') {
throw new Error('canceled')
}
if (!tryOpen) {
return
}
await open(npm, url, 'Browser unavailable. Please open the URL manually')
}
module.exports = promptOpen