codekingpro/portable-devtools
115k
1// The tracker class is intentionally as naive as possible. it is just
2// an ergonomic wrapper around process.emit('progress', ...)
3const EE = require('events')
4class Tracker extends EE {
5 constructor (name, key, total) {
6 super()
7 if (!name) {
8 throw new Error('proggy: Tracker needs a name')
9 }
10
11 if (typeof key === 'number' && !total) {
12 total = key
13 key = null
14 }
15
16 if (!total) {
17 total = 100
18 }
19
20 if (!key) {
21 key = name
22 }
23
24 this.done = false
25 this.name = name
26 this.key = key
27 this.value = 0
28 this.total = total
29 }
30
31 finish (metadata = {}) {
32 this.update(this.total, this.total, metadata)
33 }
34
35 update (value, total, metadata) {
36 if (!metadata) {
37 if (total && typeof total === 'object') {
38 metadata = total
39 } else {
40 metadata = {}
41 }
42 }
43 if (typeof total !== 'number') {
44 total = this.total
45 }
46
47 if (this.done) {
48 const msg = `proggy: updating completed tracker: ${JSON.stringify(this.key)}`
49 throw new Error(msg)
50 }
51 this.value = value
52 this.total = total
53 const done = this.value >= this.total
54 process.emit('progress', this.key, {
55 ...metadata,
56 name: this.name,
57 key: this.key,
58 value,
59 total,
60 done,
61 })
62 if (done) {
63 this.done = true
64 this.emit('done')
65 }
66 }
67}
68module.exports = Tracker
69 