-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
396 lines (392 loc) · 11.4 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
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
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import meta from '@thebespokepixel/meta';
import { format, inspect } from 'node:util';
import { Console } from 'node:console';
import termNG from 'term-ng';
import chalk from 'chalk';
import sparkles from 'sparkles';
import { bespokeTimeFormat } from '@thebespokepixel/time';
/**
* Message routing and formatting matrix.
* @private
* @type {object}
* @param {Stream} sOut Output stream.
* @param {Stream} sErr Error stream.
* @returns {object} Routing matrix object.
*/
function matrix(sOut, sError) {
return {
debug: {
level: 5,
stream: sOut,
/**
* Format the debug message.
* @private
* @param {string} pfix Message prefix.
* @param {string} message The message body.
* @return {string} The formatted mesage.
*/
format: (pfix, message) => `${pfix}${chalk.dim(message)}`,
},
info: {
level: 4,
stream: sOut,
/**
* Format the info message.
* @private
* @param {string} pfix Message prefix.
* @param {string} message The message body.
* @return {string} The formatted mesage.
*/
format: (pfix, message) => `${pfix}${message}`,
},
log: {
level: 3,
stream: sOut,
/**
* Format the log message.
* @private
* @param {string} pfix Message prefix.
* @param {string} message The message body.
* @return {string} The formatted mesage.
*/
format: (pfix, message) => `${pfix}${message}`,
},
warn: {
level: 2,
stream: sError,
/**
* Format the warn message.
* @private
* @param {string} pfix Message prefix.
* @param {string} message The message body.
* @return {string} The formatted mesage.
*/
format: (pfix, message) => `${pfix}${chalk.yellow(message)}`,
},
error: {
level: 1,
stream: sError,
/**
* Format the error message.
* @private
* @param {string} pfix Message prefix.
* @param {string} message The message body.
* @return {string} The formatted mesage.
*/
format: (pfix, message) => `${pfix}${chalk.red(`ERROR: ${message}`)}`,
},
critical: {
level: 0,
stream: sError,
/**
* Format the critical message.
* @private
* @param {string} pfix Message prefix.
* @param {string} message The message body.
* @return {string} The formatted mesage.
*/
format: (pfix, message) => `${pfix}${chalk.bold.red(`CRITICAL: ${message}`)}`,
},
panic: {
level: 0,
stream: sError,
/**
* Format the panic message.
* @private
* @param {string} pfix Message prefix.
* @param {string} message The message body.
* @return {string} The formatted mesage.
*/
format: (pfix, message) => `${pfix}${chalk.bold.red(`PANIC: ${message}`)}`,
},
emergency: {
level: 0,
stream: sError,
/**
* Format the emergency message.
* @private
* @param {string} pfix Message prefix.
* @param {string} message The message body.
* @return {string} The formatted mesage.
*/
format: (pfix, message) => `${pfix}${chalk.bold.red(`EMERGENCY: ${message}`)}`,
},
}
}
/**
* Generate a verbosity console
* @param {object} options - Configuration options.
* @param {stream.writable} options.outStream - Stream to write normal output
* @param {stream.writable} options.errorStream - Stream to write error output
* @param {number} options.verbosity - The verboseness of output:
* 0: Mute
* 1: Errors
* 2: Notice
* 3: Log
* 4: Info
* 5: Debug
* @param {string} options.timestamp - Timestamp format.
* @param {string} options.namespace - Sparkles namespace to emit events to.
* @param {boolean} options.global - Should changes to verbosity be made globally?
* @param {string} options.prefix - Logging message prefix.
* @return {Verbosity} Verbosity's console object.
*/
class Verbosity extends Console {
constructor({
outStream,
errorStream,
verbosity = 3,
timestamp,
namespace,
global,
prefix,
} = {}) {
const sOut = (ws => {
if (!ws.writable) {
throw new Error('Provided output stream must be writable')
}
return ws
})(outStream ? outStream : process.stdout);
const sError = (ws => {
if (!ws.writable) {
throw new Error('Provided error stream must be writable')
}
return ws
})(errorStream ? errorStream : sOut);
super(sOut, sError);
this.willEmit = Boolean(namespace);
this.globalControl = Boolean(global);
this.timeFormatter = (ts => ts
? () => `[${chalk.dim(bespokeTimeFormat(ts))}] `
: () => ''
)(timestamp);
this.prefixFormatter = (pfix => pfix
? () => `[${pfix}] `
: () => ''
)(prefix);
this._stdout = sOut;
this._stderr = sError;
this.threshold = verbosity;
this.globalVerbosityController = this.globalControl && sparkles('verbosityGlobal');
this.emitter = this.willEmit && sparkles(namespace);
this.matrix = matrix(sOut, sError);
if (this.globalControl) {
this.globalVerbosityController.on('level', ({level}) => {
this.threshold = level;
});
}
}
/**
* Set the current verbosity.
* @param {number|string} level - The current level (0 to 5) or level name.
* @return {number} The current verboseness (0 to 5).
*/
verbosity(level) {
if (level) {
level = (typeof level === 'string') ? this.matrix[level].level : level;
if (level < 6) {
this.threshold = level;
}
if (this.globalControl) {
this.globalVerbosityController.emit('level', {level});
}
}
return this.threshold
}
/**
* Can the requested logging level be written at this time.
* @param {number} level - The requested level (0 to 5).
* @return {boolean} `true` if ok to write.
*/
canWrite(level) {
level = (typeof level === 'string') ? this.matrix[level] : level;
return this.threshold >= level
}
/**
* Route message and emit if required.
* @private
* @param {number} level Source logging level
* @param {string} message Message to log
* @param {...string} a Additional arguments to log
*/
route(level, message, ...a) {
message = (a.length > 0) ? format(message, ...a) : message;
if (this.willEmit) {
this.emitter.emit(level, message);
}
if (this.threshold >= this.matrix[level].level) {
const pfix = `${this.timeFormatter()}${this.prefixFormatter()}`;
this.matrix[level].stream.write(`${this.matrix[level].format(pfix, message)}\n`);
}
}
/**
* Log a debug message. (Level 5)
* @param {string} message The debug message to log.
* @param {...string} args Additional arguments to log.
*/
debug(message, ...args) {
this.route('debug', message, ...args);
}
/**
* Log an info message. (Level 4)
* @param {string} message The info message to log.
* @param {...string} args Additional arguments to log.
*/
info(message, ...args) {
this.route('info', message, ...args);
}
/**
* Log a normal message. (Level 3)
* @param {string} message The normal message to log.
* @param {...string} args Additional arguments to log.
*/
log(message, ...args) {
this.route('log', message, ...args);
}
/**
* Log a warning message. (Level 2)
* @param {string} message The warning message to log.
* @param {...string} args Additional arguments to log.
*/
warn(message, ...args) {
this.route('warn', message, ...args);
}
/**
* Log an error message. (Level 1)
* @param {string} message The error message to log.
* @param {...string} args Additional arguments to log.
*/
error(message, ...args) {
this.route('error', message, ...args);
}
/**
* Log a critical error message, if something breaks. (Level 1)
* @param {string} message The critical error message to log.
* @param {...string} args Additional arguments to log.
*/
critical(message, ...args) {
this.route('critical', message, ...args);
}
/**
* Log a panic error message if something unexpected happens. (Level 1)
* @param {string} message The panic message to log.
* @param {...string} args Additional arguments to log.
*/
panic(message, ...args) {
this.route('panic', message, ...args);
}
/**
* Log a emergency message, for when something needs emergency attention. (Level 1)
* @param {string} message The debug message to log.
* @param {...string} args Additional arguments to log.
*/
emergency(message, ...args) {
this.route('emergency', message, ...args);
}
/**
* As console.dir, but defaults to colour (if appropriate) and zero depth.
* @param {object} object The Object to print.
* @param {object} options As console.dir options object.
*/
dir(object, options = {}) {
const {depth = 0, colors = termNG.color.basic} = options;
options.depth = depth;
options.colors = colors;
this._stdout.write(format(inspect(object, options)));
}
/**
* Pretty prints object, similar to OS X's plutil -p. Defaults to zero depth.
* @param {object} object The Object to print.
* @param {number} depth How many object levels to print.
* @param {boolean} color Print output in color, if supported.
* @example
* console.pretty(console)
*
* // Outputs:
* Object: VerbosityMatrix
* critical ▸ [Function]
* error ▸ [Function ▸ bound ]
* warn ▸ [Function ▸ bound ]
* log ▸ [Function ▸ bound ]
* info ▸ [Function ▸ bound ]
* debug ▸ [Function]
* canWrite ▸ [Function]
* ...
*/
pretty(object, depth = 0, color = true) {
this._stdout.write(format('Content: %s\n', inspect(object, {
depth,
colors: color && termNG.color.basic,
})
.slice(0, -1)
.replace(/^{/, 'Object\n ')
.replace(/^\[/, 'Array\n ')
.replace(/^(\w+) {/, '$1')
.replace(/(\w+):/g, '$1 ▸')
.replace(/,\n/g, '\n'),
));
}
/**
* Helper function for pretty printing a summary of the current 'yargs' options.
*
* Only prints 'long options', `._` as 'arguments' and `$0` as 'self'.
* @param {object} object The Yargs argv object to print.
* @param {boolean} color Print output in color, if supported.
* @example
* console.yargs(yargs)
*
* // Outputs:
* Object (yargs):
* left ▸ 2
* right ▸ 2
* mode ▸ 'hard'
* encoding ▸ 'utf8'
* ...
* self ▸ '/usr/local/bin/truwrap'
*/
yargs(object, color = true) {
const parsed = {};
for (const key_ of Object.keys(object)) {
const value = object[key_];
switch (key_) {
case '_':
if (value.length > 0) {
parsed.arguments = value.join(' ');
}
break
case '$0':
parsed.self = value;
break
default:
if (key_.length > 1) {
parsed[key_] = value;
}
}
}
this._stdout.write(format('Options (yargs):\n %s\n', inspect(parsed, {
colors: color && termNG.color.basic,
})
.slice(2, -1)
.replace(/(\w+):/g, '$1 ▸')
.replace(/,\n/g, '\n')));
}
}
const metadata = meta(dirname(fileURLToPath(import.meta.url)));
/**
* Create a new Verbosity object.
* @param {object} options Options to pass to the factory.
* @return {Verbosity} Verbosity's console object.
*/
function createConsole(options) {
return new Verbosity(options)
}
/**
* Return the modules version metadata.
* @function
* @param {number} level Version format required.
* @return {string} The version string.
*/
const getVersion = level => metadata.version(level);
export { Verbosity, createConsole, getVersion };