Welcome to mirror list, hosted at ThFree Co, Russian Federation.

view.js « lib « npm « deps - github.com/nodejs/node.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: bc9a13d85dd9d0c620e0972640d22987b02b2b45 (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
// npm view [pkg [pkg ...]]

const byteSize = require('byte-size')
const color = require('ansicolors')
const columns = require('cli-columns')
const log = require('npmlog')
const npa = require('npm-package-arg')
const npm = require('./npm.js')
const { packument } = require('pacote')
const path = require('path')
const { inspect, promisify } = require('util')
const relativeDate = require('tiny-relative-date')
const semver = require('semver')
const style = require('ansistyles')
const usageUtil = require('./utils/usage')

const fs = require('fs')
const readFile = promisify(fs.readFile)
const jsonParse = require('json-parse-even-better-errors')
const readJson = async file => jsonParse(await readFile(file, 'utf8'))

const usage = usageUtil(
  'view',
  'npm view [<@scope>/]<pkg>[@<version>] [<field>[.subfield]...]'
)

const cmd = (args, cb) => view(args).then(() => cb()).catch(cb)

const completion = async (opts, cb) => {
  if (opts.conf.argv.remain.length <= 2) {
    // There used to be registry completion here, but it stopped
    // making sense somewhere around 50,000 packages on the registry
    return cb()
  }
  // have the package, get the fields
  const config = { ...npm.flatOptions, fullMetadata: true, preferOnline: true }
  const { defaultTag } = config
  const spec = npa(opts.conf.argv.remain[2])
  const pckmnt = await packument(spec, config)
  const dv = pckmnt.versions[pckmnt['dist-tags'][defaultTag]]
  pckmnt.versions = Object.keys(pckmnt.versions).sort(semver.compareLoose)
  const fields = getFields(pckmnt).concat(getFields(dv))
  return cb(null, fields)

  function getFields (d, f, pref) {
    f = f || []
    if (!d)
      return f
    pref = pref || []
    Object.keys(d).forEach(function (k) {
      if (k.charAt(0) === '_' || k.indexOf('.') !== -1)
        return
      const p = pref.concat(k).join('.')
      f.push(p)
      if (Array.isArray(d[k])) {
        d[k].forEach(function (val, i) {
          const pi = p + '[' + i + ']'
          if (val && typeof val === 'object')
            getFields(val, f, [p])
          else
            f.push(pi)
        })
        return
      }
      if (typeof d[k] === 'object')
        getFields(d[k], f, [p])
    })
    return f
  }
}

const view = async args => {
  if (!args.length)
    args = ['.']

  const opts = { ...npm.flatOptions, preferOnline: true, fullMetadata: true }
  const pkg = args.shift()
  let nv
  if (/^[.]@/.test(pkg))
    nv = npa.resolve(null, pkg.slice(2))
  else
    nv = npa(pkg)

  const name = nv.name
  const local = (name === '.' || !name)

  if (opts.global && local)
    throw new Error('Cannot use view command in global mode.')

  if (local) {
    const dir = npm.prefix
    const manifest = await readJson(path.resolve(dir, 'package.json'))
    if (!manifest.name)
      throw new Error('Invalid package.json, no "name" field')
    const p = manifest.name
    nv = npa(p)
    if (pkg && ~pkg.indexOf('@'))
      nv.rawSpec = pkg.split('@')[pkg.indexOf('@')]

    await fetchAndRead(nv, args, opts)
  } else
    await fetchAndRead(nv, args, opts)
}

const fetchAndRead = async (nv, args, opts) => {
  // get the data about this package
  let version = nv.rawSpec || npm.flatOptions.defaultTag

  const pckmnt = await packument(nv, opts)

  if (pckmnt['dist-tags'] && pckmnt['dist-tags'][version])
    version = pckmnt['dist-tags'][version]

  if (pckmnt.time && pckmnt.time.unpublished) {
    const u = pckmnt.time.unpublished
    const er = new Error('Unpublished by ' + u.name + ' on ' + u.time)
    er.statusCode = 404
    er.code = 'E404'
    er.pkgid = pckmnt._id
    throw er
  }

  const results = []
  const versions = pckmnt.versions || {}
  pckmnt.versions = Object.keys(versions).sort(semver.compareLoose)
  if (!args.length)
    args = ['']

  // remove readme unless we asked for it
  if (args.indexOf('readme') === -1)
    delete pckmnt.readme

  Object.keys(versions).forEach(function (v) {
    if (semver.satisfies(v, version, true)) {
      args.forEach(arg => {
        // remove readme unless we asked for it
        if (args.indexOf('readme') !== -1)
          delete versions[v].readme

        results.push(showFields(pckmnt, versions[v], arg))
      })
    }
  })
  let retval = results.reduce(reducer, {})

  if (args.length === 1 && args[0] === '') {
    retval = cleanBlanks(retval)
    log.silly('view', retval)
  }

  if (
    !opts.json &&
    args.length === 1 &&
    args[0] === ''
  ) {
    // general view
    pckmnt.version = version
    await Promise.all(
      results.map((v) => prettyView(pckmnt, v[Object.keys(v)[0]][''], opts))
    )
    return retval
  } else {
    // view by field name
    await printData(retval, pckmnt._id, opts)
    return retval
  }
}

const prettyView = async (packument, manifest, opts) => {
  // More modern, pretty printing of default view
  const unicode = opts.unicode
  const tags = []

  Object.keys(packument['dist-tags']).forEach((t) => {
    const version = packument['dist-tags'][t]
    tags.push(`${style.bright(color.green(t))}: ${version}`)
  })
  const unpackedSize = manifest.dist.unpackedSize &&
    byteSize(manifest.dist.unpackedSize)
  const licenseField = manifest.license || 'Proprietary'
  const info = {
    name: color.green(manifest.name),
    version: color.green(manifest.version),
    bins: Object.keys(manifest.bin || {}).map(color.yellow),
    versions: color.yellow(packument.versions.length + ''),
    description: manifest.description,
    deprecated: manifest.deprecated,
    keywords: (packument.keywords || []).map(color.yellow),
    license: typeof licenseField === 'string'
      ? licenseField
      : (licenseField.type || 'Proprietary'),
    deps: Object.keys(manifest.dependencies || {}).map((dep) => {
      return `${color.yellow(dep)}: ${manifest.dependencies[dep]}`
    }),
    publisher: manifest._npmUser && unparsePerson({
      name: color.yellow(manifest._npmUser.name),
      email: color.cyan(manifest._npmUser.email),
    }),
    modified: !packument.time ? undefined
    : color.yellow(relativeDate(packument.time[packument.version])),
    maintainers: (packument.maintainers || []).map((u) => unparsePerson({
      name: color.yellow(u.name),
      email: color.cyan(u.email),
    })),
    repo: (
      manifest.bugs && (manifest.bugs.url || manifest.bugs)
    ) || (
      manifest.repository && (manifest.repository.url || manifest.repository)
    ),
    site: (
      manifest.homepage && (manifest.homepage.url || manifest.homepage)
    ),
    tags,
    tarball: color.cyan(manifest.dist.tarball),
    shasum: color.yellow(manifest.dist.shasum),
    integrity: manifest.dist.integrity && color.yellow(manifest.dist.integrity),
    fileCount: manifest.dist.fileCount && color.yellow(manifest.dist.fileCount),
    unpackedSize: unpackedSize && color.yellow(unpackedSize.value) + ' ' + unpackedSize.unit,
  }
  if (info.license.toLowerCase().trim() === 'proprietary')
    info.license = style.bright(color.red(info.license))
  else
    info.license = color.green(info.license)

  console.log('')
  console.log(
    style.underline(style.bright(`${info.name}@${info.version}`)) +
    ' | ' + info.license +
    ' | deps: ' + (info.deps.length ? color.cyan(info.deps.length) : color.green('none')) +
    ' | versions: ' + info.versions
  )
  info.description && console.log(info.description)
  if (info.repo || info.site)
    info.site && console.log(color.cyan(info.site))

  const warningSign = unicode ? ' ⚠️ ' : '!!'
  info.deprecated && console.log(
    `\n${style.bright(color.red('DEPRECATED'))}${
      warningSign
    } - ${info.deprecated}`
  )

  if (info.keywords.length) {
    console.log('')
    console.log('keywords:', info.keywords.join(', '))
  }

  if (info.bins.length) {
    console.log('')
    console.log('bin:', info.bins.join(', '))
  }

  console.log('')
  console.log('dist')
  console.log('.tarball:', info.tarball)
  console.log('.shasum:', info.shasum)
  info.integrity && console.log('.integrity:', info.integrity)
  info.unpackedSize && console.log('.unpackedSize:', info.unpackedSize)

  const maxDeps = 24
  if (info.deps.length) {
    console.log('')
    console.log('dependencies:')
    console.log(columns(info.deps.slice(0, maxDeps), { padding: 1 }))
    if (info.deps.length > maxDeps)
      console.log(`(...and ${info.deps.length - maxDeps} more.)`)
  }

  if (info.maintainers && info.maintainers.length) {
    console.log('')
    console.log('maintainers:')
    info.maintainers.forEach((u) => console.log('-', u))
  }

  console.log('')
  console.log('dist-tags:')
  console.log(columns(info.tags))

  if (info.publisher || info.modified) {
    let publishInfo = 'published'
    if (info.modified)
      publishInfo += ` ${info.modified}`
    if (info.publisher)
      publishInfo += ` by ${info.publisher}`
    console.log('')
    console.log(publishInfo)
  }
}

function cleanBlanks (obj) {
  const clean = {}
  Object.keys(obj).forEach(function (version) {
    clean[version] = obj[version]['']
  })
  return clean
}

function reducer (l, r) {
  if (r) {
    Object.keys(r).forEach(function (v) {
      l[v] = l[v] || {}
      Object.keys(r[v]).forEach(function (t) {
        l[v][t] = r[v][t]
      })
    })
  }

  return l
}

// return whatever was printed
function showFields (data, version, fields) {
  const o = {}
  ;[data, version].forEach(function (s) {
    Object.keys(s).forEach(function (k) {
      o[k] = s[k]
    })
  })
  return search(o, fields.split('.'), version.version, fields)
}

function search (data, fields, version, title) {
  let field
  const tail = fields
  while (!field && fields.length)
    field = tail.shift()
  fields = [field].concat(tail)
  let o
  if (!field && !tail.length) {
    o = {}
    o[version] = {}
    o[version][title] = data
    return o
  }
  let index = field.match(/(.+)\[([^\]]+)\]$/)
  if (index) {
    field = index[1]
    index = index[2]
    if (data[field] && data[field][index])
      return search(data[field][index], tail, version, title)
    else
      field = field + '[' + index + ']'
  }
  if (Array.isArray(data)) {
    if (data.length === 1)
      return search(data[0], fields, version, title)

    let results = []
    data.forEach(function (data, i) {
      const tl = title.length
      const newt = title.substr(0, tl - fields.join('.').length - 1) +
                 '[' + i + ']' + [''].concat(fields).join('.')
      results.push(search(data, fields.slice(), version, newt))
    })
    results = results.reduce(reducer, {})
    return results
  }
  if (!data[field])
    return undefined
  data = data[field]
  if (tail.length) {
    // there are more fields to deal with.
    return search(data, tail, version, title)
  }
  o = {}
  o[version] = {}
  o[version][title] = data
  return o
}

