1const Arborist = require('../')
2
3const printTree = require('./lib/print-tree.js')
4const log = require('./lib/logging.js')
5
6const Vuln = require('../lib/vuln.js')
7const printReport = report => {
8  for (const vuln of report.values()) {
9    log.info(printVuln(vuln))
10  }
11  if (report.topVulns.size) {
12    log.info('\n# top-level vulnerabilities')
13    for (const vuln of report.topVulns.values()) {
14      log.info(printVuln(vuln))
15    }
16  }
17}
18
19const printVuln = vuln => {
20  return {
21    __proto__: { constructor: Vuln },
22    name: vuln.name,
23    issues: [...vuln.advisories].map(a => printAdvisory(a)),
24    range: vuln.simpleRange,
25    nodes: [...vuln.nodes].map(node => `${node.name} ${node.location || '#ROOT'}`),
26    ...(vuln.topNodes.size === 0 ? {} : {
27      topNodes: [...vuln.topNodes].map(node => `${node.location || '#ROOT'}`),
28    }),
29  }
30}
31
32const printAdvisory = a => `${a.title}${a.url ? ' ' + a.url : ''}`
33
34module.exports = (options, time) => {
35  const arb = new Arborist(options)
36  return arb
37    .audit(options)
38    .then(time)
39    .then(async ({ timing, result: tree }) => {
40      if (options.fix) {
41        printTree(tree)
42      }
43      printReport(arb.auditReport)
44      if (tree.meta && options.save) {
45        await tree.meta.save()
46      }
47      return options.fix
48        ? `resolved ${tree.inventory.size} deps in ${timing.seconds}`
49        : `done in ${timing.seconds}`
50    })
51}
52