error-message.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. const { format } = require('node:util')
  2. const { resolve } = require('node:path')
  3. const { redactLog: replaceInfo } = require('@npmcli/redact')
  4. const { log } = require('proc-log')
  5. const errorMessage = (er, npm) => {
  6. const summary = []
  7. const detail = []
  8. const files = []
  9. let json
  10. er.message &&= replaceInfo(er.message)
  11. er.stack &&= replaceInfo(er.stack)
  12. switch (er.code) {
  13. case 'ERESOLVE': {
  14. const { report } = require('./explain-eresolve.js')
  15. summary.push(['ERESOLVE', er.message])
  16. detail.push(['', ''])
  17. // XXX(display): error messages are logged so we use the logColor since that is based on stderr.
  18. // This should be handled solely by the display layer so it could also be printed to stdout if necessary.
  19. const { explanation, file } = report(er, npm.logChalk, npm.noColorChalk)
  20. detail.push(['', explanation])
  21. files.push(['eresolve-report.txt', file])
  22. break
  23. }
  24. case 'ENOLOCK': {
  25. const cmd = npm.command || ''
  26. summary.push([cmd, 'This command requires an existing lockfile.'])
  27. detail.push([cmd, 'Try creating one first with: npm i --package-lock-only'])
  28. detail.push([cmd, `Original error: ${er.message}`])
  29. break
  30. }
  31. case 'ENOAUDIT':
  32. summary.push(['audit', er.message])
  33. break
  34. case 'ECONNREFUSED':
  35. summary.push(['', er])
  36. detail.push(['', [
  37. '',
  38. `If you are behind a proxy, please make sure that the 'proxy' config is set properly. See: 'npm help config'`,
  39. ].join('\n')])
  40. break
  41. case 'EACCES':
  42. case 'EPERM': {
  43. const isCachePath =
  44. typeof er.path === 'string' && npm.loaded && er.path.startsWith(npm.config.get('cache'))
  45. const isCacheDest =
  46. typeof er.dest === 'string' && npm.loaded && er.dest.startsWith(npm.config.get('cache'))
  47. if (process.platform !== 'win32' && (isCachePath || isCacheDest)) {
  48. // user probably doesn't need this, but still add it to the debug log
  49. log.verbose(er.stack)
  50. summary.push(['', [
  51. '',
  52. 'Your cache folder contains root-owned files, due to a bug in previous versions of npm which has since been addressed.',
  53. '',
  54. 'To permanently fix this problem, please run:',
  55. ` sudo chown -R ${process.getuid()}:${process.getgid()} "${npm.config.get('cache')}"`,
  56. ].join('\n')])
  57. } else {
  58. summary.push(['', er])
  59. detail.push(['', [
  60. '',
  61. 'The operation was rejected by your operating system.',
  62. ...process.platform === 'win32' ? [
  63. `It's possible that the file was already in use (by a text editor or antivirus), or that you lack permissions to access it.`,
  64. ] : [
  65. 'It is likely you do not have the permissions to access this file as the current user',
  66. ],
  67. '',
  68. 'If you believe this might be a permissions issue, please double-check the permissions of the file and its containing directories, or try running the command again as root/Administrator.',
  69. ].join('\n')])
  70. }
  71. break
  72. }
  73. case 'EALLOWGIT':
  74. summary.push(['', er.message])
  75. detail.push(['', `Refusing to fetch "${er.package}"`])
  76. break
  77. case 'ENOGIT':
  78. summary.push(['', er.message])
  79. detail.push(['', [
  80. '',
  81. 'Failed using git.',
  82. 'Please check if you have git installed and in your PATH.',
  83. ].join('\n')])
  84. break
  85. case 'EJSONPARSE':
  86. // Check whether we ran into a conflict in our own package.json
  87. if (er.path === resolve(npm.prefix, 'package.json')) {
  88. const { isDiff } = require('parse-conflict-json')
  89. const txt = require('node:fs').readFileSync(er.path, 'utf8').replace(/\r\n/g, '\n')
  90. if (isDiff(txt)) {
  91. detail.push(['', [
  92. 'Merge conflict detected in your package.json.',
  93. '',
  94. 'Please resolve the package.json conflict and retry.',
  95. ].join('\n')])
  96. break
  97. }
  98. }
  99. summary.push(['JSON.parse', er.message])
  100. detail.push(['JSON.parse', [
  101. 'Failed to parse JSON data.',
  102. 'Note: package.json must be actual JSON, not just JavaScript.',
  103. ].join('\n')])
  104. break
  105. case 'EOTP':
  106. case 'E401':
  107. // E401 is for places where we accidentally neglect OTP stuff
  108. if (er.code === 'EOTP' || /one-time pass/.test(er.message)) {
  109. const authUrl = er.body?.authUrl
  110. const doneUrl = er.body?.doneUrl
  111. if (authUrl && doneUrl) {
  112. json = { authUrl, doneUrl }
  113. summary.push(['', 'This operation requires a one-time password.'])
  114. detail.push(['', `Open this URL in your browser to authenticate:`])
  115. detail.push(['', ` ${authUrl}`])
  116. detail.push(['', ''])
  117. detail.push(['', `After authenticating, your token can be retrieved from:`])
  118. detail.push(['', ` ${doneUrl}`])
  119. } else {
  120. summary.push(['', 'This operation requires a one-time password from your authenticator.'])
  121. detail.push(['', [
  122. 'You can provide a one-time password by passing --otp=<code> to the command you ran.',
  123. 'If you already provided a one-time password then it is likely that you either typoed it, or it timed out. Please try again.',
  124. ].join('\n')])
  125. }
  126. } else {
  127. // npm ERR! code E401
  128. // npm ERR! Unable to authenticate, need: Basic
  129. const auth = !er.headers || !er.headers['www-authenticate']
  130. ? []
  131. : er.headers['www-authenticate'].map(au => au.split(/[,\s]+/))[0]
  132. if (auth.includes('Bearer')) {
  133. summary.push(['',
  134. 'Unable to authenticate, your authentication token seems to be invalid.',
  135. ])
  136. detail.push(['', [
  137. 'To correct this please try logging in again with:',
  138. ' npm login',
  139. ].join('\n')])
  140. } else if (auth.includes('Basic')) {
  141. summary.push(['', 'Incorrect or missing password.'])
  142. detail.push(['', [
  143. 'If you were trying to login, change your password, create an authentication token or enable two-factor authentication then that means you likely typed your password in incorrectly.',
  144. 'Please try again, or recover your password at:',
  145. ' https://www.npmjs.com/forgot',
  146. '',
  147. 'If you were doing some other operation then your saved credentials are probably out of date.',
  148. 'To correct this please try logging in again with:',
  149. ' npm login',
  150. ].join('\n')])
  151. } else {
  152. summary.push(['', er.message || er])
  153. }
  154. }
  155. break
  156. case 'E404':
  157. // There's no need to have 404 in the message as well.
  158. summary.push(['404', er.message.replace(/^404\s+/, '')])
  159. if (er.pkgid && er.pkgid !== '-') {
  160. const pkg = er.pkgid.replace(/(?!^)@.*$/, '')
  161. detail.push(['404', ''])
  162. detail.push([
  163. '404',
  164. '',
  165. `The requested resource '${replaceInfo(er.pkgid)}' could not be found or you do not have permission to access it.`,
  166. ])
  167. const nameValidator = require('validate-npm-package-name')
  168. const valResult = nameValidator(pkg)
  169. if (!valResult.validForNewPackages) {
  170. detail.push(['404', 'This package name is not valid, because', ''])
  171. const errorsArray = [...(valResult.errors || []), ...(valResult.warnings || [])]
  172. errorsArray.forEach((item, idx) => detail.push(['404', ' ' + (idx + 1) + '. ' + item]))
  173. }
  174. detail.push(['404', ''])
  175. detail.push(['404', 'Note that you can also install from a'])
  176. detail.push(['404', 'tarball, folder, http url, or git url.'])
  177. }
  178. break
  179. case 'EPUBLISHCONFLICT':
  180. summary.push(['publish fail', 'Cannot publish over existing version.'])
  181. detail.push(['publish fail', `Update the 'version' field in package.json and try again.`])
  182. detail.push(['publish fail', ''])
  183. detail.push(['publish fail', 'To automatically increment version numbers, see:'])
  184. detail.push(['publish fail', ' npm help version'])
  185. break
  186. case 'EISGIT':
  187. summary.push(['git', er.message])
  188. summary.push(['git', ` ${er.path}`])
  189. detail.push(['git', [
  190. 'Refusing to remove it. Update manually, or move it out of the way first.',
  191. ].join('\n')])
  192. break
  193. case 'EBADDEVENGINES': {
  194. const { current, required } = er
  195. summary.push(['EBADDEVENGINES', er.message])
  196. detail.push(['EBADDEVENGINES', { current, required }])
  197. break
  198. }
  199. case 'EBADPLATFORM': {
  200. const actual = er.current
  201. const expected = { ...er.required }
  202. const checkedKeys = []
  203. for (const key in expected) {
  204. if (Array.isArray(expected[key]) && expected[key].length > 0) {
  205. expected[key] = expected[key].join(',')
  206. checkedKeys.push(key)
  207. } else if (expected[key] === undefined ||
  208. Array.isArray(expected[key]) && expected[key].length === 0) {
  209. delete expected[key]
  210. delete actual[key]
  211. } else {
  212. checkedKeys.push(key)
  213. }
  214. }
  215. const longestKey = Math.max(...checkedKeys.map((key) => key.length))
  216. const detailEntry = []
  217. for (const key of checkedKeys) {
  218. const padding = key.length === longestKey
  219. ? 1
  220. : 1 + (longestKey - key.length)
  221. // padding + 1 because 'actual' is longer than 'valid'
  222. detailEntry.push(`Valid ${key}:${' '.repeat(padding + 1)}${expected[key]}`)
  223. detailEntry.push(`Actual ${key}:${' '.repeat(padding)}${actual[key]}`)
  224. }
  225. summary.push(['notsup', format(
  226. 'Unsupported platform for %s: wanted %j (current: %j)',
  227. er.pkgid,
  228. expected,
  229. actual
  230. )])
  231. detail.push(['notsup', detailEntry.join('\n')])
  232. break
  233. }
  234. case 'EEXIST':
  235. summary.push(['', er.message])
  236. summary.push(['', 'File exists: ' + (er.dest || er.path)])
  237. detail.push(['', 'Remove the existing file and try again, or run npm'])
  238. detail.push(['', 'with --force to overwrite files recklessly.'])
  239. break
  240. case 'ENEEDAUTH':
  241. summary.push(['need auth', er.message])
  242. detail.push(['need auth', 'You need to authorize this machine using `npm adduser`'])
  243. break
  244. case 'ECONNRESET':
  245. case 'ENOTFOUND':
  246. case 'ETIMEDOUT':
  247. case 'ERR_SOCKET_TIMEOUT':
  248. case 'EAI_FAIL':
  249. summary.push(['network', er.message])
  250. detail.push(['network', [
  251. 'This is a problem related to network connectivity.',
  252. 'In most cases you are behind a proxy or have bad network settings.',
  253. '',
  254. `If you are behind a proxy, please make sure that the 'proxy' config is set properly. See: 'npm help config'`,
  255. ].join('\n')])
  256. break
  257. case 'ETARGET':
  258. summary.push(['notarget', er.message])
  259. detail.push(['notarget', [
  260. `In most cases you or one of your dependencies are requesting a package version that doesn't exist.`,
  261. ].join('\n')])
  262. break
  263. case 'E403':
  264. summary.push(['403', er.message])
  265. detail.push(['403', [
  266. 'In most cases, you or one of your dependencies are requesting a package version that is forbidden by your security policy, or on a server you do not have access to.',
  267. ].join('\n')])
  268. break
  269. case 'EBADENGINE':
  270. summary.push(['engine', er.message])
  271. summary.push(['engine', 'Not compatible with your version of node/npm: ' + er.pkgid])
  272. detail.push(['notsup', [
  273. 'Not compatible with your version of node/npm: ' + er.pkgid,
  274. 'Required: ' + JSON.stringify(er.required),
  275. 'Actual: ' +
  276. JSON.stringify({ node: process.version, npm: npm.version }),
  277. ].join('\n')])
  278. break
  279. case 'ENOSPC':
  280. summary.push(['nospc', er.message])
  281. detail.push(['nospc', [
  282. 'There appears to be insufficient space on your system to finish.',
  283. 'Clear up some disk space and try again.',
  284. ].join('\n')])
  285. break
  286. case 'EROFS':
  287. summary.push(['rofs', er.message])
  288. detail.push(['rofs', [
  289. `Often virtualized file systems, or other file systems that don't support symlinks, give this error.`,
  290. ].join('\n')])
  291. break
  292. case 'ENOENT':
  293. summary.push(['enoent', er.message])
  294. detail.push(['enoent', [
  295. 'This is related to npm not being able to find a file.',
  296. er.file ? `\nCheck if the file '${er.file}' is present.` : '',
  297. ].join('\n')])
  298. break
  299. case 'EMISSINGARG':
  300. case 'EUNKNOWNTYPE':
  301. case 'EINVALIDTYPE':
  302. case 'ETOOMANYARGS':
  303. summary.push(['typeerror', er.stack])
  304. detail.push(['typeerror', [
  305. 'This is an error with npm itself. Please report this error at:',
  306. 'https://github.com/npm/cli/issues',
  307. ].join('\n')])
  308. break
  309. default:
  310. summary.push(['', er.message || er])
  311. if (er.cause) {
  312. detail.push(['cause', er.cause.message])
  313. }
  314. if (er.signal) {
  315. detail.push(['signal', er.signal])
  316. }
  317. if (er.cmd && Array.isArray(er.args)) {
  318. detail.push(['command', ...[er.cmd, ...er.args.map(replaceInfo)]])
  319. }
  320. if (er.stdout) {
  321. detail.push(['', er.stdout.trim()])
  322. }
  323. if (er.stderr) {
  324. detail.push(['', er.stderr.trim()])
  325. }
  326. break
  327. }
  328. return {
  329. summary,
  330. detail,
  331. files,
  332. json,
  333. }
  334. }
  335. const getExitCodeFromError = (err) => {
  336. if (typeof err?.errno === 'number') {
  337. return err.errno
  338. } else if (typeof err?.code === 'number') {
  339. return err.code
  340. }
  341. }
  342. const getError = (err, { npm, command, pkg }) => {
  343. // if we got a command that just shells out to something else, then it will presumably print its own errors and exit with a proper status code if there's a problem.
  344. // If we got an error with a code=0, then... something else went wrong along the way, so maybe an npm problem?
  345. if (command?.constructor?.isShellout && typeof err.code === 'number' && err.code) {
  346. return {
  347. exitCode: err.code,
  348. suppressError: true,
  349. }
  350. }
  351. // XXX: we should stop throwing strings
  352. if (typeof err === 'string') {
  353. return {
  354. exitCode: 1,
  355. suppressError: true,
  356. summary: [['', err]],
  357. }
  358. }
  359. // XXX: we should stop throwing other non-errors
  360. if (!(err instanceof Error)) {
  361. return {
  362. exitCode: 1,
  363. suppressError: true,
  364. summary: [['weird error', err]],
  365. }
  366. }
  367. if (err.code === 'EUNKNOWNCOMMAND') {
  368. const suggestions = require('./did-you-mean.js')(pkg, err.command)
  369. return {
  370. exitCode: 1,
  371. suppressError: true,
  372. standard: [
  373. `Unknown command: "${err.command}"`,
  374. suggestions,
  375. 'To see a list of supported npm commands, run:',
  376. ' npm help',
  377. ],
  378. }
  379. }
  380. // Anything after this is not suppressed and gets more logged information
  381. // add a code to the error if it doesnt have one and mutate some properties so they have redacted information
  382. err.code ??= err.message.match(/^(?:Error: )?(E[A-Z]+)/)?.[1]
  383. // this mutates the error and redacts stack/message
  384. const { summary, detail, files, json } = errorMessage(err, npm)
  385. return {
  386. err,
  387. code: err.code,
  388. exitCode: getExitCodeFromError(err) || 1,
  389. suppressError: false,
  390. summary,
  391. detail,
  392. files,
  393. json,
  394. verbose: ['type', 'stack', 'statusCode', 'pkgid']
  395. .filter(k => err[k])
  396. .map(k => [k, replaceInfo(err[k])]),
  397. error: ['code', 'syscall', 'file', 'path', 'dest', 'errno']
  398. .filter(k => err[k])
  399. .map(k => [k, err[k]]),
  400. }
  401. }
  402. module.exports = {
  403. getExitCodeFromError,
  404. errorMessage,
  405. getError,
  406. }