async function printData (data, name, opts) {
  const versions = Object.keys(data)
  let msg = ''
  let msgJson = []
  const includeVersions = versions.length > 1
  let includeFields

  versions.forEach(function (v) {
    const fields = Object.keys(data[v])
    includeFields = includeFields || (fields.length > 1)
    if (opts.json)
      msgJson.push({})
    fields.forEach(function (f) {
      let d = cleanup(data[v][f])
      if (fields.length === 1 && opts.json)
        msgJson[msgJson.length - 1][f] = d

      if (includeVersions || includeFields || typeof d !== 'string') {
        if (opts.json)
          msgJson[msgJson.length - 1][f] = d
        else {
          d = inspect(d, {
            showHidden: false,
            depth: 5,
            colors: npm.color,
            maxArrayLength: null,
          })
        }
      } else if (typeof d === 'string' && opts.json)
        d = JSON.stringify(d)

      if (!opts.json) {
        if (f && includeFields)
          f += ' = '
        msg += (includeVersions ? name + '@' + v + ' ' : '') +
               (includeFields ? f : '') + d + '\n'
      }
    })
  })

  if (opts.json) {
    if (msgJson.length && Object.keys(msgJson[0]).length === 1) {
      const k = Object.keys(msgJson[0])[0]
      msgJson = msgJson.map(function (m) {
        return m[k]
      })
    }
    if (msgJson.length === 1)
      msg = JSON.stringify(msgJson[0], null, 2) + '\n'
    else if (msgJson.length > 1)
      msg = JSON.stringify(msgJson, null, 2) + '\n'
  }

  // disable the progress bar entirely, as we can't meaningfully update it if
  // we may have partial lines printed.
  log.disableProgress()

  // only log if there is something to log
  if (msg !== '')
    console.log(msg.trim())
}

function cleanup (data) {
  if (Array.isArray(data))
    return data.map(cleanup)

  if (!data || typeof data !== 'object')
    return data

  const keys = Object.keys(data)
  if (keys.length <= 3 &&
      data.name &&
      (keys.length === 1 ||
       (keys.length === 3 && data.email && data.url) ||
       (keys.length === 2 && (data.email || data.url))))
    data = unparsePerson(data)

  return data
}
function unparsePerson (d) {
  return d.name +
    (d.email ? ' <' + d.email + '>' : '') +
    (d.url ? ' (' + d.url + ')' : '')
}

module.exports = Object.assign(cmd, { completion, usage })