1const promiseSpawn = require('@npmcli/promise-spawn') 2 3const { URL } = require('url') 4 5// attempt to open URL in web-browser, print address otherwise: 6const open = async (npm, url, errMsg, isFile) => { 7 url = encodeURI(url) 8 const browser = npm.config.get('browser') 9 10 function printAlternateMsg () { 11 const json = npm.config.get('json') 12 const alternateMsg = json 13 ? JSON.stringify({ 14 title: errMsg, 15 url, 16 }, null, 2) 17 : `${errMsg}:\n ${url}\n` 18 19 npm.output(alternateMsg) 20 } 21 22 if (browser === false) { 23 printAlternateMsg() 24 return 25 } 26 27 // We pass this in as true from the help command so we know we don't have to 28 // check the protocol 29 if (!isFile) { 30 try { 31 if (!/^https?:$/.test(new URL(url).protocol)) { 32 throw new Error() 33 } 34 } catch { 35 throw new Error('Invalid URL: ' + url) 36 } 37 } 38 39 const command = browser === true ? null : browser 40 await promiseSpawn.open(url, { command }) 41 .catch((err) => { 42 if (err.code !== 127) { 43 throw err 44 } 45 46 printAlternateMsg() 47 }) 48} 49 50module.exports = open 51