-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·115 lines (103 loc) · 2.46 KB
/
index.js
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
// Imports
const {Transform} = require('caterpillar')
/**
Convert human readable Caterpillar entries into browser compatible entries
Extends http://rawgit.com/bevry/caterpillar/master/docs/index.html#Transform
@extends caterpillar.Transform
@example
const logger = require('caterpillar').create()
logger.pipe(require('caterpillar-human').create()).pipe(require('caterpillar-browser').create())
logger.log('info', 'some', {data: 'oh yeah'}, 42)
*/
class Browser extends Transform {
/**
Get the initial configuration.
@returns {Object}
*/
getInitialConfig () {
return {
color: true,
write: true,
styles: {
red: {
start: 31,
end: 39,
value: 'color:red'
},
yellow: {
start: 33,
end: 39,
value: 'color:orange'
},
green: {
start: 32,
end: 39,
value: 'color:green'
},
bright: {
start: 1,
end: 22,
value: 'font-weight:bold'
},
dim: {
start: 2,
end: 22,
value: 'color:lightGray'
},
italic: {
start: 3,
end: 23,
value: 'font-style:italic'
},
underline: {
start: 4,
end: 24,
value: 'text-decoration:underline'
}
}
}
}
/**
Convert a human readable Caterpillar entry into a format that browser consoles can understand.
And if the `write` config property is `true` (it is by default), write the result to the browser console.
@param {string} message
@returns {string}
*/
format (message /* :string */ ) {
// Prepare
const {color, styles, write} = this.getConfig()
// Replace caterpillar-human formatted entry
const args = []
const result = message.replace(/\u001b\[([0-9]+)m(.+?)\u001b\[([0-9]+)m/g, function (match, start, content, end) {
// Check
if ( color === false ) return content
// Prepare
let matchedStyle, style
// Find the matcing style for this combination
for ( const key in styles ) {
if ( styles.hasOwnProperty(key) ) {
style = styles[key]
if ( String(style.start) === String(start) && String(style.end) === String(end) ) {
matchedStyle = style
break
}
}
}
// Check
if ( !matchedStyle ) return content
// Push the style
args.push(style.value)
args.push(content)
args.push('color:default; font:default; text-decoration:default')
return '%c%s%c'
})
// Final format
const parts = [result.trim()].concat(args)
// Write
if ( write ) console.log(...parts)
// Return
return parts
}
}
// Export
module.exports = Browser