mirror of
https://github.com/nodejs/node.git
synced 2025-05-15 16:01:52 +00:00

PR-URL: https://github.com/nodejs/node/pull/44119 Reviewed-By: Ruy Adorno <ruyadorno@google.com> Reviewed-By: Mohammed Keyvanzadeh <mohammadkeyvanzade94@gmail.com> Reviewed-By: Tobias Nießen <tniessen@tnie.de> Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Myles Borins <myles.borins@gmail.com>
79 lines
1.5 KiB
JavaScript
79 lines
1.5 KiB
JavaScript
const readline = require('readline')
|
|
const opener = require('opener')
|
|
|
|
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
|
|
}
|
|
|
|
const command = browser === true ? null : browser
|
|
await new Promise((resolve, reject) => {
|
|
opener(url, { command }, err => {
|
|
if (err) {
|
|
return reject(err)
|
|
}
|
|
|
|
return resolve()
|
|
})
|
|
})
|
|
}
|
|
|
|
module.exports = promptOpen
|