• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict'
2var npm = require('../npm.js')
3var util = require('util')
4var nameValidator = require('validate-npm-package-name')
5var npmlog = require('npmlog')
6var replaceInfo = require('./replace-info.js')
7
8module.exports = errorMessage
9
10function errorMessage (er) {
11  var short = []
12  var detail = []
13
14  er.message = replaceInfo(er.message)
15  er.stack = replaceInfo(er.stack)
16
17  switch (er.code) {
18    case 'ENOAUDIT':
19      short.push(['audit', er.message])
20      break
21    case 'EAUDITNOPJSON':
22      short.push(['audit', er.message])
23      break
24    case 'EAUDITNOLOCK':
25      short.push(['audit', er.message])
26      detail.push(['audit', 'Try creating one first with: npm i --package-lock-only'])
27      break
28
29    case 'ECONNREFUSED':
30      short.push(['', er])
31      detail.push([
32        '',
33        [
34          '\nIf you are behind a proxy, please make sure that the',
35          "'proxy' config is set properly.  See: 'npm help config'"
36        ].join('\n')
37      ])
38      break
39
40    case 'EACCES':
41    case 'EPERM':
42      const isCachePath = typeof er.path === 'string' &&
43        npm.config && er.path.startsWith(npm.config.get('cache'))
44      const isCacheDest = typeof er.dest === 'string' &&
45        npm.config && er.dest.startsWith(npm.config.get('cache'))
46
47      const isWindows = process.platform === 'win32'
48
49      if (!isWindows && (isCachePath || isCacheDest)) {
50        // user probably doesn't need this, but still add it to the debug log
51        npmlog.verbose(er.stack)
52        short.push([
53          '',
54          [
55            '',
56            'Your cache folder contains root-owned files, due to a bug in',
57            'previous versions of npm which has since been addressed.',
58            '',
59            'To permanently fix this problem, please run:',
60            `  sudo chown -R ${process.getuid()}:${process.getgid()} ${JSON.stringify(npm.config.get('cache'))}`
61          ].join('\n')
62        ])
63      } else {
64        short.push(['', er])
65        detail.push([
66          '',
67          [
68            '\nThe operation was rejected by your operating system.',
69            (process.platform === 'win32'
70              ? 'It\'s possible that the file was already in use (by a text editor or antivirus),\n' +
71                'or that you lack permissions to access it.'
72              : 'It is likely you do not have the permissions to access this file as the current user'),
73            '\nIf you believe this might be a permissions issue, please double-check the',
74            'permissions of the file and its containing directories, or try running',
75            'the command again as root/Administrator.'
76          ].join('\n')])
77      }
78      break
79
80    case 'EUIDLOOKUP':
81      short.push(['lifecycle', er.message])
82      detail.push([
83        '',
84        [
85          '',
86          'Failed to look up the user/group for running scripts.',
87          '',
88          'Try again with a different --user or --group settings, or',
89          'run with --unsafe-perm to execute scripts as root.'
90        ].join('\n')
91      ])
92      break
93
94    case 'ELIFECYCLE':
95      short.push(['', er.message])
96      detail.push([
97        '',
98        [
99          '',
100          'Failed at the ' + er.pkgid + ' ' + er.stage + ' script.',
101          'This is probably not a problem with npm. There is likely additional logging output above.'
102        ].join('\n')]
103      )
104      break
105
106    case 'ENOGIT':
107      short.push(['', er.message])
108      detail.push([
109        '',
110        [
111          '',
112          'Failed using git.',
113          'Please check if you have git installed and in your PATH.'
114        ].join('\n')
115      ])
116      break
117
118    case 'EJSONPARSE':
119      const path = require('path')
120      // Check whether we ran into a conflict in our own package.json
121      if (er.file === path.join(npm.prefix, 'package.json')) {
122        const isDiff = require('../install/read-shrinkwrap.js')._isDiff
123        const txt = require('fs').readFileSync(er.file, 'utf8')
124        if (isDiff(txt)) {
125          detail.push([
126            '',
127            [
128              'Merge conflict detected in your package.json.',
129              '',
130              'Please resolve the package.json conflict and retry the command:',
131              '',
132              `$ ${process.argv.join(' ')}`
133            ].join('\n')
134          ])
135          break
136        }
137      }
138      short.push(['JSON.parse', er.message])
139      detail.push([
140        'JSON.parse',
141        [
142          'Failed to parse package.json data.',
143          'package.json must be actual JSON, not just JavaScript.'
144        ].join('\n')
145      ])
146      break
147
148    case 'EOTP':
149    case 'E401':
150      // E401 is for places where we accidentally neglect OTP stuff
151      if (er.code === 'EOTP' || /one-time pass/.test(er.message)) {
152        short.push(['', 'This operation requires a one-time password from your authenticator.'])
153        detail.push([
154          '',
155          [
156            'You can provide a one-time password by passing --otp=<code> to the command you ran.',
157            'If you already provided a one-time password then it is likely that you either typoed',
158            'it, or it timed out. Please try again.'
159          ].join('\n')
160        ])
161      } else {
162        // npm ERR! code E401
163        // npm ERR! Unable to authenticate, need: Basic
164        const auth = (er.headers && er.headers['www-authenticate'] && er.headers['www-authenticate'].map((au) => au.split(/,\s*/))[0]) || []
165        if (auth.indexOf('Bearer') !== -1) {
166          short.push(['', 'Unable to authenticate, your authentication token seems to be invalid.'])
167          detail.push([
168            '',
169            [
170              'To correct this please trying logging in again with:',
171              '    npm login'
172            ].join('\n')
173          ])
174        } else if (auth.indexOf('Basic') !== -1) {
175          short.push(['', 'Incorrect or missing password.'])
176          detail.push([
177            '',
178            [
179              'If you were trying to login, change your password, create an',
180              'authentication token or enable two-factor authentication then',
181              'that means you likely typed your password in incorrectly.',
182              'Please try again, or recover your password at:',
183              '    https://www.npmjs.com/forgot',
184              '',
185              'If you were doing some other operation then your saved credentials are',
186              'probably out of date. To correct this please try logging in again with:',
187              '    npm login'
188            ].join('\n')
189          ])
190        } else {
191          short.push(['', er.message || er])
192        }
193      }
194      break
195
196    case 'E404':
197      // There's no need to have 404 in the message as well.
198      var msg = er.message.replace(/^404\s+/, '')
199      short.push(['404', msg])
200      if (er.pkgid && er.pkgid !== '-') {
201        var pkg = er.pkgid.replace(/(?!^)@.*$/, '')
202
203        detail.push(['404', ''])
204        detail.push(['404', '', "'" + er.pkgid + "' is not in the npm registry."])
205
206        var valResult = nameValidator(pkg)
207
208        if (valResult.validForNewPackages) {
209          detail.push(['404', 'You should bug the author to publish it (or use the name yourself!)'])
210        } else {
211          detail.push(['404', 'Your package name is not valid, because', ''])
212
213          var errorsArray = (valResult.errors || []).concat(valResult.warnings || [])
214          errorsArray.forEach(function (item, idx) {
215            detail.push(['404', ' ' + (idx + 1) + '. ' + item])
216          })
217        }
218
219        if (er.parent) {
220          detail.push(['404', "It was specified as a dependency of '" + er.parent + "'"])
221        }
222        detail.push(['404', '\nNote that you can also install from a'])
223        detail.push(['404', 'tarball, folder, http url, or git url.'])
224      }
225      break
226
227    case 'EPUBLISHCONFLICT':
228      short.push(['publish fail', 'Cannot publish over existing version.'])
229      detail.push(['publish fail', "Update the 'version' field in package.json and try again."])
230      detail.push(['publish fail', ''])
231      detail.push(['publish fail', 'To automatically increment version numbers, see:'])
232      detail.push(['publish fail', '    npm help version'])
233      break
234
235    case 'EISGIT':
236      short.push(['git', er.message])
237      short.push(['git', '    ' + er.path])
238      detail.push([
239        'git',
240        [
241          'Refusing to remove it. Update manually,',
242          'or move it out of the way first.'
243        ].join('\n')
244      ])
245      break
246
247    case 'ECYCLE':
248      short.push([
249        'cycle',
250        [
251          er.message,
252          'While installing: ' + er.pkgid
253        ].join('\n')
254      ])
255      detail.push([
256        'cycle',
257        [
258          'Found a pathological dependency case that npm cannot solve.',
259          'Please report this to the package author.'
260        ].join('\n')
261      ])
262      break
263
264    case 'EBADPLATFORM':
265      var validOs = er.os.join ? er.os.join(',') : er.os
266      var validArch = er.cpu.join ? er.cpu.join(',') : er.cpu
267      var expected = {os: validOs, arch: validArch}
268      var actual = {os: process.platform, arch: process.arch}
269      short.push([
270        'notsup',
271        [
272          util.format('Unsupported platform for %s: wanted %j (current: %j)', er.pkgid, expected, actual)
273        ].join('\n')
274      ])
275      detail.push([
276        'notsup',
277        [
278          'Valid OS:    ' + validOs,
279          'Valid Arch:  ' + validArch,
280          'Actual OS:   ' + process.platform,
281          'Actual Arch: ' + process.arch
282        ].join('\n')
283      ])
284      break
285
286    case 'EEXIST':
287      short.push(['', er.message])
288      short.push(['', 'File exists: ' + (er.dest || er.path)])
289      detail.push(['', 'Remove the existing file and try again, or run npm'])
290      detail.push(['', 'with --force to overwrite files recklessly.'])
291      break
292
293    case 'ENEEDAUTH':
294      short.push(['need auth', er.message])
295      detail.push(['need auth', 'You need to authorize this machine using `npm adduser`'])
296      break
297
298    case 'ECONNRESET':
299    case 'ENOTFOUND':
300    case 'ETIMEDOUT':
301    case 'EAI_FAIL':
302      short.push(['network', er.message])
303      detail.push([
304        'network',
305        [
306          'This is a problem related to network connectivity.',
307          'In most cases you are behind a proxy or have bad network settings.',
308          '\nIf you are behind a proxy, please make sure that the',
309          "'proxy' config is set properly.  See: 'npm help config'"
310        ].join('\n')
311      ])
312      break
313
314    case 'ENOPACKAGEJSON':
315      short.push(['package.json', er.message])
316      detail.push([
317        'package.json',
318        [
319          "npm can't find a package.json file in your current directory."
320        ].join('\n')
321      ])
322      break
323
324    case 'ETARGET':
325      short.push(['notarget', er.message])
326      msg = [
327        'In most cases you or one of your dependencies are requesting',
328        "a package version that doesn't exist."
329      ]
330      if (er.parent) {
331        msg.push("\nIt was specified as a dependency of '" + er.parent + "'\n")
332      }
333      detail.push(['notarget', msg.join('\n')])
334      break
335
336    case 'E403':
337      short.push(['403', er.message])
338      msg = [
339        'In most cases, you or one of your dependencies are requesting',
340        'a package version that is forbidden by your security policy.'
341      ]
342      if (er.parent) {
343        msg.push("\nIt was specified as a dependency of '" + er.parent + "'\n")
344      }
345      detail.push(['403', msg.join('\n')])
346      break
347
348    case 'ENOTSUP':
349      if (er.required) {
350        short.push(['notsup', er.message])
351        short.push(['notsup', 'Not compatible with your version of node/npm: ' + er.pkgid])
352        detail.push([
353          'notsup',
354          [
355            'Not compatible with your version of node/npm: ' + er.pkgid,
356            'Required: ' + JSON.stringify(er.required),
357            'Actual:   ' + JSON.stringify({
358              npm: npm.version,
359              node: npm.config.get('node-version')
360            })
361          ].join('\n')
362        ])
363        break
364      } // else passthrough
365      /* eslint no-fallthrough:0 */
366
367    case 'ENOSPC':
368      short.push(['nospc', er.message])
369      detail.push([
370        'nospc',
371        [
372          'There appears to be insufficient space on your system to finish.',
373          'Clear up some disk space and try again.'
374        ].join('\n')
375      ])
376      break
377
378    case 'EROFS':
379      short.push(['rofs', er.message])
380      detail.push([
381        'rofs',
382        [
383          'Often virtualized file systems, or other file systems',
384          "that don't support symlinks, give this error."
385        ].join('\n')
386      ])
387      break
388
389    case 'ENOENT':
390      short.push(['enoent', er.message])
391      detail.push([
392        'enoent',
393        [
394          'This is related to npm not being able to find a file.',
395          er.file ? "\nCheck if the file '" + er.file + "' is present." : ''
396        ].join('\n')
397      ])
398      break
399
400    case 'EMISSINGARG':
401    case 'EUNKNOWNTYPE':
402    case 'EINVALIDTYPE':
403    case 'ETOOMANYARGS':
404      short.push(['typeerror', er.stack])
405      detail.push([
406        'typeerror',
407        [
408          'This is an error with npm itself. Please report this error at:',
409          '    <https://npm.community>'
410        ].join('\n')
411      ])
412      break
413
414    default:
415      short.push(['', er.message || er])
416      break
417  }
418  if (er.optional) {
419    short.unshift(['optional', er.optional + ' (' + er.location + '):'])
420    short.concat(detail).forEach(function (msg) {
421      if (!msg[0]) msg[0] = 'optional'
422      if (msg[1]) msg[1] = msg[1].toString().replace(/(^|\n)/g, '$1SKIPPING OPTIONAL DEPENDENCY: ')
423    })
424  }
425  return {summary: short, detail: detail}
426}
427