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
|
// a class to manage an inventory and set of indexes of
// a set of objects based on specific fields.
// primary is the primary index key.
// keys is the set of fields to be able to query.
const _primaryKey = Symbol('_primaryKey')
const _index = Symbol('_index')
const defaultKeys = ['name', 'license', 'funding', 'realpath', 'packageName']
const { hasOwnProperty } = Object.prototype
const debug = require('./debug.js')
class Inventory extends Map {
constructor (opt = {}) {
const { primary, keys } = opt
super()
this[_primaryKey] = primary || 'location'
this[_index] = (keys || defaultKeys).reduce((index, i) => {
index.set(i, new Map())
return index
}, new Map())
}
get primaryKey () {
return this[_primaryKey]
}
get indexes () {
return [...this[_index].keys()]
}
* filter (fn) {
for (const node of this.values()) {
if (fn(node))
yield node
}
}
add (node) {
const root = super.get('')
if (root && node.root !== root && node.root !== root.root) {
debug(() => {
throw Object.assign(new Error('adding external node to inventory'), {
root: root.path,
node: node.path,
nodeRoot: node.root.path,
})
})
return
}
const current = super.get(node[this.primaryKey])
if (current) {
if (current === node)
return
this.delete(current)
}
super.set(node[this.primaryKey], node)
for (const [key, map] of this[_index].entries()) {
// if the node has the value, but it's false, then use that
const val_ = hasOwnProperty.call(node, key) ? node[key]
: node[key] || (node.package && node.package[key])
const val = typeof val_ === 'string' ? val_
: !val_ || typeof val_ !== 'object' ? val_
: key === 'license' ? val_.type
: key === 'funding' ? val_.url
: /* istanbul ignore next - not used */ val_
const set = map.get(val) || new Set()
set.add(node)
map.set(val, set)
}
}
delete (node) {
if (!this.has(node))
return
super.delete(node[this.primaryKey])
for (const [key, map] of this[_index].entries()) {
const val = node[key] !== undefined ? node[key]
: (node[key] || (node.package && node.package[key]))
const set = map.get(val)
if (set) {
set.delete(node)
if (set.size === 0)
map.delete(node[key])
}
}
}
query (key, val) {
const map = this[_index].get(key)
return map && (arguments.length === 2 ? map.get(val) : map.keys()) ||
new Set()
}
has (node) {
return super.get(node[this.primaryKey]) === node
}
set (k, v) {
throw new Error('direct set() not supported, use inventory.add(node)')
}
}
module.exports = Inventory
|