summaryrefslogtreecommitdiff
path: root/deps/npm/lib/npm.js
blob: da5a36360212235e595c0b4eedc061cdfecc41e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
;(function () {
  // windows: running 'npm blah' in this folder will invoke WSH, not node.
  /* globals WScript */
  if (typeof WScript !== 'undefined') {
    WScript.echo(
      'npm does not work when run\n' +
      'with the Windows Scripting Host\n\n' +
      '"cd" to a different directory,\n' +
      'or type "npm.cmd <args>",\n' +
      'or type "node npm <args>".'
    )
    WScript.quit(1)
    return
  }

  var unsupported = require('../lib/utils/unsupported.js')
  unsupported.checkForBrokenNode()

  var gfs = require('graceful-fs')
  // Patch the global fs module here at the app level
  var fs = gfs.gracefulify(require('fs'))

  var EventEmitter = require('events').EventEmitter
  var npm = module.exports = new EventEmitter()
  var npmconf = require('./config/core.js')
  var log = require('npmlog')
  var inspect = require('util').inspect

  // capture global logging
  process.on('log', function (level) {
    try {
      return log[level].apply(log, [].slice.call(arguments, 1))
    } catch (ex) {
      log.verbose('attempt to log ' + inspect(arguments) + ' crashed: ' + ex.message)
    }
  })

  var path = require('path')
  var abbrev = require('abbrev')
  var which = require('which')
  var glob = require('glob')
  var rimraf = require('rimraf')
  var lazyProperty = require('lazy-property')
  var parseJSON = require('./utils/parse-json.js')
  var clientConfig = require('./config/reg-client.js')
  var aliases = require('./config/cmd-list').aliases
  var cmdList = require('./config/cmd-list').cmdList
  var plumbing = require('./config/cmd-list').plumbing
  var output = require('./utils/output.js')
  var startMetrics = require('./utils/metrics.js').start
  var perf = require('./utils/perf.js')

  perf.emit('time', 'npm')
  perf.on('timing', function (name, finished) {
    log.timing(name, 'Completed in', finished + 'ms')
  })

  npm.config = {
    loaded: false,
    get: function () {
      throw new Error('npm.load() required')
    },
    set: function () {
      throw new Error('npm.load() required')
    }
  }

  npm.commands = {}

  // TUNING
  npm.limit = {
    fetch: 10,
    action: 50
  }
  // ***

  npm.lockfileVersion = 1

  npm.rollbacks = []

  try {
    // startup, ok to do this synchronously
    var j = parseJSON(fs.readFileSync(
      path.join(__dirname, '../package.json')) + '')
    npm.name = j.name
    npm.version = j.version
  } catch (ex) {
    try {
      log.info('error reading version', ex)
    } catch (er) {}
    npm.version = ex
  }

  var commandCache = {}
  var aliasNames = Object.keys(aliases)

  var littleGuys = [ 'isntall', 'verison' ]
  var fullList = cmdList.concat(aliasNames).filter(function (c) {
    return plumbing.indexOf(c) === -1
  })
  var abbrevs = abbrev(fullList)

  // we have our reasons
  fullList = npm.fullList = fullList.filter(function (c) {
    return littleGuys.indexOf(c) === -1
  })

  var registryRefer
  var registryLoaded

  Object.keys(abbrevs).concat(plumbing).forEach(function addCommand (c) {
    Object.defineProperty(npm.commands, c, { get: function () {
      if (!loaded) {
        throw new Error(
          'Call npm.load(config, cb) before using this command.\n' +
            'See the README.md or bin/npm-cli.js for example usage.'
        )
      }
      var a = npm.deref(c)
      if (c === 'la' || c === 'll') {
        npm.config.set('long', true)
      }

      npm.command = c
      if (commandCache[a]) return commandCache[a]

      var cmd = require(path.join(__dirname, a + '.js'))

      commandCache[a] = function () {
        var args = Array.prototype.slice.call(arguments, 0)
        if (typeof args[args.length - 1] !== 'function') {
          args.push(defaultCb)
        }
        if (args.length === 1) args.unshift([])

        // Options are prefixed by a hyphen-minus (-, \u2d).
        // Other dash-type chars look similar but are invalid.
        Array(args[0]).forEach(function (arg) {
          if (/^[\u2010-\u2015\u2212\uFE58\uFE63\uFF0D]/.test(arg)) {
            log.error('arg', 'Argument starts with non-ascii dash, this is probably invalid:', arg)
          }
        })

        if (!registryRefer) {
          registryRefer = [a].concat(args[0]).map(function (arg) {
            // exclude anything that might be a URL, path, or private module
            // Those things will always have a slash in them somewhere
            if (arg && arg.match && arg.match(/\/|\\/)) {
              return '[REDACTED]'
            } else {
              return arg
            }
          }).filter(function (arg) {
            return arg && arg.match
          }).join(' ')
          if (registryLoaded) npm.registry.refer = registryRefer
        }

        cmd.apply(npm, args)
      }

      Object.keys(cmd).forEach(function (k) {
        commandCache[a][k] = cmd[k]
      })

      return commandCache[a]
    },
    enumerable: fullList.indexOf(c) !== -1,
    configurable: true })

    // make css-case commands callable via camelCase as well
    if (c.match(/-([a-z])/)) {
      addCommand(c.replace(/-([a-z])/g, function (a, b) {
        return b.toUpperCase()
      }))
    }
  })

  function defaultCb (er, data) {
    log.disableProgress()
    if (er) console.error(er.stack || er.message)
    else output(data)
  }

  npm.deref = function (c) {
    if (!c) return ''
    if (c.match(/[A-Z]/)) {
      c = c.replace(/([A-Z])/g, function (m) {
        return '-' + m.toLowerCase()
      })
    }
    if (plumbing.indexOf(c) !== -1) return c
    var a = abbrevs[c]
    while (aliases[a]) {
      a = aliases[a]
    }
    return a
  }

  var loaded = false
  var loading = false
  var loadErr = null
  var loadListeners = []

  function loadCb (er) {
    loadListeners.forEach(function (cb) {
      process.nextTick(cb.bind(npm, er, npm))
    })
    loadListeners.length = 0
  }

  npm.load = function (cli, cb_) {
    if (!cb_ && typeof cli === 'function') {
      cb_ = cli
      cli = {}
    }
    if (!cb_) cb_ = function () {}
    if (!cli) cli = {}
    loadListeners.push(cb_)
    if (loaded || loadErr) return cb(loadErr)
    if (loading) return
    loading = true
    var onload = true

    function cb (er) {
      if (loadErr) return
      loadErr = er
      if (er) return cb_(er)
      if (npm.config.get('force')) {
        log.warn('using --force', 'I sure hope you know what you are doing.')
      }
      npm.config.loaded = true
      loaded = true
      loadCb(loadErr = er)
      onload = onload && npm.config.get('onload-script')
      if (onload) {
        try {
          require(onload)
        } catch (err) {
          log.warn('onload-script', 'failed to require onload script', onload)
          log.warn('onload-script', err)
        }
        onload = false
      }
    }

    log.pause()

    load(npm, cli, cb)
  }

  function load (npm, cli, cb) {
    which(process.argv[0], function (er, node) {
      if (!er && node.toUpperCase() !== process.execPath.toUpperCase()) {
        log.verbose('node symlink', node)
        process.execPath = node
        process.installPrefix = path.resolve(node, '..', '..')
      }

      // look up configs
      var builtin = path.resolve(__dirname, '..', 'npmrc')
      npmconf.load(cli, builtin, function (er, config) {
        if (er === config) er = null

        npm.config = config
        if (er) return cb(er)

        // if the 'project' config is not a filename, and we're
        // not in global mode, then that means that it collided
        // with either the default or effective userland config
        if (!config.get('global') &&
            config.sources.project &&
            config.sources.project.type !== 'ini') {
          log.verbose(
            'config',
            'Skipping project config: %s. (matches userconfig)',
            config.localPrefix + '/.npmrc'
          )
        }

        // Include npm-version and node-version in user-agent
        var ua = config.get('user-agent') || ''
        ua = ua.replace(/\{node-version\}/gi, process.version)
        ua = ua.replace(/\{npm-version\}/gi, npm.version)
        ua = ua.replace(/\{platform\}/gi, process.platform)
        ua = ua.replace(/\{arch\}/gi, process.arch)
        config.set('user-agent', ua)

        if (config.get('metrics-registry') == null) {
          config.set('metrics-registry', config.get('registry'))
        }

        var color = config.get('color')

        if (npm.config.get('timing') && npm.config.get('loglevel') === 'notice') {
          log.level = 'timing'
        } else {
          log.level = config.get('loglevel')
        }
        log.heading = config.get('heading') || 'npm'
        log.stream = config.get('logstream')

        switch (color) {
          case 'always':
            npm.color = true
            break
          case false:
            npm.color = false
            break
          default:
            npm.color = process.stdout.isTTY && process.env['TERM'] !== 'dumb'
            break
        }
        if (npm.color) {
          log.enableColor()
        } else {
          log.disableColor()
        }

        if (config.get('unicode')) {
          log.enableUnicode()
        } else {
          log.disableUnicode()
        }

        if (config.get('progress') && process.stderr.isTTY && process.env['TERM'] !== 'dumb') {
          log.enableProgress()
        } else {
          log.disableProgress()
        }

        glob(path.resolve(npm.cache, '_logs', '*-debug.log'), function (er, files) {
          if (er) return cb(er)

          while (files.length >= npm.config.get('logs-max')) {
            rimraf.sync(files[0])
            files.splice(0, 1)
          }
        })

        log.resume()

        var umask = npm.config.get('umask')
        npm.modes = {
          exec: parseInt('0777', 8) & (~umask),
          file: parseInt('0666', 8) & (~umask),
          umask: umask
        }

        var gp = Object.getOwnPropertyDescriptor(config, 'globalPrefix')
        Object.defineProperty(npm, 'globalPrefix', gp)

        var lp = Object.getOwnPropertyDescriptor(config, 'localPrefix')
        Object.defineProperty(npm, 'localPrefix', lp)

        config.set('scope', scopeifyScope(config.get('scope')))
        npm.projectScope = config.get('scope') ||
         scopeifyScope(getProjectScope(npm.prefix))

        // at this point the configs are all set.
        // go ahead and spin up the registry client.
        lazyProperty(npm, 'registry', function () {
          registryLoaded = true
          var RegClient = require('npm-registry-client')
          var registry = new RegClient(clientConfig(npm, log, npm.config))
          registry.version = npm.version
          registry.refer = registryRefer
          return registry
        })

        startMetrics()

        return cb(null, npm)
      })
    })
  }

  Object.defineProperty(npm, 'prefix',
    {
      get: function () {
        return npm.config.get('global') ? npm.globalPrefix : npm.localPrefix
      },
      set: function (r) {
        var k = npm.config.get('global') ? 'globalPrefix' : 'localPrefix'
        npm[k] = r
        return r
      },
      enumerable: true
    })

  Object.defineProperty(npm, 'bin',
    {
      get: function () {
        if (npm.config.get('global')) return npm.globalBin
        return path.resolve(npm.root, '.bin')
      },
      enumerable: true
    })

  Object.defineProperty(npm, 'globalBin',
    {
      get: function () {
        var b = npm.globalPrefix
        if (process.platform !== 'win32') b = path.resolve(b, 'bin')
        return b
      }
    })

  Object.defineProperty(npm, 'dir',
    {
      get: function () {
        if (npm.config.get('global')) return npm.globalDir
        return path.resolve(npm.prefix, 'node_modules')
      },
      enumerable: true
    })

  Object.defineProperty(npm, 'globalDir',
    {
      get: function () {
        return (process.platform !== 'win32')
          ? path.resolve(npm.globalPrefix, 'lib', 'node_modules')
          : path.resolve(npm.globalPrefix, 'node_modules')
      },
      enumerable: true
    })

  Object.defineProperty(npm, 'root',
    { get: function () { return npm.dir } })

  Object.defineProperty(npm, 'cache',
    { get: function () { return npm.config.get('cache') },
      set: function (r) { return npm.config.set('cache', r) },
      enumerable: true
    })

  var tmpFolder
  var rand = require('crypto').randomBytes(4).toString('hex')
  Object.defineProperty(npm, 'tmp',
    {
      get: function () {
        if (!tmpFolder) tmpFolder = 'npm-' + process.pid + '-' + rand
        return path.resolve(npm.config.get('tmp'), tmpFolder)
      },
      enumerable: true
    })

  // the better to repl you with
  Object.getOwnPropertyNames(npm.commands).forEach(function (n) {
    if (npm.hasOwnProperty(n) || n === 'config') return

    Object.defineProperty(npm, n, { get: function () {
      return function () {
        var args = Array.prototype.slice.call(arguments, 0)
        var cb = defaultCb

        if (args.length === 1 && Array.isArray(args[0])) {
          args = args[0]
        }

        if (typeof args[args.length - 1] === 'function') {
          cb = args.pop()
        }
        npm.commands[n](args, cb)
      }
    },
    enumerable: false,
    configurable: true })
  })

  if (require.main === module) {
    require('../bin/npm-cli.js')
  }

  function scopeifyScope (scope) {
    return (!scope || scope[0] === '@') ? scope : ('@' + scope)
  }

  function getProjectScope (prefix) {
    try {
      var pkg = JSON.parse(fs.readFileSync(path.join(prefix, 'package.json')))
      if (typeof pkg.name !== 'string') return ''
      var sep = pkg.name.indexOf('/')
      if (sep === -1) return ''
      return pkg.name.slice(0, sep)
    } catch (ex) {
      return ''
    }
  }
})()